dsh-sweeper 0.0.0-stage → 1.4.1

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.
package/lib/deep.js ADDED
@@ -0,0 +1,695 @@
1
+ /**
2
+ * dsh-sweeper · deep pass (per-conversation model review).
3
+ *
4
+ * A conversation that has been idle for a week still remembers what it was
5
+ * doing: which script was a throwaway probe, which file was the deliverable.
6
+ * The rule-based scan cannot know that, so this module feeds a compact digest
7
+ * of ONE conversation — its own tool calls, its own leftovers — to the user's
8
+ * configured model and asks which of those leftovers nobody needs anymore.
9
+ *
10
+ * Boundaries (the plugin never crosses them):
11
+ * • conversation logs are opened read-only through `sessionPersistence`;
12
+ * • the digest is built from tool names, targets and short excerpts, and the
13
+ * request carries a synthetic session id so nothing is written back;
14
+ * • the model only ever answers with ids from the candidate list we handed
15
+ * it, and every id is re-validated on disk before it can be shown.
16
+ */
17
+
18
+ import { randomUUID } from 'node:crypto'
19
+ import { _internal as scanRules } from './scan.js'
20
+ import { lstatSync, readFileSync, statSync } from 'node:fs'
21
+ import { WIN, normKey, isInside, baseOf, joinPath } from './paths.js'
22
+ import { dshHome, trashRoot, rejectionReason as defaultRejection } from './trash.js'
23
+ import { auditWithTools, looksLikePath, insideWorkspace } from './deep-agent.js'
24
+
25
+ const PAGE = 2000
26
+ const WEEK = 7 * 24 * 60 * 60 * 1000
27
+ const DAY = 24 * 60 * 60 * 1000
28
+
29
+ const MAX_SESSIONS = 24
30
+ const MAX_CANDIDATES = 40
31
+ const MAX_DIGEST_CHARS = 12_000
32
+ const MAX_TOOL_LINES = 22
33
+ const MAX_ASK = 900
34
+ const MAX_ANSWER = 1_400
35
+ const MAX_TOKENS = 3_000
36
+ const TIMEOUT_MS = 150_000
37
+ const CONCURRENCY = 4
38
+
39
+ const PRODUCER_TOOLS = new Set(['write', 'ops_write_file', 'edit', 'ops_edit_file'])
40
+ const PATH_ARGS = ['file_path', 'path', 'source_path', 'target_path', 'output_path', 'dest', 'files']
41
+ const SPILL_RE = /[A-Za-z]:[\\/][^\s"'<>|*?]*dsh-spill-[^\s"'<>|*?]+/g
42
+ const REVIEW_SESSION_ID = randomUUID()
43
+ // A long conversation can write thousands of files; only the tail matters for
44
+ // candidates, and the array is kept per planned session in memory.
45
+ const MAX_ARTIFACTS = 4000
46
+
47
+ export const SYSTEM = [
48
+ '你是一个“工作区垃圾审计员”。你会看到一段已经结束的编程对话的摘要,以及这次对话在生产环境中留下的、目前仍然存在的文件清单。',
49
+ '你的任务:判断清单里的每个文件现在是否还需要。只能依据这份摘要,不要凭文件名臆测。',
50
+ '',
51
+ '硬性规则:',
52
+ '- 只能引用清单给出的编号;不要发明路径;不要输出任何命令或脚本;不要建议删除清单以外的东西。',
53
+ '- 以下一律判 K(保留):会话记录/聊天历史/附件、~/.dsh 内的任何东西、git 跟踪的文件、源码/配置/文档/测试/依赖清单等正式产物、用户明确要求过保留或交付的东西、你无法确定的东西。',
54
+ '- S = 可以无脑删:明显是这次对话的临时产物(探针脚本、一次性转换、截图、草稿、缓存),摘要里没有任何“之后还要用/要交付/用户想要”的迹象。',
55
+ '- O = 可选删:大概是临时产物,但摘要里有不确定因素(被文档引用、看起来像最终产物、看不出用途)。',
56
+ '- K = 必须保留:源码、配置、文档、测试、正式产物,或任何判断不了的情况。',
57
+ '',
58
+ '输出格式:每个编号一行,不要输出其它任何内容,不要加代码块,不要加前后说明:',
59
+ 'S i3 一句话理由',
60
+ 'O i7 一句话理由',
61
+ 'K i2 一句话理由',
62
+ ].join('\n')
63
+
64
+ const ms = (n) => (Number.isFinite(n) && n > 0 ? n : 0)
65
+
66
+ function idOf(snap) {
67
+ if (!snap || typeof snap !== 'object') return ''
68
+ if (typeof snap.id === 'string') return snap.id
69
+ const h = snap.header
70
+ if (h && (h.id || h.sessionId)) return h.id || h.sessionId
71
+ return ''
72
+ }
73
+
74
+ function textOf(message) {
75
+ if (!message || !Array.isArray(message.content)) return ''
76
+ let out = ''
77
+ for (const part of message.content) if (part && typeof part.text === 'string') out += part.text + '\n'
78
+ return out
79
+ }
80
+
81
+ function failMsg(d) {
82
+ const err = d && d.error
83
+ if (!err) return ''
84
+ return String(err.name || err.code || 'error').slice(0, 60)
85
+ }
86
+
87
+ /** Rough token estimate: CJK characters count as one, the rest as a quarter. */
88
+ export function estimateTokens(text) {
89
+ const s = String(text || '')
90
+ let cjk = 0
91
+ let other = 0
92
+ for (const ch of s) {
93
+ const code = ch.codePointAt(0)
94
+ if (code >= 0x2e80 && code <= 0x9fff) cjk += 1
95
+ else if (code >= 0x3000 && code <= 0x303f) cjk += 1
96
+ else if (code >= 0xff00 && code <= 0xffef) cjk += 1
97
+ else other += 1
98
+ }
99
+ return Math.ceil(cjk + other / 4)
100
+ }
101
+
102
+ function clip(text, max) {
103
+ const s = String(text || '').replace(/\s+/g, ' ').trim()
104
+ if (!s) return ''
105
+ return s.length > max ? s.slice(0, max) + '…' : s
106
+ }
107
+
108
+ async function readAll(handle, limit = 200_000) {
109
+ const events = []
110
+ let off = 0
111
+ for (;;) {
112
+ let page
113
+ try { page = await handle.read(off, PAGE) } catch { return { events, truncated: events.length > 0 } }
114
+ const list = Array.isArray(page) ? page : (page && page.events) || []
115
+ if (!list.length) return { events, truncated: false }
116
+ for (const ev of list) events.push(ev)
117
+ off += list.length
118
+ if (list.length < PAGE) return { events, truncated: false }
119
+ // Stopping at the cap means everything after this point was never seen. The
120
+ // digest has to say so, otherwise the model judges a conversation by its
121
+ // opening and the row looks like a complete read.
122
+ if (off > limit) return { events, truncated: true }
123
+ }
124
+ }
125
+
126
+ function argPaths(args, out) {
127
+ if (!args || typeof args !== 'object') return
128
+ for (const field of PATH_ARGS) {
129
+ const v = args[field]
130
+ if (typeof v === 'string') out.push(v)
131
+ else if (Array.isArray(v)) for (const x of v) if (typeof x === 'string') out.push(x)
132
+ }
133
+ }
134
+
135
+ /** Pull one conversation apart into the pieces the prompt needs. */
136
+ export async function describeSession(ctx, persistence, snapshot) {
137
+ const id = idOf(snapshot)
138
+ if (!id) return null
139
+ let handle
140
+ try { handle = await persistence.open(id, 'read') } catch (err) {
141
+ // Tell the planner this one is unreadable rather than just absent: a log
142
+ // the host cannot open is a fact worth showing, not a silent skip.
143
+ const e = new Error('unreadable session log: ' + ((err && err.message) || String(err)))
144
+ e.code = 'SWEEPER_UNREADABLE'
145
+ throw e
146
+ }
147
+ let read = { events: [], truncated: false }
148
+ try {
149
+ read = await readAll(handle)
150
+ } finally {
151
+ // planDeep runs once per cache window and opens one handle per conversation;
152
+ // not closing them would pile up file handles across refreshes.
153
+ try { await handle.close() } catch { /* the host may not expose close */ }
154
+ }
155
+ const events = read.events
156
+ if (!events.length) return null
157
+
158
+ const info = {
159
+ id, title: '', cwd: '', createdAt: 0, lastTime: 0, events: events.length,
160
+ truncated: !!read.truncated,
161
+ toolCalls: 0, tools: {}, firstAsk: '', lastAnswer: '', tail: [],
162
+ artifacts: [], spill: [], errors: 0,
163
+ }
164
+ const calls = new Map()
165
+
166
+ for (const ev of events) {
167
+ if (!ev || typeof ev !== 'object') continue
168
+ if (info.lastTime && typeof ev.time === 'number') info.lastTime = Math.max(info.lastTime, ev.time)
169
+ else if (typeof ev.time === 'number') info.lastTime = ev.time
170
+ const t = ev.type
171
+ if (t === 'session') {
172
+ info.createdAt = ms(ev.createdAt) || ms(ev.time)
173
+ info.cwd = typeof ev.cwd === 'string' ? ev.cwd : ''
174
+ info.lastTime = info.lastTime || ms(ev.createdAt)
175
+ continue
176
+ }
177
+ if (t === 'session/title') {
178
+ const d = ev.data || {}
179
+ const title = typeof d.title === 'string' ? d.title : (typeof d === 'string' ? d : '')
180
+ if (title) info.title = title.trim().slice(0, 120)
181
+ continue
182
+ }
183
+ if (t === 'user/message' && !info.firstAsk) {
184
+ const text = textOf(ev.data && ev.data.message)
185
+ if (text.trim()) info.firstAsk = clip(text, MAX_ASK)
186
+ continue
187
+ }
188
+ if (t === 'assistant/message') {
189
+ const text = textOf(ev.data && ev.data.message)
190
+ if (text.trim()) info.lastAnswer = clip(text, MAX_ANSWER)
191
+ continue
192
+ }
193
+ if (t === 'tool/call') {
194
+ const d = ev.data || {}
195
+ const name = String(d.name || '?')
196
+ info.toolCalls += 1
197
+ info.tools[name] = (info.tools[name] || 0) + 1
198
+ calls.set(String(d.callId || ''), { name, args: d.arguments })
199
+ const targets = []
200
+ try { argPaths(JSON.parse(d.arguments || '{}'), targets) } catch { /* not JSON */ }
201
+ if (PRODUCER_TOOLS.has(name)) {
202
+ for (const p of targets) {
203
+ if (info.artifacts.length < MAX_ARTIFACTS) info.artifacts.push({ path: p, tool: name, time: ms(ev.time) })
204
+ }
205
+ }
206
+ const shown = targets.slice(0, 1).map((p) => clip(p, 90))
207
+ if (name === 'ops_bash' || name === 'pwsh') {
208
+ try {
209
+ const a = JSON.parse(d.arguments || '{}')
210
+ if (typeof a.command === 'string') shown.push(clip(a.command, 90))
211
+ } catch { /* ignore */ }
212
+ }
213
+ info.tail.push({ name, text: [name, ...shown].join(' '), time: ms(ev.time) })
214
+ if (info.tail.length > 200) info.tail.shift()
215
+ continue
216
+ }
217
+ if (t === 'tool/result') {
218
+ const d = ev.data || {}
219
+ const msg = d.message || {}
220
+ if (msg.isError) info.errors += 1
221
+ const text = textOf(msg)
222
+ if (text.includes('dsh-spill-')) {
223
+ const found = text.match(SPILL_RE) || []
224
+ for (const p of found) info.spill.push({ path: p, tool: (calls.get(String(msg.toolCallId)) || {}).name || '?', time: ms(ev.time) })
225
+ }
226
+ }
227
+ }
228
+ return info
229
+ }
230
+
231
+ function blockedRoots() {
232
+ const roots = []
233
+ const home = dshHome()
234
+ if (home) roots.push(normKey(home))
235
+ const trash = trashRoot()
236
+ if (trash) roots.push(normKey(trash))
237
+ const userHome = process.env.USERPROFILE || process.env.HOME
238
+ if (userHome) roots.push(normKey(joinPath(userHome, '.agents')))
239
+ return roots.filter(Boolean)
240
+ }
241
+
242
+ /**
243
+ * Existing files this conversation produced, filtered to things a model could
244
+ * legitimately be asked about. Anything inside DSH's own home, anything the
245
+ * trash already holds, or anything we cannot stat is left out entirely — the
246
+ * model never sees it, so it can never vote for it.
247
+ */
248
+ export function candidatesOf(info, ctx = {}) {
249
+ const seen = new Set()
250
+ const out = []
251
+ const roots = blockedRoots()
252
+ void ctx
253
+
254
+ const push = (raw, kind, tool, time) => {
255
+ const key = normKey(raw)
256
+ if (!key || seen.has(key)) return
257
+ // Only artifacts that already look like scratch. Project sources and configs
258
+ // are not this pass's business: sending them spends tokens to be told "keep".
259
+ if (kind !== 'spill' && !scanRules.SCRATCH.test(key)) return
260
+ seen.add(key)
261
+ if (roots.some((r) => r && isInside(key, r))) return
262
+ // stat the path the log actually recorded: normKey lowercases on Windows,
263
+ // and the page should show the real casing (Linux/macOS are case sensitive).
264
+ const shown = String(raw || '').replace(/\//g, WIN ? '\\' : '/')
265
+ let st
266
+ try { st = statSync(shown) } catch { try { st = statSync(key) } catch { return } }
267
+ if (!st.isFile()) return
268
+ if (st.size > 50 * 1024 * 1024) return
269
+ out.push({ key, path: shown, kind, tool, time, size: st.size, mtime: st.mtimeMs })
270
+ }
271
+ for (const a of info.artifacts) push(a.path, 'written', a.tool, a.time)
272
+ for (const s of info.spill) push(s.path, 'spill', s.tool, s.time)
273
+ out.sort((a, b) => a.mtime - b.mtime)
274
+ const capped = out.slice(0, MAX_CANDIDATES)
275
+ // How many candidates this conversation actually has, so the page can say
276
+ // "40 of 63 sent" instead of quietly reviewing the first 40 and looking
277
+ // complete. Non-enumerable: the array is serialised into job rows as-is.
278
+ Object.defineProperty(capped, 'hidden', { value: out.length - capped.length, enumerable: false })
279
+ return capped
280
+ }
281
+
282
+
283
+ function ageText(time, now) {
284
+ if (!time) return '未知'
285
+ const days = Math.floor((now - time) / DAY)
286
+ return days <= 0 ? '今天' : days + ' 天'
287
+ }
288
+
289
+ function sizeText(bytes) {
290
+ if (!bytes) return '0 B'
291
+ if (bytes < 1024) return bytes + ' B'
292
+ if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
293
+ return (bytes / 1024 / 1024).toFixed(1) + ' MB'
294
+ }
295
+
296
+ /** Build the digest + candidate map for one conversation. */
297
+ export function buildDigest(info, candidates, now = Date.now(), opts = {}) {
298
+ const lines = []
299
+ lines.push('对话:' + (info.title || '(无标题)'))
300
+ if (info.cwd) lines.push('工作目录:' + info.cwd)
301
+ lines.push('时间:' + (info.createdAt ? new Date(info.createdAt).toISOString().slice(0, 10) : '?')
302
+ + ' → ' + (info.lastTime ? new Date(info.lastTime).toISOString().slice(0, 10) : '?')
303
+ + '(最后活动 ' + ageText(info.lastTime, now) + '前)')
304
+ if (info.truncated) {
305
+ lines.push('')
306
+ lines.push('注意:这段对话的事件超过 ' + info.events + ' 条,下面只覆盖了最早的部分;')
307
+ lines.push('它最近在做什么没有被读到,判断时请把这一点算进去。')
308
+ }
309
+ const tools = Object.entries(info.tools).sort((a, b) => b[1] - a[1]).slice(0, 8)
310
+ .map(([k, v]) => k + ' ' + v).join(' / ')
311
+ lines.push('工具调用:' + info.toolCalls + ' 次(' + (tools || '无') + '),其中 ' + info.errors + ' 次失败')
312
+ if (info.firstAsk) lines.push('', '用户最初的请求:' + info.firstAsk)
313
+ if (info.lastAnswer) lines.push('', '最近一次回答(可能是交付结论):' + info.lastAnswer)
314
+ if (info.tail.length) {
315
+ lines.push('', '最近 ' + Math.min(MAX_TOOL_LINES, info.tail.length) + ' 次工具调用:')
316
+ for (const step of info.tail.slice(-MAX_TOOL_LINES)) lines.push('- ' + step.text)
317
+ }
318
+ lines.push('', '这次对话留下、目前仍然存在的文件:')
319
+ if (opts.canLook) {
320
+ lines.push('- 除了下面这些,你也可以用工具查看工作目录,找清单里没有的大文件(改用绝对路径回答)')
321
+ }
322
+ if (candidates.hidden) {
323
+ lines.push('- 清单只列了前 ' + candidates.length + ' 个;这段对话还有 ' + candidates.hidden + ' 个临时文件没有列出来(不影响你判断上面的)')
324
+ }
325
+ if (!candidates.length) lines.push(opts.canLook ? '- (清单为空;请用 list_dir / find_files 查看工作目录)' : '- (没有)')
326
+ for (let i = 0; i < candidates.length; i++) {
327
+ const c = candidates[i]
328
+ lines.push('i' + (i + 1) + '. ' + c.path + ' | ' + sizeText(c.size) + ' | '
329
+ + ageText(c.mtime, now) + ' | ' + c.kind + ' | 由 ' + (c.tool || '?') + ' 产生')
330
+ }
331
+
332
+ let text = lines.join('\n')
333
+ if (text.length > MAX_DIGEST_CHARS) text = text.slice(0, MAX_DIGEST_CHARS) + '\n…(摘要已截断,未列出的文件不要判断)'
334
+ return text
335
+ }
336
+
337
+ export function parseReply(text) {
338
+ const out = { sweep: [], optional: [], keep: [], unknown: [], raw: String(text || '').slice(0, 4000) }
339
+ for (const rawLine of String(text || '').split(/\r?\n/)) {
340
+ const line = rawLine.replace(/^[\s>*\-•\d.、)]+/, '').trim()
341
+ const m = /^(S|O|K)\s*[.::]?\s*(i\d+)\b\s*(.*)$/i.exec(line)
342
+ if (!m) continue
343
+ const kind = m[1].toUpperCase()
344
+ const id = m[2].toLowerCase()
345
+ const why = m[3].replace(/^[-–—::\s]+/, '').trim().slice(0, 160)
346
+ if (kind === 'S') out.sweep.push({ id, reason: why })
347
+ else if (kind === 'O') out.optional.push({ id, reason: why })
348
+ else out.keep.push({ id, reason: why })
349
+ }
350
+ if (!out.sweep.length && !out.optional.length && !out.keep.length) out.unknown.push({ id: '', reason: 'model returned no usable line' })
351
+ return out
352
+ }
353
+
354
+ /** One conversation → one model call. */
355
+ export async function askConversation(ctx, info, candidates, opts = {}) {
356
+ const llm = typeof ctx.get === 'function' ? ctx.get('llm') : null
357
+ if (!llm || typeof llm.prepareCall !== 'function') throw new Error('the host llm service is not available')
358
+ const route = resolveRoute(ctx, opts.model)
359
+ const digest = buildDigest(info, candidates, opts.now || Date.now())
360
+ const started = Date.now()
361
+ const controller = new AbortController()
362
+ const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : TIMEOUT_MS
363
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
364
+ // A cancelled pass must also stop the calls that are already streaming,
365
+ // otherwise pressing 停止 would still burn tokens for every queued session.
366
+ const external = opts.signal
367
+ const onAbort = () => controller.abort()
368
+ if (external) {
369
+ if (external.aborted) controller.abort()
370
+ else external.addEventListener('abort', onAbort, { once: true })
371
+ }
372
+ const acc = { deltas: '', blocks: '', types: {}, finish: null, error: null }
373
+ try {
374
+ const call = await llm.prepareCall({ ...route, maxTokens: MAX_TOKENS }, controller.signal, (controls) => controls)
375
+ const messages = [{
376
+ id: randomUUID(),
377
+ role: 'user',
378
+ content: [{ type: 'text', text: digest }],
379
+ source: { kind: 'dsh-sweeper' },
380
+ }]
381
+ for await (const chunk of call.stream({
382
+ ...call.config,
383
+ messages,
384
+ system: SYSTEM,
385
+ sessionId: REVIEW_SESSION_ID,
386
+ purpose: 'sweeper-deep',
387
+ signal: controller.signal,
388
+ })) collectText(chunk, acc)
389
+ } catch (err) {
390
+ if (controller.signal.aborted) {
391
+ throw new Error(external && external.aborted
392
+ ? 'model call cancelled'
393
+ : 'model call timed out after ' + Math.round(timeoutMs / 1000) + 's')
394
+ }
395
+ throw err
396
+ } finally {
397
+ clearTimeout(timer)
398
+ if (external && typeof external.removeEventListener === 'function') external.removeEventListener('abort', onAbort)
399
+ }
400
+ const text = acc.deltas || acc.blocks
401
+ const parsed = parseReply(text)
402
+ return { parsed, digestChars: digest.length, estTokens: estimateTokens(digest), ms: Date.now() - started, trace: acc.types }
403
+ }
404
+
405
+ function collectText(chunk, acc) {
406
+ if (!chunk || typeof chunk !== 'object') return
407
+ acc.types[chunk.type] = (acc.types[chunk.type] || 0) + 1
408
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') { acc.deltas += chunk.text; return }
409
+ if (chunk.type === 'block-end' && chunk.block && chunk.block.type === 'text' && typeof chunk.block.text === 'string') acc.blocks += chunk.block.text
410
+ if (chunk.type === 'finish' && acc.finish === null) acc.finish = JSON.stringify(chunk).slice(0, 300)
411
+ if (chunk.type === 'error' && acc.error === null) acc.error = JSON.stringify(chunk).slice(0, 300)
412
+ }
413
+
414
+ export function resolveRoute(ctx, override) {
415
+ const pick = (v) => (typeof v === 'string' && v.trim() ? v.trim() : '')
416
+ if (pick(override && override.provider) && pick(override && override.model)) {
417
+ return { provider: pick(override.provider), model: pick(override.model) }
418
+ }
419
+ try {
420
+ const svc = typeof ctx.get === 'function' ? ctx.get('agentDefaultModel') : null
421
+ const cur = svc && typeof svc.currentSelection === 'function' ? svc.currentSelection() : null
422
+ if (cur && pick(cur.provider) && pick(cur.model)) return { provider: pick(cur.provider), model: pick(cur.model) }
423
+ } catch { /* fall through */ }
424
+ throw new Error('no model route: set a default model in DSH first')
425
+ }
426
+
427
+ /** session id -> workspace folder, from the registry DSH keeps for the sidebar. */
428
+ function workspaceIndex() {
429
+ const out = new Map()
430
+ try {
431
+ const raw = JSON.parse(readFileSync(joinPath(joinPath(dshHome(), 'storages'), 'workspace.json'), 'utf8'))
432
+ const tables = (raw && raw.tables) || {}
433
+ for (const ws of Object.values(tables.workspaces || {})) {
434
+ const dir = ws && typeof ws.path === 'string' ? ws.path : ''
435
+ if (!dir) continue
436
+ for (const sid of (ws.sessionIds || [])) if (sid) out.set(String(sid), dir)
437
+ }
438
+ } catch { /* no registry, no fallback */ }
439
+ return out
440
+ }
441
+
442
+ /** Sessions that are idle for at least `week` and still own files on disk. */
443
+ export async function planDeep(ctx, opts = {}) {
444
+ const persistence = ctx.get ? ctx.get('sessionPersistence') : ctx.sessionPersistence
445
+ if (!persistence) throw new Error('sessionPersistence service is not available')
446
+ const now = opts.now || Date.now()
447
+ const week = Number(opts.week) > 0 ? Number(opts.week) : 7
448
+ const cutoff = now - week * DAY
449
+
450
+ const liveIds = new Set()
451
+ const sessionsService = ctx.get ? ctx.get('sessions') : ctx.sessions
452
+ if (!sessionsService || typeof sessionsService.list !== 'function') {
453
+ // Without the live list the plugin cannot tell an idle conversation from one
454
+ // that is running right now. Planning anyway would send a live conversation
455
+ // to the model, so this fails closed instead.
456
+ throw Object.assign(new Error('the session service is not available, so which conversations are idle cannot be told'), { status: 503 })
457
+ }
458
+ try {
459
+ const arr = sessionsService.list()
460
+ for (const s of arr || []) { const lid = idOf(s); if (lid) liveIds.add(String(lid)) }
461
+ } catch (err) {
462
+ throw Object.assign(new Error('the session service failed while listing live conversations: ' + ((err && err.message) || String(err))), { status: 503 })
463
+ }
464
+
465
+ const snapshots = await persistence.list()
466
+ const list = Array.isArray(snapshots) ? snapshots : [...(snapshots || [])]
467
+ const workspaces = workspaceIndex()
468
+ const sessions = []
469
+ let skipped = 0
470
+ let unreadable = 0
471
+ let totalEstTokens = 0
472
+ for (const snap of list) {
473
+ const id = idOf(snap)
474
+ if (!id || liveIds.has(String(id))) continue
475
+ // One log this build cannot parse must not cost the user the whole plan.
476
+ let info = null
477
+ try { info = await describeSession(ctx, persistence, snap) } catch { unreadable += 1; continue }
478
+ if (!info) continue
479
+ // Older logs have no cwd in the header; the sidebar registry still knows it.
480
+ if (!info.cwd) info.cwd = workspaces.get(String(id)) || ''
481
+ const lastUsed = info.lastTime || info.createdAt
482
+ if (!lastUsed || lastUsed > cutoff) continue
483
+ const candidates = candidatesOf(info, ctx)
484
+ // With tools the model can look for artifacts the digest never listed, so a
485
+ // conversation with zero candidates is still worth a pass — that is exactly
486
+ // the case the one-prompt version mistook for "nothing to clean".
487
+ const canLook = opts.agent !== false && !!info.cwd
488
+ if (!candidates.length && !canLook) { skipped += 1; continue }
489
+ const digest = buildDigest(info, candidates, now, { canLook })
490
+ const estTokens = estimateTokens(digest) + (canLook ? 900 : 0)
491
+ totalEstTokens += estTokens
492
+ sessions.push({
493
+ id, title: info.title || baseOf(info.cwd || '') || id,
494
+ cwd: info.cwd, createdAt: info.createdAt, lastUsedAt: lastUsed,
495
+ ageDays: Math.max(0, Math.floor((now - lastUsed) / DAY)),
496
+ toolCalls: info.toolCalls,
497
+ candidates: candidates.length,
498
+ hidden: candidates.hidden || 0,
499
+ truncated: !!info.truncated,
500
+ estTokens,
501
+ _info: info,
502
+ _candidates: candidates,
503
+ })
504
+ if (sessions.length >= (opts.limit || MAX_SESSIONS)) break
505
+ }
506
+ sessions.sort((a, b) => b.candidates - a.candidates)
507
+ return { sessions, totalEstTokens, concurrency: CONCURRENCY, week, skipped, unreadable }
508
+ }
509
+
510
+ /**
511
+ * Run the per-conversation reviews with a bounded worker pool. Results arrive
512
+ * one by one through `onResult`, so the UI can paint a row as soon as its
513
+ * model call lands instead of waiting for the slowest one.
514
+ */
515
+ /**
516
+ * Bounded worker pool. Once `isStopped()` turns true no further job is
517
+ * dispatched; the ones already streaming are expected to abort themselves.
518
+ */
519
+ export async function runPool(jobs, opts = {}) {
520
+ const concurrency = Math.max(1, Math.min(Number(opts.concurrency) || CONCURRENCY, 8))
521
+ const queue = jobs.slice()
522
+ const results = new Map()
523
+ const isStopped = typeof opts.isStopped === 'function' ? opts.isStopped : () => false
524
+ let active = 0
525
+ let cancelled = 0
526
+
527
+ await new Promise((resolve) => {
528
+ const pump = () => {
529
+ if (isStopped()) { cancelled += queue.length; queue.length = 0 }
530
+ if (!queue.length && active === 0) return resolve()
531
+ while (active < concurrency && queue.length) {
532
+ const job = queue.shift()
533
+ active += 1
534
+ ;(async () => {
535
+ let payload
536
+ try {
537
+ payload = await opts.run(job)
538
+ } catch (err) {
539
+ payload = { ok: false, error: (err && err.message) || String(err) }
540
+ } finally {
541
+ active -= 1
542
+ }
543
+ results.set(job.id, payload)
544
+ try { if (opts.onResult) await opts.onResult(job, payload) } catch { /* listener must not kill the pool */ }
545
+ pump()
546
+ })()
547
+ }
548
+ }
549
+ pump()
550
+ })
551
+
552
+ return { results, cancelled }
553
+ }
554
+
555
+ export async function runDeep(ctx, sessions, opts = {}) {
556
+ const started = Date.now()
557
+ const pooled = await runPool(sessions, {
558
+ concurrency: opts.concurrency,
559
+ isStopped: () => !!(opts.signal && opts.signal.aborted),
560
+ run: async (job) => {
561
+ // Tool loop first: the model can see sizes and dig for artifacts the
562
+ // digest never listed. If the host refuses tools, fall back to the one
563
+ // prompt so a conversation still gets judged.
564
+ if (opts.agent !== false) {
565
+ try {
566
+ const digest = buildDigest(job._info, job._candidates, opts.now || Date.now())
567
+ const audited = await auditWithTools(ctx, job._info, digest, {
568
+ route: () => resolveRoute(ctx, opts.model),
569
+ signal: opts.signal,
570
+ timeoutMs: opts.timeoutMs,
571
+ maxTurns: opts.maxTurns,
572
+ maxCalls: opts.maxCalls,
573
+ deny: [dshHome(), trashRoot()],
574
+ })
575
+ const verdict = audited.verdict
576
+ return {
577
+ ok: true,
578
+ parsed: verdict,
579
+ agent: true,
580
+ turns: audited.turns,
581
+ calls: audited.calls,
582
+ ms: audited.ms,
583
+ estTokens: estimateTokens(digest) + audited.calls * 120,
584
+ digestChars: digest.length,
585
+ trace: { types: { agent: 1 }, turns: audited.turns, calls: audited.calls, text: (audited.text || '').slice(0, 600) },
586
+ }
587
+ } catch (err) {
588
+ if (opts.signal && opts.signal.aborted) throw err
589
+ if (!opts.forceAgent) { /* fall through to the single prompt */ } else throw err
590
+ }
591
+ }
592
+ return { ok: true, ...(await askConversation(ctx, job._info, job._candidates, opts)) }
593
+ },
594
+ onResult: opts.onResult,
595
+ })
596
+ return { results: pooled.results, cancelled: pooled.cancelled, ms: Date.now() - started, concurrency: Math.max(1, Math.min(Number(opts.concurrency) || CONCURRENCY, 8)) }
597
+ }
598
+
599
+ /**
600
+ * Re-check every id the model named before any of it reaches the page.
601
+ *
602
+ * The model only sees ids; this turns ids back into paths and re-reads the
603
+ * disk at answer time. Anything that no longer matches — an id we never sent,
604
+ * a file that grew, a link, something git tracks — becomes a `rejected` entry
605
+ * with a reason, never a candidate.
606
+ */
607
+ /**
608
+ * Drop the keys of files that were just restored from the trash.
609
+ *
610
+ * A restore puts a file back where it came from. If its deep/extra row stayed
611
+ * on the page, the next "clean" click would move it into the bin again — the
612
+ * restore would look like it did nothing. Both the buckets and the job rows are
613
+ * cleared here so the page and the poll agree.
614
+ */
615
+ export function forgetRestored(deep, job, paths) {
616
+ const back = new Set((paths || []).map((p) => normKey(p)))
617
+ if (!back.size) return deep
618
+ if (deep) {
619
+ deep.sweep = (deep.sweep || []).filter((it) => !back.has(it.key))
620
+ deep.optional = (deep.optional || []).filter((it) => !back.has(it.key))
621
+ for (const key of back) if (deep.byKey) deep.byKey.delete(key)
622
+ }
623
+ if (job && job.sessions) {
624
+ for (const id of job.order || []) {
625
+ const row = job.sessions.get(id)
626
+ if (row && Array.isArray(row.items)) row.items = row.items.filter((it) => !back.has(it.key))
627
+ }
628
+ }
629
+ return deep
630
+ }
631
+
632
+ export async function vetDeepResult(session, parsed, deps = {}) {
633
+ const reject = deps.rejectionReason || defaultRejection
634
+ const trackedOf = deps.gitTracked || scanRules.gitTracked
635
+ const scratch = deps.scratchRe || scanRules.SCRATCH
636
+ const statOf = deps.lstat || lstatSync
637
+ const list = Array.isArray(session._candidates) ? session._candidates : Array.isArray(session.candidates) ? session.candidates : []
638
+ const byId = new Map(list.map((c, i) => ['i' + (i + 1), c]))
639
+ const out = { sweep: [], optional: [], rejected: [] }
640
+ const seen = new Set()
641
+ for (const bucket of ['sweep', 'optional']) {
642
+ for (const p of parsed[bucket] || []) {
643
+ let c = byId.get(p.id)
644
+ if (!c) {
645
+ // The model may name a path it found with a tool rather than an id from
646
+ // the digest. Accept it only inside the conversation's own workspace.
647
+ if (!looksLikePath(p.id)) { out.rejected.push({ path: p.id || '(missing id)', reason: 'not one of the files this conversation produced' }); continue }
648
+ if (!insideWorkspace(p.id, session.cwd)) { out.rejected.push({ path: String(p.id), reason: 'outside the workspace this conversation wrote to' }); continue }
649
+ const dkey = normKey(p.id)
650
+ if (!dkey) { out.rejected.push({ path: String(p.id), reason: 'not an absolute path' }); continue }
651
+ c = { key: dkey, path: String(p.id), kind: scanRules.SCRATCH.test(dkey) ? 'scratch' : 'file', size: null, discovered: true }
652
+ }
653
+ if (seen.has(c.key)) continue
654
+ const why = await reject(c.key)
655
+ if (why) { out.rejected.push({ path: c.path, reason: why }); continue }
656
+ let st
657
+ try { st = statOf(c.key) } catch { out.rejected.push({ path: c.path, reason: 'the file is gone' }); continue }
658
+ if (!st.isFile() || st.isSymbolicLink()) { out.rejected.push({ path: c.path, reason: 'it is not a regular file' }); continue }
659
+ if (c.size !== null && st.size !== c.size) { out.rejected.push({ path: c.path, reason: 'the file changed after the deep plan' }); continue }
660
+ let tracked = 'unknown'
661
+ try { tracked = await trackedOf(c.key, new Map()) } catch { tracked = 'unknown' }
662
+ if (tracked === true) { out.rejected.push({ path: c.path, reason: 'tracked by git' }); continue }
663
+ if (tracked === 'unknown') { out.rejected.push({ path: c.path, reason: 'git could not confirm whether it is tracked' }); continue }
664
+ seen.add(c.key)
665
+ const looksTemporary = c.kind === 'spill' || scratch.test(c.key)
666
+ // A file the model had to go looking for is never "one click": it is
667
+ // exactly the case where a wrong guess costs gigabytes.
668
+ const large = st.size > 5 * 1024 * 1024
669
+ // Only the scanner earns the one-click tier. A path the model dug up gets
670
+ // a human look, even when it happens to sit in a scratch directory.
671
+ const safe = bucket === 'sweep' && looksTemporary && !large && c.kind !== 'file' && c.discovered !== true
672
+ out[bucket].push({
673
+ key: c.key,
674
+ path: c.path,
675
+ tier: safe ? 'safe' : 'unsure',
676
+ kind: c.kind === 'spill' ? 'spill' : c.kind === 'file' ? 'file' : 'scratch',
677
+ discovered: c.discovered === true,
678
+ large,
679
+ size: st.size,
680
+ mtime: st.mtimeMs,
681
+ ageDays: session.ageDays,
682
+ refs: 0,
683
+ uses: 0,
684
+ failed: false,
685
+ reasons: [(p.reason || 'model judgement').slice(0, 160)],
686
+ origin: 'deep',
687
+ session: { id: session.id, title: session.title },
688
+ })
689
+ }
690
+ }
691
+ return out
692
+ }
693
+
694
+ export const _internal = {
695
+ readAll, describeSession, candidatesOf, buildDigest, estimateTokens, parseReply, idOf, workspaceIndex, runPool, vetDeepResult }