dsh-sweeper 0.0.0-stage → 1.4.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.
package/lib/index.js ADDED
@@ -0,0 +1,994 @@
1
+ /**
2
+ * dsh-sweeper · host half.
3
+ *
4
+ * Read-only scan + user-initiated, reversible cleanup:
5
+ * GET /plugins/dsh-sweeper/report report (cached, ?refresh=1 re-scans)
6
+ * POST /plugins/dsh-sweeper/delete move selected items into a trash batch
7
+ * GET /plugins/dsh-sweeper/trash list trash batches
8
+ * POST /plugins/dsh-sweeper/restore move a batch back
9
+ * POST /plugins/dsh-sweeper/purge permanently remove a batch
10
+ * POST /plugins/dsh-sweeper/review one model opinion over the candidates
11
+ * GET /plugins/dsh-sweeper/health scan state
12
+ *
13
+ * Deleting is only ever a rename into `DSH_HOME/plugin-data/dsh-sweeper/trash`
14
+ * (see trash.js); nothing in this plugin unlinks a user file.
15
+ */
16
+
17
+ import { randomBytes, randomUUID } from 'node:crypto'
18
+ import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
19
+ import { scan, _internal } from './scan.js'
20
+ import { dshHome, quarantine, restore, purge, listBatches, trashRoot, rejectionReason } from './trash.js'
21
+ import { review, applyVerdict } from './review.js'
22
+ import { planDeep, runDeep, vetDeepResult, forgetRestored } from './deep.js'
23
+ import { runAgentLoop } from './agent.js'
24
+ import { makeFsTools, rootsFor } from './fs-tools.js'
25
+ import { tmpdir } from 'node:os'
26
+ import { join as joinTmpPath } from 'node:path'
27
+
28
+ const BASE = '/plugins/dsh-sweeper'
29
+ const CACHE_MS = 60_000
30
+ const MAX_BODY = 1024 * 1024
31
+ const DAY = 24 * 60 * 60 * 1000
32
+
33
+ export const name = 'dsh-sweeper'
34
+
35
+ const fail = (status, message, extra) => Object.assign(new Error(message), { status }, extra || {})
36
+
37
+ /**
38
+ * Reject a browser-shaped request that is not same-origin ours.
39
+ *
40
+ * Only used when the Connection service (which owns DSH's authoritative
41
+ * `requestRejection`) is absent — an older composition with a `webServer` but
42
+ * no browser-authentication owner. Fail-closed on the three browser vectors a
43
+ * plain route would otherwise accept:
44
+ * • `sec-fetch-site: cross-site` — a page on any origin driving this API;
45
+ * • an `Origin` that is not our own authority — the same, with CORS markers;
46
+ * • a non-loopback `Host` — DNS rebinding, where a name the attacker owns
47
+ * resolves to 127.0.0.1 so even `Origin === Host` looks "same-origin".
48
+ * Non-browser callers (curl, scripts) carry no `Sec-Fetch-*`/`Origin` and a
49
+ * loopback `Host`, so they keep working — the same shape DSH uses for `/api`.
50
+ */
51
+ function fallbackRejection(req) {
52
+ const headers = req && req.headers
53
+ if (!headers || typeof headers !== 'object') return undefined
54
+ const header = (name) => {
55
+ const value = headers[name]
56
+ return typeof value === 'string' ? value : Array.isArray(value) ? value[0] : undefined
57
+ }
58
+ if (header('sec-fetch-site') === 'cross-site') return 403
59
+ const host = header('host')
60
+ const origin = header('origin')
61
+ if (origin !== undefined && host !== undefined) {
62
+ try {
63
+ if (new URL(origin).host !== host) return 403
64
+ } catch { return 403 }
65
+ }
66
+ if (host !== undefined) {
67
+ const hostname = host.replace(/:\d+$/, '').toLowerCase()
68
+ const loopback = hostname === 'localhost' || hostname === '[::1]'
69
+ || /^127(?:\.\d{1,3}){3}$/.test(hostname)
70
+ if (!loopback) return 403
71
+ }
72
+ return undefined
73
+ }
74
+
75
+ function recount(items) {
76
+ const tiers = { safe: { count: 0, bytes: 0 }, unsure: { count: 0, bytes: 0 } }
77
+ const kinds = {}
78
+ for (const it of items) {
79
+ const t = tiers[it.tier] === undefined ? tiers.unsure : tiers[it.tier]
80
+ t.count += 1
81
+ t.bytes += it.size || 0
82
+ kinds[it.kind] = (kinds[it.kind] || 0) + 1
83
+ }
84
+ return { tiers, kinds }
85
+ }
86
+
87
+ export function apply(ctx, config = {}) {
88
+ const state = {
89
+ report: null,
90
+ publishedAt: 0,
91
+ token: null,
92
+ byKey: new Map(),
93
+ running: null,
94
+ reviewing: false,
95
+ lastError: null,
96
+ // Bumped whenever something moved on disk (delete/restore). A scan that was
97
+ // already running describes the disk as it was before that move, so the
98
+ // pass checks this counter afterwards and runs once more if it changed.
99
+ epoch: 0,
100
+ passes: 0,
101
+ routes: new Map(),
102
+ extra: { sweep: [], optional: [], rejected: [], byKey: new Map() },
103
+ }
104
+ // The in-process self test lives outside apply(); it reaches the report through here.
105
+ ctx.__sweeperState = state
106
+ ctx.__sweeperNoteChanged = () => noteDiskChanged()
107
+
108
+ const svc = (c, key) => (typeof c.get === 'function' ? c.get(key) : c[key])
109
+ const weekDays = Number(config.weekDays) > 0 ? Number(config.weekDays) : 7
110
+ const cacheMs = Number(config.cacheSeconds) >= 0 ? Number(config.cacheSeconds) * 1000 : CACHE_MS
111
+
112
+ /**
113
+ * Model proposals are untrusted. Accept one only if it is literally one of the
114
+ * files the scan itself observed, still exists unchanged, is not a link, is not
115
+ * inside DSH/git, and is small enough to be a leftover. Anything else is dropped
116
+ * with a reason (fail-closed, never "best effort").
117
+ */
118
+ const vetProposals = async (proposals, report) => {
119
+ const known = new Map((report.hints || []).map((h) => [h.key, h]))
120
+ const out = { sweep: [], optional: [], rejected: [] }
121
+ const seen = new Set()
122
+ for (const bucket of ['sweep', 'optional']) {
123
+ for (const p of proposals[bucket] || []) {
124
+ const h = known.get(p.key)
125
+ if (!h) { out.rejected.push({ path: p.path, reason: 'not one of the files the scan observed' }); continue }
126
+ if (seen.has(h.key)) continue
127
+ const why = await checkProposal(h)
128
+ if (why) { out.rejected.push({ path: h.path, reason: why }); continue }
129
+ seen.add(h.key)
130
+ out[bucket].push({ key: h.key, path: h.path, size: h.size, ageDays: h.ageDays, bucket })
131
+ }
132
+ }
133
+ return out
134
+ }
135
+
136
+ const checkProposal = async (h) => {
137
+ let st
138
+ try { st = lstatSync(h.path) } catch { return 'the file is gone' }
139
+ if (!st.isFile()) return st.isSymbolicLink() ? 'it is a link' : 'it is not a regular file'
140
+ if (st.isSymbolicLink()) return 'it is a link'
141
+ if (st.size !== h.size) return 'the file changed after the scan'
142
+ if (st.size > 50 * 1024 * 1024) return 'larger than 50 MB'
143
+ if (Math.abs(st.mtimeMs - h.mtime) > 2000) return 'the file changed after the scan'
144
+ let tracked = 'unknown'
145
+ try { tracked = await _internal.gitTracked(h.path, new Map()) } catch { tracked = 'unknown' }
146
+ if (tracked === true) return 'tracked by git'
147
+ if (tracked === 'unknown') return 'git could not confirm whether it is tracked'
148
+ return ''
149
+ }
150
+
151
+ // ── deep pass: one model call per idle conversation ───────────────────────
152
+ // Each conversation knows what it was doing; the scan cannot. The model is
153
+ // asked, per conversation, which of *that conversation's* leftovers are dead
154
+ // weight. Its answer is untrusted like any other model output: an item only
155
+ // becomes selectable when it is still the same file, is not tracked by git,
156
+ // and (for the "safe" bucket) sits in a place the scan already treats as
157
+ // throwaway space. Anything else lands in "optional" or is rejected.
158
+ let deepJob = null
159
+ let deepPlan = null
160
+ let deep = null
161
+ let deepPlanAt = 0
162
+
163
+ const deepVet = (session, parsed) => vetDeepResult(session, parsed)
164
+
165
+ const mergeDeep = (job) => {
166
+ // A cancelled pass can still have a model call in flight when the next pass
167
+ // starts. Its late callback must not repaint the page with the old rows.
168
+ if (deepJob && job !== deepJob) return deep
169
+ const byKey = new Map()
170
+ const sweep = []
171
+ const optional = []
172
+ for (const id of job.order) {
173
+ const s = job.sessions.get(id)
174
+ if (!s) continue
175
+ for (const it of s.items) {
176
+ if (byKey.has(it.key)) continue
177
+ byKey.set(it.key, it)
178
+ ;(it.tier === 'safe' ? sweep : optional).push(it)
179
+ }
180
+ }
181
+ const rejected = []
182
+ for (const id of job.order) {
183
+ const s = job.sessions.get(id)
184
+ if (!s) continue
185
+ for (const r of s.rejected || []) rejected.push(r)
186
+ }
187
+ deep = { job, byKey, sweep, optional, rejected }
188
+ return deep
189
+ }
190
+
191
+ const planView = (plan) => ({
192
+ generatedAt: Date.now(),
193
+ week: plan.week,
194
+ concurrency: plan.concurrency,
195
+ totalEstTokens: plan.totalEstTokens,
196
+ skipped: plan.skipped || 0,
197
+ unreadable: plan.unreadable || 0,
198
+ sessions: plan.sessions.map((s) => ({
199
+ id: s.id, title: s.title, cwd: s.cwd, ageDays: s.ageDays, toolCalls: s.toolCalls,
200
+ candidates: s.candidates, hidden: s.hidden || 0, estTokens: s.estTokens,
201
+ truncated: !!s.truncated, tools: !!s.cwd,
202
+ })),
203
+ })
204
+
205
+ const deepView = (job) => ({
206
+ id: job.id,
207
+ state: job.state,
208
+ startedAt: job.startedAt,
209
+ ms: Date.now() - job.startedAt,
210
+ week: job.week,
211
+ concurrency: job.concurrency,
212
+ model: job.model || null,
213
+ totals: {
214
+ sessions: job.order.length,
215
+ truncated: job.order.reduce((n, id) => n + ((job.sessions.get(id) || {}).truncated ? 1 : 0), 0),
216
+ done: job.done,
217
+ failed: job.fail,
218
+ candidates: job.order.reduce((n, id) => n + ((job.sessions.get(id) || {}).candidates || 0), 0),
219
+ hidden: job.order.reduce((n, id) => n + ((job.sessions.get(id) || {}).hidden || 0), 0),
220
+ estTokens: job.estTokens,
221
+ calls: job.order.reduce((n, id) => n + ((job.sessions.get(id) || {}).calls || 0), 0),
222
+ ms: job.ms,
223
+ },
224
+ sessions: job.order.map((id) => {
225
+ const s = job.sessions.get(id)
226
+ return {
227
+ id, title: s.title, cwd: s.cwd, ageDays: s.ageDays, toolCalls: s.toolCalls,
228
+ candidates: s.candidates, hidden: s.hidden || 0, truncated: !!s.truncated,
229
+ estTokens: s.estTokens, status: s.status,
230
+ agent: s.agent === true, turns: s.turns || 0, calls: s.calls || 0,
231
+ ms: s.ms, error: s.error, found: s.items.length,
232
+ debug: job.debug ? s.debug : undefined,
233
+ }
234
+ }),
235
+ sweep: deep ? deep.sweep : [],
236
+ optional: deep ? deep.optional : [],
237
+ rejected: ((deep && deep.rejected) || []).concat(job.rejectedAll || []),
238
+ })
239
+
240
+ /** Publish a finished report: the token belongs to the report, not to one GET. */
241
+ const publish = (report) => {
242
+ if (report !== state.report) {
243
+ state.report = report
244
+ state.publishedAt = Date.now()
245
+ state.token = randomBytes(9).toString('hex')
246
+ state.byKey = new Map(report.items.map((it) => [it.key, it]))
247
+ state.extra = { sweep: [], optional: [], rejected: [], byKey: new Map() }
248
+ // A rescan while a deep pass is streaming must not orphan that pass: the
249
+ // job keeps writing into `deep`, and the page keeps polling it. The rows
250
+ // are re-checked against the disk when they are acted on, so keeping them
251
+ // is safe even though the report they came from is gone.
252
+ if (!deepJob || deepJob.state !== 'running') {
253
+ deep = null
254
+ deepJob = null
255
+ deepPlan = null
256
+ deepPlanAt = 0
257
+ }
258
+ }
259
+ return {
260
+ ...report,
261
+ token: state.token,
262
+ trashRoot: trashRoot(),
263
+ ageMs: Date.now() - state.publishedAt,
264
+ lastError: state.lastError,
265
+ }
266
+ }
267
+
268
+ const run = async (force) => {
269
+ if (!force && state.report && Date.now() - state.publishedAt < cacheMs) return publish(state.report)
270
+ // Coalesce: everyone who asks while a pass is in flight waits for the same
271
+ // pass, and that promise only settles after the report is published. The
272
+ // old shape cleared `state.running` in `finally` and published afterwards,
273
+ // which left a window where a second caller saw no running pass and started
274
+ // its own full scan on top of the one that had just finished.
275
+ if (state.running) return state.running
276
+ state.running = (async () => {
277
+ try {
278
+ let epoch = state.epoch
279
+ let report = null
280
+ for (let i = 0; i < 3; i++) {
281
+ state.passes += 1
282
+ report = await scan(ctx, { week: weekDays * DAY })
283
+ if (state.epoch === epoch) break
284
+ epoch = state.epoch
285
+ }
286
+ state.lastError = null
287
+ return publish(report)
288
+ } catch (err) {
289
+ state.lastError = (err && err.message) || String(err)
290
+ try { ctx.logger && ctx.logger.warn && ctx.logger.warn('[dsh-sweeper] scan failed: %s', state.lastError) } catch { /* ignore */ }
291
+ throw err
292
+ } finally {
293
+ state.running = null
294
+ }
295
+ })()
296
+ return state.running
297
+ }
298
+
299
+ const sendJSON = (res, status, body) => {
300
+ if (res.writableEnded || res.headersSent) return
301
+ const text = JSON.stringify(body)
302
+ res.writeHead(status, {
303
+ 'content-type': 'application/json; charset=utf-8',
304
+ 'cache-control': 'no-store',
305
+ 'x-content-type-options': 'nosniff',
306
+ 'content-length': Buffer.byteLength(text),
307
+ })
308
+ res.end(text)
309
+ }
310
+
311
+ const readBody = (req) => new Promise((resolve, reject) => {
312
+ if (req.method !== 'POST') return reject(fail(405, 'POST required'))
313
+ if (String(req.headers['x-dsh-sweeper'] || '') !== '1') return reject(fail(403, 'missing x-dsh-sweeper header'))
314
+ let settled = false
315
+ const done = (fn, value) => { if (settled) return; settled = true; fn(value) }
316
+ const chunks = []
317
+ let size = 0
318
+ req.on('data', (c) => {
319
+ if (settled) return
320
+ size += c.length
321
+ if (size > MAX_BODY) {
322
+ done(reject, fail(413, 'body too large'))
323
+ req.destroy()
324
+ return
325
+ }
326
+ chunks.push(c)
327
+ })
328
+ req.on('end', () => {
329
+ try { done(resolve, JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) }
330
+ catch { done(reject, fail(400, 'bad JSON')) }
331
+ })
332
+ req.on('error', (err) => done(reject, err))
333
+ req.on('aborted', () => done(reject, fail(400, 'request aborted')))
334
+ // A client that goes away mid-body would otherwise leave this promise (and
335
+ // whatever the route holds next to it) pending forever.
336
+ req.on('close', () => done(reject, fail(400, 'request closed before the body arrived')))
337
+ })
338
+
339
+ // The Connection service is read per request, not captured at registration:
340
+ // webServer and connection arrive independently, and a late-arriving
341
+ // authenticator must still fence the routes registered before it.
342
+ const rejectionFor = (req) => {
343
+ let connection
344
+ try { connection = typeof ctx.get === 'function' ? ctx.get('connection') : undefined } catch { connection = undefined }
345
+ return typeof connection?.requestRejection === 'function'
346
+ ? connection.requestRejection(req)
347
+ : fallbackRejection(req)
348
+ }
349
+
350
+ const handle = (fn) => async (req, res) => {
351
+ const rejection = rejectionFor(req)
352
+ if (rejection !== undefined) {
353
+ if (!res.writableEnded && !res.headersSent) {
354
+ res.writeHead(rejection, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
355
+ res.end(rejection === 401 ? 'unauthorized' : 'forbidden')
356
+ }
357
+ return
358
+ }
359
+ try { await fn(req, res) } catch (err) {
360
+ sendJSON(res, (err && err.status) || 500, { error: (err && err.message) || String(err) })
361
+ }
362
+ }
363
+
364
+ const requireReport = () => {
365
+ if (!state.report) throw fail(409, 'no report yet; scan first')
366
+ return state.report
367
+ }
368
+
369
+ const requireToken = (body) => {
370
+ requireReport()
371
+ if (body.token !== state.token) {
372
+ // A second tab (or a rescan) rotated the token. The selection on that page
373
+ // points at a list that no longer exists, so say so plainly and tell the
374
+ // page it may refresh by itself.
375
+ throw fail(409, 'this list is out of date because the report was refreshed elsewhere; scanning again', { stale: true })
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Note that the disk changed: a scan in flight will run again after it, and
381
+ * the deep plan must be recomputed because its candidate counts came from
382
+ * stat() at plan time. Invalidating the plan here (instead of at each call
383
+ * site) is the fix for a miss: `/review` cleaned files and left the plan
384
+ * cache alone, so the next minute still served rows for files in the bin.
385
+ */
386
+ const noteDiskChanged = () => {
387
+ state.epoch += 1
388
+ state.publishedAt = 0
389
+ deepPlanAt = 0
390
+ }
391
+
392
+ const dropKeys = (keys) => {
393
+ const gone = new Set(keys)
394
+ state.report.items = state.report.items.filter((it) => !gone.has(it.key))
395
+ state.byKey = new Map(state.report.items.map((it) => [it.key, it]))
396
+ const { tiers, kinds } = recount(state.report.items)
397
+ state.report.tiers = tiers
398
+ state.report.stats.candidates = state.report.items.length
399
+ state.report.stats.kinds = kinds
400
+ return tiers
401
+ }
402
+
403
+ ctx.inject(['webServer'], (inner) => {
404
+ const web = svc(inner, 'webServer')
405
+ if (!web || typeof web.register !== 'function') return
406
+ const route = (path, fn) => {
407
+ state.routes.set(path, fn)
408
+ ctx.__sweeperRoutes = state.routes
409
+ return inner.effect(() => web.register({ kind: 'exact', path, handler: handle(fn) }), 'dsh-sweeper: ' + path)
410
+ }
411
+
412
+ route(BASE + '/report', async (req, res) => {
413
+ // `run` already coalesces concurrent callers onto one pass and resolves
414
+ // with the published view, so a second `publish` here would hand the
415
+ // report a fresh token while the page is still holding the old one.
416
+ const force = /[?&]refresh=1/.test(String((req && req.url) || ''))
417
+ sendJSON(res, 200, await run(force))
418
+ })
419
+
420
+ route(BASE + '/delete', async (req, res) => {
421
+ const body = await readBody(req)
422
+ requireToken(body)
423
+ const keys = Array.isArray(body.keys) ? [...new Set(body.keys.map(String))].slice(0, 5000) : []
424
+ if (!keys.length) throw fail(400, 'no keys selected')
425
+ if (body.confirmed !== true) throw fail(400, 'confirmation required')
426
+
427
+ const deepPick = body.deep === true
428
+ const extraPick = body.extra === true
429
+ const source = deepPick ? (deep ? deep.byKey : new Map()) : extraPick ? state.extra.byKey : state.byKey
430
+ const picked = []
431
+ const refused = []
432
+ for (const key of keys) {
433
+ if (deepPick && !deep) {
434
+ refused.push({ key, reason: 'the deep pass has no results yet' })
435
+ continue
436
+ }
437
+ const item = source.get(key)
438
+ if (!item) {
439
+ refused.push({
440
+ key,
441
+ reason: deepPick ? 'not in the current deep results' : extraPick ? 'not in the current model proposals' : 'not in the current report',
442
+ })
443
+ continue
444
+ }
445
+ picked.push(item)
446
+ }
447
+ if (!picked.length) {
448
+ sendJSON(res, 200, { batch: null, moved: [], failed: [], refused, tiers: state.report ? state.report.tiers : null, items: state.report ? state.report.items.length : 0 })
449
+ return
450
+ }
451
+ if (picked.some((it) => it.tier === 'unsure') && body.acknowledge !== true) {
452
+ throw fail(400, 'selection contains uncertain items; acknowledge them explicitly')
453
+ }
454
+ const note = body.note || (deepPick ? 'deep review' : extraPick ? 'model proposal' : 'manual selection')
455
+ const result = await quarantine(picked, { note })
456
+ noteDiskChanged()
457
+ let tiers
458
+ if (deepPick) {
459
+ const gone = new Set(result.moved || [])
460
+ for (const id of deepJob ? deepJob.order : []) {
461
+ const row = deepJob.sessions.get(id)
462
+ if (row) row.items = row.items.filter((it) => !gone.has(it.key))
463
+ }
464
+ if (deepJob) mergeDeep(deepJob)
465
+ tiers = state.report ? state.report.tiers : null
466
+ } else if (extraPick) {
467
+ const gone = new Set(result.moved || [])
468
+ state.extra.sweep = state.extra.sweep.filter((it) => !gone.has(it.key))
469
+ state.extra.optional = state.extra.optional.filter((it) => !gone.has(it.key))
470
+ for (const k of gone) state.extra.byKey.delete(k)
471
+ tiers = state.report.tiers
472
+ } else {
473
+ tiers = dropKeys(result.moved || [])
474
+ }
475
+ const sizeOf = new Map(picked.map((it) => [it.key, it.size || 0]))
476
+ const movedBytes = (result.moved || []).reduce((n, k) => n + (sizeOf.get(k) || 0), 0)
477
+ sendJSON(res, 200, { ...result, movedBytes, refused, tiers, deep: deepPick ? deepView(deepJob) : undefined, items: state.report ? state.report.items.length : 0 })
478
+ })
479
+
480
+ // Dynamic pass: one model opinion over the current candidate list. Items the
481
+ // model marks delete AND that are tier 'safe' are moved to the trash right
482
+ // away; everything else becomes a question for the user.
483
+ route(BASE + '/review', async (req, res) => {
484
+ const body = await readBody(req)
485
+ requireToken(body)
486
+ if (state.reviewing) throw fail(409, 'a model review is already running')
487
+ const report = state.report
488
+ const tokenAt = state.token
489
+ state.reviewing = true
490
+ try {
491
+ let out
492
+ try {
493
+ out = await review(ctx, report, { model: body.model, timeoutMs: body.timeoutMs })
494
+ } catch (err) {
495
+ sendJSON(res, 502, {
496
+ error: 'model review failed: ' + ((err && err.message) || String(err)),
497
+ trace: (err && err.trace) || null,
498
+ })
499
+ return
500
+ }
501
+ // A rescan during the model call replaces the token. Acting on the old
502
+ // list would move files the user is no longer looking at.
503
+ if (state.token !== tokenAt) {
504
+ sendJSON(res, 409, { error: 'the report changed while the model was reading it; nothing was moved — rescan and try again' })
505
+ return
506
+ }
507
+ const plan = applyVerdict(report, out.verdict)
508
+ const veto = await vetProposals(out.proposals || {}, report)
509
+ state.extra = {
510
+ sweep: veto.sweep,
511
+ optional: veto.optional,
512
+ rejected: veto.rejected,
513
+ byKey: new Map(veto.sweep.concat(veto.optional).map((it) => [it.key, it])),
514
+ }
515
+ let moved = []
516
+ let movedBytes = 0
517
+ let failed = []
518
+ let batch = null
519
+ const sizeOf = new Map(report.items.map((it) => [it.key, it.size || 0]))
520
+ if (plan.auto.length && body.autoDelete !== false) {
521
+ const result = await quarantine(plan.auto, { note: 'model review' })
522
+ moved = result.moved || []
523
+ failed = result.failed || []
524
+ batch = result.batch
525
+ movedBytes = moved.reduce((n, k) => n + (sizeOf.get(k) || 0), 0)
526
+ if (moved.length) dropKeys(moved)
527
+ }
528
+ // Proposals are never acted on unless the caller opts in explicitly.
529
+ let extraMoved = []
530
+ let extraMovedBytes = 0
531
+ if (body.extraAuto === true && state.extra.sweep.length) {
532
+ const result = await quarantine(state.extra.sweep, { note: 'model proposal' })
533
+ noteDiskChanged()
534
+ extraMoved = result.moved || []
535
+ failed = failed.concat(result.failed || [])
536
+ const gone = new Set(extraMoved)
537
+ const extraSize = new Map(state.extra.sweep.map((it) => [it.key, it.size || 0]))
538
+ extraMovedBytes = extraMoved.reduce((n, k) => n + (extraSize.get(k) || 0), 0)
539
+ state.extra.sweep = state.extra.sweep.filter((it) => !gone.has(it.key))
540
+ for (const k of gone) state.extra.byKey.delete(k)
541
+ }
542
+ sendJSON(res, 200, {
543
+ model: out.model,
544
+ ms: out.ms,
545
+ reviewed: out.reviewed,
546
+ skipped: out.skipped,
547
+ note: out.verdict && out.verdict.note ? out.verdict.note : '',
548
+ auto: plan.auto.map((it) => ({ key: it.key, path: it.path, size: it.size })),
549
+ autoBytes: plan.auto.reduce((n, it) => n + (it.size || 0), 0),
550
+ batch,
551
+ moved,
552
+ movedBytes,
553
+ failed,
554
+ asks: plan.asks,
555
+ kept: plan.kept,
556
+ unknown: plan.unknown.concat((out.unknownIds || []).map((x) => 'unmatched: ' + x)),
557
+ extra: {
558
+ sweep: state.extra.sweep,
559
+ optional: state.extra.optional,
560
+ rejected: state.extra.rejected,
561
+ hints: out.hints || 0,
562
+ moved: extraMoved,
563
+ movedBytes: extraMovedBytes,
564
+ },
565
+ raw: body.debug ? out.raw : undefined,
566
+ trace: out.trace,
567
+ tiers: report.tiers,
568
+ items: report.items.length,
569
+ })
570
+ } finally {
571
+ state.reviewing = false
572
+ }
573
+ })
574
+
575
+ // ── deep pass ────────────────────────────────────────────────────────────
576
+ // Step 1 costs nothing but log reads and says how much the review would
577
+ // cost in tokens, so the page can ask before anything is sent anywhere.
578
+ route(BASE + '/deep/plan', async (req, res) => {
579
+ const force = /[?&]refresh=1/.test(String((req && req.url) || ''))
580
+ const cached = !force && !!deepPlan && Date.now() - deepPlanAt < cacheMs
581
+ if (cached) {
582
+ sendJSON(res, 200, { ...planView(deepPlan), cached: true, plannedAt: deepPlanAt })
583
+ return
584
+ }
585
+ const plan = await planDeep(ctx, { week: weekDays, limit: 24 })
586
+ deepPlan = plan
587
+ deepPlanAt = Date.now()
588
+ sendJSON(res, 200, { ...planView(plan), cached: false, plannedAt: deepPlanAt })
589
+ })
590
+
591
+ // Step 2: send each idle conversation's digest to the model, at most four
592
+ // at a time, and merge each answer as it lands (the UI poll /deep/status).
593
+ route(BASE + '/deep/start', async (req, res) => {
594
+ const body = await readBody(req)
595
+ requireToken(body)
596
+ if (body.consent !== true) throw fail(400, 'this sends conversation summaries to your model; confirm it explicitly')
597
+ if (deepJob && deepJob.state === 'running') throw fail(409, 'a deep pass is already running')
598
+ let plan = (!deepPlan || body.refresh === true) ? await planDeep(ctx, { week: weekDays, limit: 24 }) : deepPlan
599
+ const cap = Number(body.maxSessions)
600
+ // `maxSessions` only limits this run. Caching the slice would make the
601
+ // page show "1 conversation" for the next minute after a test run.
602
+ let picked = plan.sessions
603
+ // `only` exists for the self-test: it can aim one pass at a known
604
+ // conversation instead of whatever the sorter put first.
605
+ if (Array.isArray(body.only) && body.only.length > 0) {
606
+ const prefixes = body.only.map(String)
607
+ picked = picked.filter((s) => prefixes.some((prefix) => String(s.id).includes(prefix)))
608
+ }
609
+ const runPlan = (Number.isFinite(cap) && cap > 0 && picked.length > cap)
610
+ ? { ...plan, sessions: picked.slice(0, cap) }
611
+ : { ...plan, sessions: picked }
612
+ deepPlan = plan
613
+ deepPlanAt = Date.now()
614
+ if (!runPlan.sessions.length) {
615
+ sendJSON(res, 200, { jobId: null, sessions: 0, reason: 'no idle conversation still owns files' })
616
+ return
617
+ }
618
+ const job = {
619
+ id: randomUUID().slice(0, 8),
620
+ startedAt: Date.now(),
621
+ state: 'running',
622
+ week: weekDays,
623
+ concurrency: Math.max(1, Math.min(Number(body.concurrency) || runPlan.concurrency, 8)),
624
+ model: body.model && body.model.model ? String(body.model.model) : null,
625
+ done: 0,
626
+ fail: 0,
627
+ ms: 0,
628
+ estTokens: runPlan.sessions.reduce((n, s) => n + (s.estTokens || 0), 0),
629
+ order: runPlan.sessions.map((s) => s.id),
630
+ sessions: new Map(),
631
+ cancelled: false,
632
+ debug: body.debug === true,
633
+ // Aborting this stops the calls that are already streaming, so 停止
634
+ // does not keep spending tokens on the queued conversations.
635
+ abort: typeof AbortController === 'function' ? new AbortController() : null,
636
+ }
637
+ for (const s of runPlan.sessions) {
638
+ job.sessions.set(s.id, { ...s, status: 'queued', ms: 0, error: null, items: [] })
639
+ }
640
+ if (!job.model) {
641
+ try {
642
+ const sel = ctx.get('agentDefaultModel')
643
+ const pick = sel && typeof sel.currentSelection === 'function' ? sel.currentSelection() : null
644
+ if (pick && pick.provider && pick.model) job.model = pick.provider + '/' + pick.model
645
+ } catch (err) { /* the label is cosmetic; never block the pass */ }
646
+ }
647
+ deepJob = job
648
+ deep = null
649
+ runDeep(ctx, runPlan.sessions, {
650
+ concurrency: job.concurrency,
651
+ model: body.model,
652
+ agent: body.agent !== false,
653
+ timeoutMs: body.timeoutMs,
654
+ signal: job.abort ? job.abort.signal : undefined,
655
+ onResult: async (session, payload) => {
656
+ const row = job.sessions.get(session.id)
657
+ if (!row) return
658
+ try {
659
+ if (job.cancelled) { row.status = 'cancelled'; return }
660
+ if (!payload.ok) {
661
+ row.status = 'failed'
662
+ row.error = payload.error || 'model call failed'
663
+ job.fail += 1
664
+ mergeDeep(job)
665
+ return
666
+ }
667
+ if (job.debug) {
668
+ row.debug = {
669
+ estTokens: payload.estTokens,
670
+ digestChars: payload.digestChars,
671
+ parsed: payload.parsed,
672
+ trace: payload.trace,
673
+ raw: String(payload.raw || '').slice(0, 1500),
674
+ }
675
+ }
676
+ const veto = await deepVet(row, payload.parsed)
677
+ row.items = veto.sweep.concat(veto.optional)
678
+ row.rejected = veto.rejected
679
+ row.status = 'done'
680
+ row.agent = payload.agent === true
681
+ row.turns = payload.turns || 0
682
+ row.calls = payload.calls || 0
683
+ row.ms = payload.ms || 0
684
+ row.estTokens = payload.estTokens || row.estTokens
685
+ job.done += 1
686
+ if (job.rejectedAll === undefined) job.rejectedAll = []
687
+ job.rejectedAll = job.rejectedAll.concat(veto.rejected)
688
+ mergeDeep(job)
689
+ } catch (err) {
690
+ row.status = 'failed'
691
+ row.error = 'vetting failed: ' + ((err && err.message) || String(err))
692
+ job.fail += 1
693
+ mergeDeep(job)
694
+ }
695
+ },
696
+ }).then(() => {
697
+ // anything the pool never got to is cancelled, not left looking queued
698
+ for (const row of job.sessions.values()) if (row.status === 'queued') row.status = 'cancelled'
699
+ job.state = job.cancelled ? 'cancelled' : 'done'
700
+ job.ms = Date.now() - job.startedAt
701
+ mergeDeep(job)
702
+ }).catch((err) => {
703
+ job.state = 'failed'
704
+ job.ms = Date.now() - job.startedAt
705
+ job.error = (err && err.message) || String(err)
706
+ })
707
+ sendJSON(res, 202, { jobId: job.id, sessions: job.order.length, estTokens: job.estTokens, concurrency: job.concurrency })
708
+ })
709
+
710
+ route(BASE + '/deep/status', async (req, res) => {
711
+ if (!deepJob) { sendJSON(res, 200, { job: null }); return }
712
+ sendJSON(res, 200, { job: deepView(deepJob) })
713
+ })
714
+
715
+ route(BASE + '/deep/cancel', async (req, res) => {
716
+ const body = await readBody(req)
717
+ if (!deepJob || deepJob.state !== 'running') throw fail(409, 'no deep pass is running')
718
+ if (body.jobId && body.jobId !== deepJob.id) throw fail(409, 'that deep pass is not the current one')
719
+ deepJob.cancelled = true
720
+ if (deepJob.abort) { try { deepJob.abort.abort() } catch (err) { /* already aborted */ } }
721
+ sendJSON(res, 200, { cancelled: true, jobId: deepJob.id })
722
+ })
723
+
724
+
725
+ route(BASE + '/trash', async (req, res) => {
726
+ sendJSON(res, 200, { root: trashRoot(), batches: await listBatches() })
727
+ })
728
+
729
+ route(BASE + '/restore', async (req, res) => {
730
+ const body = await readBody(req)
731
+ const result = await restore(body.batchId)
732
+ // Files that just went back to their old places must not stay on the page
733
+ // as candidates: otherwise the next "clean" click would drop them into the
734
+ // bin again, which makes restore look like it did nothing.
735
+ // One call covers all three caches: the report, the scan-in-flight epoch
736
+ // and the deep plan counts.
737
+ noteDiskChanged()
738
+ forgetRestored(deep, deepJob, result.restoredPaths)
739
+ if (deepJob) mergeDeep(deepJob)
740
+ if (state.extra) forgetRestored(state.extra, null, result.restoredPaths)
741
+ sendJSON(res, 200, result)
742
+ })
743
+
744
+ route(BASE + '/purge', async (req, res) => {
745
+ const body = await readBody(req)
746
+ if (body.confirmed !== true) throw fail(400, 'confirmation required')
747
+ const gone = await purge(body.batchId)
748
+ if (gone.missing) throw fail(404, 'that batch is already gone')
749
+ sendJSON(res, 200, gone)
750
+ })
751
+
752
+ route(BASE + '/health', async (req, res) => {
753
+ const r = state.report
754
+ sendJSON(res, 200, {
755
+ ok: true,
756
+ error: state.lastError,
757
+ hasReport: !!r,
758
+ ageMs: r ? Date.now() - state.publishedAt : null,
759
+ durationMs: r ? r.durationMs : null,
760
+ items: r ? r.items.length : 0,
761
+ tiers: r ? r.tiers : null,
762
+ scanning: !!state.running,
763
+ passes: state.passes,
764
+ reviewing: state.reviewing,
765
+ trashRoot: trashRoot(),
766
+ weekDays,
767
+ })
768
+ })
769
+ })
770
+
771
+ applySelfTest(ctx)
772
+ }
773
+
774
+ // ── in-process self test ───────────────────────────────────────────────────
775
+ // The HTTP routes sit behind DSH's browser trust check, so a terminal cannot
776
+ // call them. When `<plugin-data>/selftest.json` exists at load, this drives the
777
+ // real handlers in-process instead: scan → deep plan → one conversation's model
778
+ // call → the exact JSON the page polls. It never calls /delete or /purge.
779
+ const SELFTEST_REPORT = 'selftest-out.json'
780
+
781
+ function makeFakeRequest(method, url, body) {
782
+ const listeners = new Map()
783
+ const req = {
784
+ method,
785
+ url,
786
+ headers: { 'x-dsh-sweeper': '1', 'content-type': 'application/json' },
787
+ on(event, fn) {
788
+ if (!listeners.has(event)) listeners.set(event, [])
789
+ listeners.get(event).push(fn)
790
+ return req
791
+ },
792
+ destroy() {},
793
+ }
794
+ setTimeout(() => {
795
+ const emit = (event, value) => (listeners.get(event) || []).forEach((fn) => fn(value))
796
+ if (body !== undefined) emit('data', Buffer.from(JSON.stringify(body), 'utf8'))
797
+ emit('end')
798
+ }, 0)
799
+ return req
800
+ }
801
+
802
+ function makeFakeResponse(resolve) {
803
+ return {
804
+ statusCode: 0,
805
+ headersSent: false,
806
+ writeHead(code, headers) { this.statusCode = code; this.headersSent = true; this.headers = headers },
807
+ setHeader() {},
808
+ end(payload) { resolve({ status: this.statusCode || 200, body: String(payload == null ? '' : payload) }) },
809
+ write() {},
810
+ }
811
+ }
812
+
813
+ function joinTmp(name) {
814
+ return joinTmpPath(tmpdir(), name + '-' + randomBytes(3).toString('hex'))
815
+ }
816
+
817
+ export function applySelfTest(ctx) {
818
+ const dir = dshHome() + '/plugin-data/dsh-sweeper'
819
+ const trigger = dir + '/selftest.json'
820
+ if (!existsSync(trigger)) return
821
+ let triggerCfg = {}
822
+ try { triggerCfg = JSON.parse(readFileSync(trigger, 'utf8')) || {} } catch (err) { triggerCfg = {} }
823
+ setTimeout(async () => {
824
+ const out = { at: new Date().toISOString(), steps: [], timeline: [], error: null }
825
+ const call = (method, path, body) =>
826
+ new Promise((resolve, reject) => {
827
+ const fn = ctx.__sweeperRoutes && ctx.__sweeperRoutes.get(String(path).split('?')[0])
828
+ if (!fn) return reject(new Error('route not found: ' + path))
829
+ const res = makeFakeResponse(resolve)
830
+ Promise.resolve(fn(makeFakeRequest(method, path, body), res)).catch(reject)
831
+ })
832
+ try {
833
+ const t0 = Date.now()
834
+ // Test-only: pretend something moved while the scan is running, so the
835
+ // pass has to notice the epoch change and read the disk again.
836
+ if (triggerCfg.mutateDuringScan) {
837
+ setTimeout(() => {
838
+ try { ctx.__sweeperNoteChanged(); out.mutatedAt = Date.now() - t0 } catch { /* ignore */ }
839
+ }, 400)
840
+ }
841
+ const scanOut = await call('GET', '/plugins/dsh-sweeper/report?refresh=1')
842
+ const report = JSON.parse(scanOut.body)
843
+ out.scanPasses = ctx.__sweeperState ? ctx.__sweeperState.passes : null
844
+ out.steps.push({ step: 'scan', status: scanOut.status, items: (report.items || []).length, tiers: report.tiers, protected: report.protected, unreadable: (report.unreadable || []).length, truncated: !!report.truncated, scanMs: report.durationMs })
845
+ const planOut = await call('GET', '/plugins/dsh-sweeper/deep/plan?refresh=1')
846
+ const plan = JSON.parse(planOut.body)
847
+ out.steps.push({ step: 'plan', status: planOut.status, sessions: (plan.sessions || []).length, estTokens: plan.estTokens, concurrency: plan.concurrency })
848
+ if (triggerCfg.deep === false) {
849
+ out.note = 'deep step skipped by trigger'
850
+ } else if (!plan.sessions || !plan.sessions.length) {
851
+ out.note = 'no idle conversation still owns files; nothing was sent to the model'
852
+ } else {
853
+ const startOut = await call('POST', '/plugins/dsh-sweeper/deep/start', {
854
+ token: report.token,
855
+ consent: true,
856
+ maxSessions: Math.max(1, Math.min(Number(triggerCfg.sessions) || 1, 12)),
857
+ only: Array.isArray(triggerCfg.only) ? triggerCfg.only : undefined,
858
+ refresh: triggerCfg.refresh !== false,
859
+ concurrency: Math.max(1, Math.min(Number(triggerCfg.concurrency) || 1, 4)),
860
+ debug: triggerCfg.debug === true,
861
+ })
862
+ const started = JSON.parse(startOut.body)
863
+ out.steps.push({ step: 'start', status: startOut.status, jobId: started.jobId, sessions: started.sessions, estTokens: started.estTokens })
864
+ if (Number(triggerCfg.cancelAfterMs) > 0) {
865
+ setTimeout(() => {
866
+ call('POST', '/plugins/dsh-sweeper/deep/cancel', { jobId: started.jobId })
867
+ .then((r) => out.steps.push({ step: 'cancel', status: r.status, at: Date.now() - t0 }))
868
+ .catch((err) => out.steps.push({ step: 'cancel', status: 'error', error: String(err && err.message) }))
869
+ }, Number(triggerCfg.cancelAfterMs))
870
+ }
871
+ let status = null
872
+ for (let i = 0; i < 150; i++) {
873
+ await new Promise((r) => setTimeout(r, 2000))
874
+ const st = await call('GET', '/plugins/dsh-sweeper/deep/status')
875
+ const parsed = JSON.parse(st.body)
876
+ status = parsed.job
877
+ if (status) {
878
+ out.timeline.push({
879
+ t: Date.now() - t0,
880
+ done: status.totals ? status.totals.done : 0,
881
+ failed: status.totals ? status.totals.failed : 0,
882
+ rows: (status.sessions || []).map((row) => row.id.slice(0, 12) + ':' + row.status),
883
+ })
884
+ }
885
+ if (!status || status.state !== 'running') break
886
+ }
887
+ out.deep = status
888
+ out.steps.push({ step: 'status', state: status && status.state, sweep: status ? status.sweep.length : 0, optional: status ? status.optional.length : 0, rejected: status ? status.rejected.length : 0 })
889
+ }
890
+ // Test-only: let the trigger hand the review pass a fixture list. Nothing
891
+ // is ever moved from here — the review call below runs with autoDelete off.
892
+ // Read-only check of the stale-tab contract: a wrong token must be
893
+ // refused *before* anything is looked at, and the refusal must say the
894
+ // list is out of date so the page can refresh itself.
895
+ if (triggerCfg.staleToken) {
896
+ // Either shape is fine here: the handler may answer 409 or reject with
897
+ // the same error object. What matters is that no file was touched.
898
+ let stale = { status: 0, stale: false, error: '' }
899
+ try {
900
+ const r = await call('POST', '/plugins/dsh-sweeper/delete', {
901
+ token: 'token-from-another-tab', keys: [], confirmed: true,
902
+ })
903
+ let body = {}
904
+ try { body = JSON.parse(r.body) } catch { body = {} }
905
+ stale = { status: r.status, stale: body.stale === true, error: body.error || '' }
906
+ } catch (err) {
907
+ stale = { status: (err && err.status) || 0, stale: !!(err && err.stale), error: (err && err.message) || String(err) }
908
+ }
909
+ out.staleToken = stale
910
+ out.steps.push({ step: 'stale-token', status: stale.status, stale: stale.stale })
911
+ }
912
+
913
+ // Read-only check of the plan cache: after the plugin notes a disk change,
914
+ // the next plan must be recomputed instead of served from the 60s cache.
915
+ // Test-only: hand back the published report so the replay fixtures can be
916
+ // checked against a real response instead of a hand-written one.
917
+ if (triggerCfg.captureReport && ctx.__sweeperState && ctx.__sweeperState.report) {
918
+ out.reportView = ctx.__sweeperState.report
919
+ out.steps.push({ step: 'report-view', items: out.reportView.items.length })
920
+ }
921
+
922
+ if (triggerCfg.planStale) {
923
+ const first = JSON.parse((await call('GET', '/plugins/dsh-sweeper/deep/plan?refresh=1')).body)
924
+ try { ctx.__sweeperNoteChanged() } catch { /* older host */ }
925
+ const second = JSON.parse((await call('GET', '/plugins/dsh-sweeper/deep/plan')).body)
926
+ const invalidated = second.plannedAt !== first.plannedAt
927
+ out.planStale = { before: first.plannedAt, after: second.plannedAt, invalidated, cached: second.cached === true }
928
+ out.steps.push({ step: 'plan-stale', invalidated, cached: second.cached === true })
929
+ }
930
+
931
+ if (Array.isArray(triggerCfg.items) && triggerCfg.items.length) {
932
+ const items = triggerCfg.items.map((it, n) => ({
933
+ key: it.key, path: it.path, tier: it.tier === 'unsure' ? 'unsure' : 'safe',
934
+ kind: it.kind || 'scratch', size: it.size || 0, mtime: it.mtime || Date.now(),
935
+ ageDays: it.ageDays || 10, refs: 0, uses: 0, failed: false,
936
+ reasons: ['fixture'], origin: 'fixture', n: n + 1,
937
+ }))
938
+ const safe = items.filter((i) => i.tier === 'safe')
939
+ const bytes = (arr) => arr.reduce((n, i) => n + (i.size || 0), 0)
940
+ const tiers = {
941
+ safe: { count: safe.length, bytes: bytes(safe) },
942
+ unsure: { count: items.length - safe.length, bytes: bytes(items) - bytes(safe) },
943
+ }
944
+ const st = ctx.__sweeperState
945
+ if (st && st.report) st.report = Object.assign({}, st.report, { items, tiers })
946
+ out.steps.push({ step: 'fixture', items: items.length, tiers })
947
+ }
948
+ if (triggerCfg.agentProbe === true) {
949
+ // A tiny sandbox so the probe proves the loop and the tools, not the
950
+ // user's disk: one small file, one 3 MB file, one nested directory.
951
+ const probeRoot = joinTmp('sweeper-agent-probe')
952
+ mkdirSync(probeRoot + '/nested', { recursive: true })
953
+ writeFileSync(probeRoot + '/notes.md', 'hello\n')
954
+ writeFileSync(probeRoot + '/run.bin', Buffer.alloc(3 * 1024 * 1024, 7))
955
+ writeFileSync(probeRoot + '/nested/keep.txt', 'keep\n')
956
+ const tools = makeFsTools({ roots: rootsFor(probeRoot), deny: [dshHome()] })
957
+ const result = await runAgentLoop(ctx, {
958
+ system: 'You are auditing one directory for files a completed job left behind. Use the tools to look. Then answer in plain text with one line per file: "S <path> <reason>" for clearly disposable, "O <path> <reason>" for probably disposable, "K <path> <reason>" to keep. Never guess a path you have not listed.',
959
+ goal: 'Directory: ' + probeRoot + '\n\nFind the files in it that look like leftovers, especially anything large. Use list_dir and find_files, then answer.',
960
+ route: () => { const sel = ctx.get('agentDefaultModel')?.currentSelection?.(); return sel ? { provider: sel.provider, model: sel.model } : null },
961
+ tools,
962
+ maxTurns: 4,
963
+ maxCalls: 6,
964
+ })
965
+ out.agentProbe = { turns: result.turns, calls: result.calls, finished: result.finished, text: (result.text || '').slice(0, 1200), trace: result.trace }
966
+ out.steps.push({ step: 'agent-probe', turns: result.turns, calls: result.calls, text: (result.text || '').slice(0, 200) })
967
+ }
968
+
969
+ if (triggerCfg.review === true) {
970
+ const revOut = await call('POST', '/plugins/dsh-sweeper/review', { token: report.token, autoDelete: false })
971
+ const rev = JSON.parse(revOut.body)
972
+ out.steps.push({
973
+ step: 'review', status: revOut.status, model: rev.model, ms: rev.ms,
974
+ reviewed: rev.reviewed, auto: (rev.auto || []).length, asks: (rev.asks || []).length,
975
+ unknown: (rev.unknown || []).length, extra: rev.extra ? {
976
+ hints: rev.extra.hints, sweep: (rev.extra.sweep || []).length,
977
+ optional: (rev.extra.optional || []).length, rejected: (rev.extra.rejected || []).length,
978
+ } : null,
979
+ })
980
+ out.review = rev
981
+ }
982
+ out.ms = Date.now() - t0
983
+ } catch (err) {
984
+ out.error = (err && err.message) || String(err)
985
+ }
986
+ try {
987
+ mkdirSync(dir, { recursive: true })
988
+ writeFileSync(dir + '/' + SELFTEST_REPORT, JSON.stringify(out, null, 2), 'utf8')
989
+ unlinkSync(trigger)
990
+ } catch { /* ignore */ }
991
+ }, 2000)
992
+ }
993
+
994
+ export const inject = ['webServer']