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/LICENSE +21 -0
- package/README.md +358 -2
- package/cordis.patch.yml +3 -0
- package/icon.svg +5 -0
- package/lib/agent.js +190 -0
- package/lib/client.js +1639 -0
- package/lib/deep-agent.js +131 -0
- package/lib/deep.js +695 -0
- package/lib/fs-tools.js +198 -0
- package/lib/index.js +994 -0
- package/lib/paths.js +83 -0
- package/lib/review.js +336 -0
- package/lib/scan.js +520 -0
- package/lib/trash.js +345 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +72 -4
package/lib/scan.js
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-sweeper · static scan of tool-execution traces.
|
|
3
|
+
*
|
|
4
|
+
* Read-only: the only filesystem effects are `stat`, and (optionally) `git ls-files`.
|
|
5
|
+
* Nothing here deletes, moves, writes into a session, or touches an attachment object.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { execFile } from 'node:child_process'
|
|
9
|
+
import { readdirSync, statSync } from 'node:fs'
|
|
10
|
+
import { homedir, tmpdir } from 'node:os'
|
|
11
|
+
import { basename, dirname, extname, isAbsolute, join, sep } from 'node:path'
|
|
12
|
+
import { WIN, isAbsPath, joinPath, normKey as pathKey, isInside } from './paths.js'
|
|
13
|
+
|
|
14
|
+
const WEEK = 7 * 24 * 60 * 60 * 1000
|
|
15
|
+
const DSH_HOME_KEY = normKey(String(process.env.DSH_HOME || join(homedir(), '.dsh')))
|
|
16
|
+
const AGENTS_HOME_KEY = normKey(join(homedir(), '.agents'))
|
|
17
|
+
|
|
18
|
+
const insideDsh = (key) => isInside(key, DSH_HOME_KEY) || isInside(key, AGENTS_HOME_KEY)
|
|
19
|
+
const PAGE = 2000
|
|
20
|
+
|
|
21
|
+
const PRODUCER_TOOLS = new Set(['write', 'ops_write_file', 'edit', 'ops_edit_file'])
|
|
22
|
+
const PATH_ARGS = ['file_path', 'path', 'source_path', 'target_path', 'output_path', 'dest', 'files']
|
|
23
|
+
|
|
24
|
+
const SCRATCH = /(?:[\\/]\.scratch(?:[\\/]|$)|[\\/]tmp[\\/]|[\\/]temp[\\/]|_tmp|(?:^|[\\/])repro-|(?:^|[\\/])shot-|\.tmp$|\.bak$|__pycache__)/i
|
|
25
|
+
/** Paths that are unambiguously machine scratch space (not just "written by the agent"). */
|
|
26
|
+
const DEEP_TEMP = /(?:[\\/]\.scratch[\\/]|[\\/]tmp[\\/]|[\\/]temp[\\/]|__pycache__[\\/]|\.bak$|\.tmp$)/i
|
|
27
|
+
const SPILL = /(?:^|[\\/])dsh-spill-[^\\/]+[\\/]/i
|
|
28
|
+
const SPILL_TEXT = /(?:stored at:\s*)?((?:[A-Za-z]:[\\/]|\/)[^\r\n"]*?dsh-spill-[^\r\n"]*?\.(?:txt|log|json|md|html|xml|csv))/i
|
|
29
|
+
|
|
30
|
+
function normKey(p) {
|
|
31
|
+
return pathKey(p)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function idOf(entry) {
|
|
35
|
+
if (!entry) return null
|
|
36
|
+
if (entry.id) return entry.id
|
|
37
|
+
if (entry.sessionId) return entry.sessionId
|
|
38
|
+
const h = entry.header
|
|
39
|
+
if (h && (h.id || h.sessionId)) return h.id || h.sessionId
|
|
40
|
+
return null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function spilledBy(sessionId, spillPath) {
|
|
44
|
+
const uuid = String(sessionId || '').replace(/^session-/, '').replace(/-/g, '')
|
|
45
|
+
if (uuid.length < 12) return false
|
|
46
|
+
return String(spillPath).toLowerCase().includes('session-' + uuid.slice(0, 12).toLowerCase())
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function last2(key) {
|
|
50
|
+
const parts = key.split(WIN ? '\\' : '/').filter(Boolean)
|
|
51
|
+
return parts.slice(-2).join(WIN ? '\\' : '/')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// A relative path mentioned in a log (".scratch/probe.mjs") has to be matched
|
|
55
|
+
// against the suffix map built from normalised absolute keys. Build that key
|
|
56
|
+
// the same way `last2` does instead of assuming Windows separators and folding
|
|
57
|
+
// case everywhere: on POSIX both would make the lookup miss every time.
|
|
58
|
+
function relKey(raw) {
|
|
59
|
+
const parts = String(raw || '').split(/[\\/]+/).filter(Boolean)
|
|
60
|
+
if (parts.length < 2) return ''
|
|
61
|
+
const tail = parts.slice(-2).join(WIN ? '\\' : '/')
|
|
62
|
+
return WIN ? tail.toLowerCase() : tail
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function toks(text) {
|
|
66
|
+
const out = []
|
|
67
|
+
if (!text) return out
|
|
68
|
+
const t = text.length > 200_000 ? text.slice(0, 200_000) : text
|
|
69
|
+
const abs = /(?:[A-Za-z]:[\\/]|\/)[^\s"'<>|*?\n]{2,400}/g
|
|
70
|
+
const rel = /(?:^|[\s"'`(:=])((?:\.{0,2}[\\/])?(?:[\w.@$-]+[\\/]){1,12}[\w.@$-]+\.[A-Za-z0-9]{1,8})(?=$|[\s"'`),:;\]}])/g
|
|
71
|
+
let m
|
|
72
|
+
while ((m = abs.exec(t))) out.push({ raw: m[0], abs: true })
|
|
73
|
+
while ((m = rel.exec(t))) out.push({ raw: m[1], abs: false })
|
|
74
|
+
return out
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function textOf(ev) {
|
|
78
|
+
const d = ev && ev.data
|
|
79
|
+
if (!d) return ''
|
|
80
|
+
if (typeof d.arguments === 'string') return d.arguments
|
|
81
|
+
const msg = d.message
|
|
82
|
+
if (msg && Array.isArray(msg.content)) {
|
|
83
|
+
let s = ''
|
|
84
|
+
for (const c of msg.content) if (c && typeof c.text === 'string') s += c.text + '\n'
|
|
85
|
+
return s
|
|
86
|
+
}
|
|
87
|
+
return ''
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function forEachEvent(handle, fn) {
|
|
91
|
+
const limit = 200_000
|
|
92
|
+
let off = 0
|
|
93
|
+
for (;;) {
|
|
94
|
+
let page
|
|
95
|
+
try { page = await handle.read(off, PAGE) } catch { return }
|
|
96
|
+
const evs = Array.isArray(page) ? page : (page && page.events) || []
|
|
97
|
+
if (!evs.length) return
|
|
98
|
+
for (const ev of evs) fn(ev)
|
|
99
|
+
off += evs.length
|
|
100
|
+
if (evs.length < PAGE) return
|
|
101
|
+
if (off > limit) return
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function statOf(p) {
|
|
106
|
+
try {
|
|
107
|
+
const st = statSync(p)
|
|
108
|
+
return { exists: true, size: st.size, mtime: st.mtimeMs, dir: st.isDirectory() }
|
|
109
|
+
} catch {
|
|
110
|
+
return { exists: false, size: 0, mtime: 0, dir: false }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 'norepo' — not inside a git work tree, so there is nothing to track
|
|
115
|
+
// true — inside a work tree and tracked
|
|
116
|
+
// false — inside a work tree and untracked
|
|
117
|
+
// 'unknown' — inside a work tree but git could not answer (missing binary,
|
|
118
|
+
// permissions, timeout); the caller must protect rather than guess
|
|
119
|
+
function gitTracked(p, cache) {
|
|
120
|
+
const root = findRepo(p, cache)
|
|
121
|
+
if (!root) return 'norepo'
|
|
122
|
+
return new Promise((resolve) => {
|
|
123
|
+
const rel = p.slice(root.length).replace(/^[\\/]+/, '')
|
|
124
|
+
execFile('git', ['-C', root, 'ls-files', '--error-unmatch', '--', rel], { timeout: 3000, windowsHide: true },
|
|
125
|
+
(err) => {
|
|
126
|
+
if (!err) return resolve(true)
|
|
127
|
+
// exit code 1 is git's "pathspec did not match" — a definite "untracked".
|
|
128
|
+
// Anything else (ENOENT, EACCES, killed by timeout) means we do not know.
|
|
129
|
+
resolve(err.code === 1 ? false : 'unknown')
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function findRepo(p, cache) {
|
|
135
|
+
let dir = dirname(p)
|
|
136
|
+
const seen = []
|
|
137
|
+
for (;;) {
|
|
138
|
+
if (cache.has(dir)) { const hit = cache.get(dir); for (const s of seen) cache.set(s, hit); return hit }
|
|
139
|
+
seen.push(dir)
|
|
140
|
+
try {
|
|
141
|
+
// A worktree or submodule keeps a `.git` *file* instead of a directory.
|
|
142
|
+
// Testing isDirectory() made those look like plain folders, and every
|
|
143
|
+
// tracked file in them became a delete candidate.
|
|
144
|
+
statSync(dir + sep + '.git')
|
|
145
|
+
for (const s of seen) cache.set(s, dir)
|
|
146
|
+
return dir
|
|
147
|
+
} catch { /* keep walking */ }
|
|
148
|
+
const up = dirname(dir)
|
|
149
|
+
if (up === dir) { for (const s of seen) cache.set(s, null); return null }
|
|
150
|
+
dir = up
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* @param {object} ctx cordis context (with sessions / sessionPersistence mounted)
|
|
156
|
+
* @param {{now?: number, week?: number}} opts
|
|
157
|
+
*/
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Directory part of a scratch path, e.g.
|
|
161
|
+
* D:\OpenFuture\.scratch\shot-1.mjs -> D:\OpenFuture\.scratch
|
|
162
|
+
* ...\Temp\dsh-spill-abc\session-1\x.txt -> ...\Temp\dsh-spill-abc\session-1
|
|
163
|
+
* Used only to decide where to *look* for hints; nothing here writes.
|
|
164
|
+
*/
|
|
165
|
+
const TEMP_ROOTS = (() => {
|
|
166
|
+
const out = new Set()
|
|
167
|
+
for (const v of [tmpdir(), process.env.TEMP, process.env.TMP]) {
|
|
168
|
+
if (v) out.add(normKey(v).replace(/[\\/]+$/, ''))
|
|
169
|
+
}
|
|
170
|
+
return out
|
|
171
|
+
})()
|
|
172
|
+
|
|
173
|
+
function scratchRootOf(raw) {
|
|
174
|
+
const s = String(raw || '')
|
|
175
|
+
if (!s || s.includes('\ufffd') || s.includes('[object')) return null
|
|
176
|
+
// dsh's own spill directory is an exact, unmistakable root
|
|
177
|
+
const spill = s.match(/^(.*?[\\/]dsh-spill-[^\\/]+)[\\/]/i)
|
|
178
|
+
if (spill) return spill[1]
|
|
179
|
+
const m = s.match(/^(.*?[\\/](?:\.scratch|tmp|temp|__pycache__))[\\/]/i)
|
|
180
|
+
if (!m) return null
|
|
181
|
+
const root = m[1]
|
|
182
|
+
// never walk the whole OS temp directory: it holds other apps' files
|
|
183
|
+
if (TEMP_ROOTS.has(normKey(root).replace(/[\\/]+$/, ''))) return null
|
|
184
|
+
return root
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const HINT_LIMIT = 160
|
|
188
|
+
const HINT_DEPTH = 3
|
|
189
|
+
const HINT_SKIP = new Set(['node_modules', '.git', '.venv', 'venv', 'dist', 'build', '.next', 'target'])
|
|
190
|
+
|
|
191
|
+
/** Files that live in a scratch directory but never appeared in any session log. */
|
|
192
|
+
function collectHints(roots, artifacts, cutoff, now) {
|
|
193
|
+
const out = []
|
|
194
|
+
const seen = new Set(artifacts.keys())
|
|
195
|
+
const queue = roots.slice(0, 40).map((r) => ({ dir: r, depth: 0 }))
|
|
196
|
+
while (queue.length && out.length < HINT_LIMIT) {
|
|
197
|
+
const { dir, depth } = queue.shift()
|
|
198
|
+
let entries
|
|
199
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { continue }
|
|
200
|
+
for (const ent of entries) {
|
|
201
|
+
if (out.length >= HINT_LIMIT) break
|
|
202
|
+
if (ent.isSymbolicLink()) continue
|
|
203
|
+
const full = joinPath(dir, ent.name)
|
|
204
|
+
if (ent.isDirectory()) {
|
|
205
|
+
if (depth < HINT_DEPTH && !HINT_SKIP.has(ent.name.toLowerCase())) queue.push({ dir: full, depth: depth + 1 })
|
|
206
|
+
continue
|
|
207
|
+
}
|
|
208
|
+
if (!ent.isFile()) continue
|
|
209
|
+
const key = normKey(full)
|
|
210
|
+
if (!key || seen.has(key)) continue
|
|
211
|
+
const st = statOf(full)
|
|
212
|
+
if (!st.exists || st.dir) continue
|
|
213
|
+
if (st.mtime > cutoff) continue // still fresh, or not provably idle
|
|
214
|
+
seen.add(key)
|
|
215
|
+
out.push({
|
|
216
|
+
path: full,
|
|
217
|
+
key,
|
|
218
|
+
root: scratchRootOf(full) || dir,
|
|
219
|
+
size: st.size,
|
|
220
|
+
mtime: st.mtime,
|
|
221
|
+
ageDays: Math.floor((now - st.mtime) / 86_400_000),
|
|
222
|
+
})
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
out.sort((a, b) => b.size - a.size)
|
|
226
|
+
return out
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export async function scan(ctx, opts = {}) {
|
|
230
|
+
const started = Date.now()
|
|
231
|
+
const now = opts.now ?? Date.now()
|
|
232
|
+
const week = opts.week ?? WEEK
|
|
233
|
+
const cutoff = now - week
|
|
234
|
+
|
|
235
|
+
const persistence = ctx.get ? ctx.get('sessionPersistence') : ctx.sessionPersistence
|
|
236
|
+
if (!persistence) throw new Error('sessionPersistence service is not available')
|
|
237
|
+
const liveIds = new Set()
|
|
238
|
+
try {
|
|
239
|
+
const sessions = (ctx.get ? ctx.get('sessions') : ctx.sessions)
|
|
240
|
+
const arr = sessions && typeof sessions.list === 'function' ? sessions.list() : []
|
|
241
|
+
for (const s of arr || []) { const lid = idOf(s); if (lid) liveIds.add(String(lid)) }
|
|
242
|
+
} catch { /* live detection is best effort */ }
|
|
243
|
+
|
|
244
|
+
const snapshots = await persistence.list()
|
|
245
|
+
const list = Array.isArray(snapshots) ? snapshots : [...(snapshots || [])]
|
|
246
|
+
|
|
247
|
+
const artifacts = new Map() // key -> record
|
|
248
|
+
const suffix = new Map() // last2 -> Set<key>
|
|
249
|
+
const callMeta = new Map() // callId -> {name, ok, time, turn, step}
|
|
250
|
+
const unreadable = []
|
|
251
|
+
const stats = { sessions: 0, events: 0, toolCalls: 0, errors: 0, openJobs: 0 }
|
|
252
|
+
|
|
253
|
+
const titleOf = new Map()
|
|
254
|
+
const addArtifact = (raw, producer) => {
|
|
255
|
+
const key = normKey(raw)
|
|
256
|
+
if (!key) return null
|
|
257
|
+
let rec = artifacts.get(key)
|
|
258
|
+
if (!rec) {
|
|
259
|
+
rec = {
|
|
260
|
+
key, raw, producers: [], firstTime: producer ? producer.time : 0,
|
|
261
|
+
refCount: 0, lastRef: producer ? producer.time : 0, kind: 'other',
|
|
262
|
+
}
|
|
263
|
+
artifacts.set(key, rec)
|
|
264
|
+
const s2 = last2(key)
|
|
265
|
+
if (!suffix.has(s2)) suffix.set(s2, new Set())
|
|
266
|
+
suffix.get(s2).add(key)
|
|
267
|
+
}
|
|
268
|
+
if (producer) {
|
|
269
|
+
rec.producers.push(producer)
|
|
270
|
+
if (!rec.firstTime || producer.time < rec.firstTime) rec.firstTime = producer.time
|
|
271
|
+
}
|
|
272
|
+
return rec
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ── pass 1: producers, spill paths, job bookkeeping ─────────────────────
|
|
276
|
+
for (const snap of list) {
|
|
277
|
+
const id = idOf(snap)
|
|
278
|
+
if (!id) continue
|
|
279
|
+
let handle
|
|
280
|
+
try { handle = await persistence.open(id, 'read') } catch { unreadable.push(String(id)); continue }
|
|
281
|
+
stats.sessions++
|
|
282
|
+
const jobs = new Set()
|
|
283
|
+
const localCalls = []
|
|
284
|
+
try {
|
|
285
|
+
await forEachEvent(handle, (ev) => {
|
|
286
|
+
stats.events++
|
|
287
|
+
const type = ev && ev.type
|
|
288
|
+
const d = (ev && ev.data) || {}
|
|
289
|
+
const time = (ev && ev.time) || 0
|
|
290
|
+
if (type === 'session/title') {
|
|
291
|
+
const t = d.title || (d.message && d.message.title) || ''
|
|
292
|
+
if (typeof t === 'string' && t) titleOf.set(String(id), t)
|
|
293
|
+
} else if (type === 'tool/call') {
|
|
294
|
+
stats.toolCalls++
|
|
295
|
+
const callId = d.callId || (d.message && d.message.toolCallId) || ''
|
|
296
|
+
const meta = { name: d.name || '?', ok: true, time, turn: d.turn, step: d.step }
|
|
297
|
+
callMeta.set(String(callId), meta)
|
|
298
|
+
localCalls.push(String(callId))
|
|
299
|
+
if (PRODUCER_TOOLS.has(meta.name)) {
|
|
300
|
+
let args = {}
|
|
301
|
+
try { args = JSON.parse(d.arguments || '{}') } catch { args = {} }
|
|
302
|
+
for (const k of PATH_ARGS) {
|
|
303
|
+
const v = args[k]
|
|
304
|
+
if (typeof v === 'string' && v) {
|
|
305
|
+
addArtifact(v, { sessionId: String(id), tool: meta.name, callId: String(callId), time, turn: d.turn, step: d.step })
|
|
306
|
+
} else if (Array.isArray(v)) {
|
|
307
|
+
for (const x of v) if (typeof x === 'string') addArtifact(x, { sessionId: String(id), tool: meta.name, callId: String(callId), time, turn: d.turn, step: d.step })
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
} else if (type === 'tool/result') {
|
|
312
|
+
const msg = d.message || {}
|
|
313
|
+
const callId = String(msg.toolCallId || d.callId || '')
|
|
314
|
+
const meta = callMeta.get(callId)
|
|
315
|
+
if (meta && msg.isError) { meta.ok = false; stats.errors++ }
|
|
316
|
+
const text = textOf(ev)
|
|
317
|
+
if (text) {
|
|
318
|
+
const m = SPILL_TEXT.exec(text)
|
|
319
|
+
if (m) {
|
|
320
|
+
const p = m[1].replace(/\s+$/, '')
|
|
321
|
+
addArtifact(p, {
|
|
322
|
+
sessionId: String(id), tool: (meta && meta.name) || '?', callId,
|
|
323
|
+
time, turn: d.turn, step: d.step, spill: true,
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
} else if (type === 'job/registered') {
|
|
328
|
+
const jid = d.jobId || d.id
|
|
329
|
+
if (jid) jobs.add(String(jid))
|
|
330
|
+
} else if (type === 'job/settled') {
|
|
331
|
+
const jid = d.jobId || d.id
|
|
332
|
+
if (jid) jobs.delete(String(jid))
|
|
333
|
+
}
|
|
334
|
+
})
|
|
335
|
+
} catch (err) {
|
|
336
|
+
unreadable.push(String(id))
|
|
337
|
+
} finally {
|
|
338
|
+
try { await handle.close() } catch { /* ignore */ }
|
|
339
|
+
}
|
|
340
|
+
stats.openJobs += jobs.size
|
|
341
|
+
const title = titleOf.get(String(id))
|
|
342
|
+
if (title) for (const c of localCalls) { const m = callMeta.get(c); if (m) m.title = title }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// ── pass 2: references (any later text that names a known path) ─────────
|
|
346
|
+
for (const snap of list) {
|
|
347
|
+
const id = idOf(snap)
|
|
348
|
+
if (!id || unreadable.includes(String(id))) continue
|
|
349
|
+
let handle
|
|
350
|
+
try { handle = await persistence.open(id, 'read') } catch { continue }
|
|
351
|
+
const sid = String(id)
|
|
352
|
+
try {
|
|
353
|
+
await forEachEvent(handle, (ev) => {
|
|
354
|
+
const type = ev && ev.type
|
|
355
|
+
if (type !== 'tool/call' && type !== 'tool/result' && type !== 'assistant/message') return
|
|
356
|
+
const time = (ev && ev.time) || 0
|
|
357
|
+
const text = textOf(ev)
|
|
358
|
+
if (!text) return
|
|
359
|
+
const d = (ev && ev.data) || {}
|
|
360
|
+
const callId = String(d.callId || (d.message && d.message.toolCallId) || '')
|
|
361
|
+
// A real "use" is a later tool call that names the path as an argument
|
|
362
|
+
// (running the script, reading the file). Plain mentions inside output
|
|
363
|
+
// text still count for the 7-day protection, but not for the split.
|
|
364
|
+
const strong = type === 'tool/call' && !!callId
|
|
365
|
+
|
|
366
|
+
const bump = (k, t) => {
|
|
367
|
+
const rec = artifacts.get(k)
|
|
368
|
+
if (!rec || t <= rec.firstTime) return
|
|
369
|
+
rec.refCount++
|
|
370
|
+
if (t > rec.lastRef) { rec.lastRef = t; rec.lastRefSession = sid }
|
|
371
|
+
if (!strong) return
|
|
372
|
+
if (rec.producers.some((pr) => pr.callId === callId)) return
|
|
373
|
+
if (!rec.useCalls) rec.useCalls = new Set()
|
|
374
|
+
if (rec.useCalls.has(callId)) return
|
|
375
|
+
rec.useCalls.add(callId)
|
|
376
|
+
rec.uses = (rec.uses || 0) + 1
|
|
377
|
+
if (t > (rec.lastUse || 0)) rec.lastUse = t
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
for (const t of toks(text)) {
|
|
381
|
+
const key = t.abs ? normKey(t.raw) : null
|
|
382
|
+
if (!key) {
|
|
383
|
+
const s2 = relKey(t.raw)
|
|
384
|
+
if (!s2) continue
|
|
385
|
+
const set = suffix.get(s2)
|
|
386
|
+
if (!set) continue
|
|
387
|
+
for (const k of set) bump(k, time)
|
|
388
|
+
continue
|
|
389
|
+
}
|
|
390
|
+
if (artifacts.has(key)) bump(key, time)
|
|
391
|
+
else {
|
|
392
|
+
const s2 = last2(key)
|
|
393
|
+
const set = suffix.get(s2)
|
|
394
|
+
if (set) for (const k of set) if (k.endsWith(key) || key.endsWith(k)) bump(k, time)
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
})
|
|
398
|
+
} catch { /* ignore */ } finally {
|
|
399
|
+
try { await handle.close() } catch { /* ignore */ }
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// ── finalize ────────────────────────────────────────────────────────────
|
|
404
|
+
const repoCache = new Map()
|
|
405
|
+
const items = []
|
|
406
|
+
const protectedCounts = { recent: 0, live: 0, tracked: 0, gone: 0, unsafe: 0 }
|
|
407
|
+
|
|
408
|
+
for (const rec of artifacts.values()) {
|
|
409
|
+
if (insideDsh(rec.key)) { protectedCounts.unsafe++; continue }
|
|
410
|
+
const st = statOf(rec.raw)
|
|
411
|
+
if (!st.exists || st.dir) { protectedCounts.gone++; continue }
|
|
412
|
+
|
|
413
|
+
const producer = rec.producers[0] || null
|
|
414
|
+
const meta = producer && producer.callId ? callMeta.get(producer.callId) : null
|
|
415
|
+
const failed = !!(producer && producer.callId && callMeta.get(producer.callId) && callMeta.get(producer.callId).ok === false)
|
|
416
|
+
const isSpill = SPILL.test(rec.key)
|
|
417
|
+
const isScratch = !isSpill && SCRATCH.test(rec.key) && PRODUCER_TOOLS.has(producer ? producer.tool : '')
|
|
418
|
+
const kind = isSpill ? 'spill' : isScratch ? 'scratch' : failed && st.size < 1024 ? 'failed' : 'other'
|
|
419
|
+
if (kind === 'other') continue
|
|
420
|
+
|
|
421
|
+
// Protection follows real use (a later tool call naming the path), not every
|
|
422
|
+
// chat mention: otherwise the report's own output would protect its items.
|
|
423
|
+
const lastUse = Math.max(rec.lastUse || 0, st.mtime || 0, rec.firstTime || 0)
|
|
424
|
+
const age = now - lastUse
|
|
425
|
+
const inLive = (producer && liveIds.has(producer.sessionId)) ||
|
|
426
|
+
(isSpill && [...liveIds].some((lid) => spilledBy(lid, rec.key)))
|
|
427
|
+
|
|
428
|
+
if (age < week) { protectedCounts.recent++; continue }
|
|
429
|
+
if (inLive) { protectedCounts.live++; continue }
|
|
430
|
+
|
|
431
|
+
const tracked = await gitTracked(rec.raw, repoCache)
|
|
432
|
+
if (tracked === true || tracked === 'unknown') { protectedCounts.tracked++; continue }
|
|
433
|
+
|
|
434
|
+
const uses = rec.uses || 0
|
|
435
|
+
const reasons = []
|
|
436
|
+
let tier = 'unsure'
|
|
437
|
+
const clearlyTemp = DEEP_TEMP.test(rec.key)
|
|
438
|
+
if (kind === 'spill') {
|
|
439
|
+
reasons.push('遗留在系统临时目录的完整工具输出')
|
|
440
|
+
if (uses === 0) { tier = 'safe'; reasons.push('之后再没被当文件打开或执行过') }
|
|
441
|
+
else reasons.push('之后还被用过 ' + uses + ' 次')
|
|
442
|
+
} else if (kind === 'scratch') {
|
|
443
|
+
if (clearlyTemp && uses === 0 && !failed) {
|
|
444
|
+
tier = 'safe'
|
|
445
|
+
reasons.push('临时目录里的脚本/产物')
|
|
446
|
+
reasons.push('产生后再没被用过')
|
|
447
|
+
} else if (clearlyTemp) {
|
|
448
|
+
if (uses > 0) reasons.push('临时目录,但之后还被用过 ' + uses + ' 次')
|
|
449
|
+
else reasons.push('临时目录')
|
|
450
|
+
} else {
|
|
451
|
+
reasons.push('由 write/edit 写出,目录不像明确的临时目录')
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
if (failed) { tier = 'unsure'; reasons.push('产生它的工具调用失败了,可能是半成品') }
|
|
455
|
+
if (st.size > 1024 * 1024) { tier = 'unsure'; reasons.push('体积超过 1 MB') }
|
|
456
|
+
|
|
457
|
+
items.push({
|
|
458
|
+
path: rec.raw,
|
|
459
|
+
key: rec.key,
|
|
460
|
+
kind,
|
|
461
|
+
tier,
|
|
462
|
+
reasons,
|
|
463
|
+
size: st.size,
|
|
464
|
+
mtime: st.mtime,
|
|
465
|
+
ageDays: Math.floor(age / 86_400_000),
|
|
466
|
+
lastUseAt: lastUse,
|
|
467
|
+
refs: rec.refCount,
|
|
468
|
+
uses,
|
|
469
|
+
failed,
|
|
470
|
+
tracked: tracked === true,
|
|
471
|
+
session: producer ? { id: producer.sessionId, title: (callMeta.get(producer.callId) || {}).title || titleOf.get(producer.sessionId) || null } : null,
|
|
472
|
+
tool: producer ? producer.tool : null,
|
|
473
|
+
turn: producer ? producer.turn : null,
|
|
474
|
+
step: producer ? producer.step : null,
|
|
475
|
+
at: rec.firstTime || null,
|
|
476
|
+
})
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const rootSet = new Set()
|
|
480
|
+
for (const rec of artifacts.values()) {
|
|
481
|
+
if (!SCRATCH.test(rec.key)) continue
|
|
482
|
+
const r = scratchRootOf(rec.raw)
|
|
483
|
+
if (r && !insideDsh(normKey(r)) && r.length < 180) rootSet.add(r)
|
|
484
|
+
}
|
|
485
|
+
let hints = []
|
|
486
|
+
try { hints = collectHints([...rootSet], artifacts, cutoff, now) } catch { hints = [] }
|
|
487
|
+
|
|
488
|
+
items.sort((a, b) => b.size - a.size || String(a.path).localeCompare(String(b.path)))
|
|
489
|
+
const capped = items.slice(0, 2000)
|
|
490
|
+
|
|
491
|
+
const tiers = { safe: { count: 0, bytes: 0 }, unsure: { count: 0, bytes: 0 } }
|
|
492
|
+
for (const it of capped) { const t = tiers[it.tier] || tiers.unsure; t.count++; t.bytes += it.size }
|
|
493
|
+
|
|
494
|
+
return {
|
|
495
|
+
generatedAt: now,
|
|
496
|
+
durationMs: Date.now() - started,
|
|
497
|
+
weekDays: Math.round(week / 86_400_000),
|
|
498
|
+
home: safeHome(),
|
|
499
|
+
stats: {
|
|
500
|
+
...stats,
|
|
501
|
+
artifacts: artifacts.size,
|
|
502
|
+
candidates: items.length,
|
|
503
|
+
listed: capped.length,
|
|
504
|
+
liveSessions: liveIds.size,
|
|
505
|
+
unreadableSessions: unreadable.length,
|
|
506
|
+
},
|
|
507
|
+
protected: protectedCounts,
|
|
508
|
+
tiers,
|
|
509
|
+
unreadable,
|
|
510
|
+
items: capped,
|
|
511
|
+
hints,
|
|
512
|
+
truncated: items.length > capped.length,
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function safeHome() {
|
|
517
|
+
try { return homedir() } catch { return '' }
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
export const _internal = { normKey, toks, last2, relKey, SCRATCH, DEEP_TEMP, SPILL, scratchRootOf, collectHints, gitTracked }
|