@gtheys/pi-interactive-subagents 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +462 -2
- package/agents/claude-code.md +23 -0
- package/agents/planner.md +569 -0
- package/agents/reviewer.md +152 -0
- package/agents/scout.md +112 -0
- package/agents/visual-tester.md +202 -0
- package/agents/worker.md +109 -0
- package/config.json.example +6 -0
- package/config.schema.json +71 -0
- package/package.json +59 -4
- package/pi-extension/subagents/activity.ts +730 -0
- package/pi-extension/subagents/asks.ts +234 -0
- package/pi-extension/subagents/assignments.ts +395 -0
- package/pi-extension/subagents/config.ts +191 -0
- package/pi-extension/subagents/control.ts +172 -0
- package/pi-extension/subagents/dataroot.ts +52 -0
- package/pi-extension/subagents/delivered.ts +81 -0
- package/pi-extension/subagents/flow-env.ts +112 -0
- package/pi-extension/subagents/herdr.ts +323 -0
- package/pi-extension/subagents/inbox.ts +213 -0
- package/pi-extension/subagents/index.ts +5003 -0
- package/pi-extension/subagents/lock.ts +318 -0
- package/pi-extension/subagents/peer-bindings.ts +175 -0
- package/pi-extension/subagents/peers.ts +401 -0
- package/pi-extension/subagents/plan-skill.md +219 -0
- package/pi-extension/subagents/plugin/.claude-plugin/plugin.json +5 -0
- package/pi-extension/subagents/plugin/hooks/hooks.json +15 -0
- package/pi-extension/subagents/plugin/hooks/on-stop.sh +68 -0
- package/pi-extension/subagents/retention.ts +918 -0
- package/pi-extension/subagents/retirement.ts +216 -0
- package/pi-extension/subagents/session.ts +194 -0
- package/pi-extension/subagents/snapshot.ts +151 -0
- package/pi-extension/subagents/spawn.ts +237 -0
- package/pi-extension/subagents/spawnseq.ts +116 -0
- package/pi-extension/subagents/state-events.ts +152 -0
- package/pi-extension/subagents/status.ts +886 -0
- package/pi-extension/subagents/store.ts +245 -0
- package/pi-extension/subagents/subagent-done.ts +1452 -0
- package/pi-extension/subagents/surface.ts +365 -0
- package/pi-extension/subagents/task-composition.ts +113 -0
- package/pi-extension/subagents/tool-effects.ts +203 -0
- package/pi-extension/subagents/usage.ts +330 -0
- package/pi-extension/subagents/watermark.ts +126 -0
- package/pi-extension/subagents/worktrees.ts +147 -0
- package/skills/subagent-orchestration/SKILL.md +57 -0
|
@@ -0,0 +1,918 @@
|
|
|
1
|
+
// Retention / pruning sweep for the subagents data root (PMR-KT90).
|
|
2
|
+
//
|
|
3
|
+
// pruneSubagentsData walks <dataRoot>/pi-subagents/ and removes records per
|
|
4
|
+
// the record-class policy matrix (plan 2026-11-21-add-safe-retention-for-
|
|
5
|
+
// inactive). Two invariants are absolute:
|
|
6
|
+
//
|
|
7
|
+
// AIDEV-NOTE (PMR-KT90): result-ref-reservations and spawn-seq are NEVER
|
|
8
|
+
// enumerated for deletion — pruning either resets a monotonic counter
|
|
9
|
+
// (highestExistingN / spawn-seq N), which would reuse semantic refs and
|
|
10
|
+
// childIds. This module deliberately contains no code path that reads or
|
|
11
|
+
// lists those two directories for removal.
|
|
12
|
+
//
|
|
13
|
+
// AIDEV-NOTE (PMR-KT90): every class fails CLOSED — an unreadable record, an
|
|
14
|
+
// unparseable/missing timestamp, a failed liveness inspection
|
|
15
|
+
// (readProcessLockStatus throws "Unable to verify" by design), or an
|
|
16
|
+
// unresolvable session-file lookup all KEEP the record and count it as
|
|
17
|
+
// skipped. Deletions are per-record try/caught so one bad record never
|
|
18
|
+
// aborts the sweep.
|
|
19
|
+
//
|
|
20
|
+
// Injectable `now` (activity.ts precedent) and `root` (dataroot.ts test
|
|
21
|
+
// seam) keep the policy path free of wall-clock and default-path reads.
|
|
22
|
+
import {
|
|
23
|
+
existsSync,
|
|
24
|
+
readdirSync,
|
|
25
|
+
readFileSync,
|
|
26
|
+
rmSync,
|
|
27
|
+
statSync,
|
|
28
|
+
unlinkSync,
|
|
29
|
+
} from 'node:fs'
|
|
30
|
+
import { join } from 'node:path'
|
|
31
|
+
import { getAgentDir } from '@mariozechner/pi-coding-agent'
|
|
32
|
+
import { pidAlive, readAssignment } from './assignments.ts'
|
|
33
|
+
import { controlRecordPath } from './control.ts'
|
|
34
|
+
import { type SubagentsDataDirName, subagentsDataRoot } from './dataroot.ts'
|
|
35
|
+
import { readProcessLockStatus } from './lock.ts'
|
|
36
|
+
import { peerLockPath, readPresence } from './peers.ts'
|
|
37
|
+
|
|
38
|
+
export interface PruneReport {
|
|
39
|
+
cutoffIso: string
|
|
40
|
+
removed: Partial<Record<SubagentsDataDirName, number>>
|
|
41
|
+
skipped: Partial<Record<SubagentsDataDirName, number>>
|
|
42
|
+
skipReasons: string[]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
46
|
+
|
|
47
|
+
/** Mutable per-sweep accounting shared by the per-class policy functions. */
|
|
48
|
+
interface PruneLedger {
|
|
49
|
+
cutoffMs: number
|
|
50
|
+
removed: Partial<Record<SubagentsDataDirName, number>>
|
|
51
|
+
skipped: Partial<Record<SubagentsDataDirName, number>>
|
|
52
|
+
reasonCounts: Map<string, number>
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function markRemoved(ledger: PruneLedger, cls: SubagentsDataDirName): void {
|
|
56
|
+
ledger.removed[cls] = (ledger.removed[cls] ?? 0) + 1
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Count a skip; `reason` (optional) joins the human-readable skipReasons. */
|
|
60
|
+
function markSkipped(
|
|
61
|
+
ledger: PruneLedger,
|
|
62
|
+
cls: SubagentsDataDirName,
|
|
63
|
+
reason?: string,
|
|
64
|
+
): void {
|
|
65
|
+
ledger.skipped[cls] = (ledger.skipped[cls] ?? 0) + 1
|
|
66
|
+
if (reason !== undefined) {
|
|
67
|
+
const key = `${cls}: ${reason}`
|
|
68
|
+
ledger.reasonCounts.set(key, (ledger.reasonCounts.get(key) ?? 0) + 1)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Read a JSON file as unknown; null on any read/parse failure (fail closed). */
|
|
73
|
+
function readJson(path: string): Record<string, unknown> | null {
|
|
74
|
+
try {
|
|
75
|
+
const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
|
|
76
|
+
if (parsed == null || typeof parsed !== 'object') return null
|
|
77
|
+
if (Array.isArray(parsed)) return null
|
|
78
|
+
return parsed as Record<string, unknown>
|
|
79
|
+
} catch {
|
|
80
|
+
return null
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Date.parse-based timestamp; null on missing/non-string/unparseable. */
|
|
85
|
+
function parseTimestamp(value: unknown): number | null {
|
|
86
|
+
if (typeof value !== 'string') return null
|
|
87
|
+
const ms = Date.parse(value)
|
|
88
|
+
if (Number.isNaN(ms)) return null
|
|
89
|
+
return ms
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function stringField(
|
|
93
|
+
record: Record<string, unknown>,
|
|
94
|
+
key: string,
|
|
95
|
+
): string | null {
|
|
96
|
+
const value = record[key]
|
|
97
|
+
if (typeof value !== 'string' || value === '') return null
|
|
98
|
+
return value
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Directory entries; null when the dir is missing or unreadable (fail closed). */
|
|
102
|
+
function dirEntries(dir: string): string[] | null {
|
|
103
|
+
try {
|
|
104
|
+
return readdirSync(dir)
|
|
105
|
+
} catch {
|
|
106
|
+
return null
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Session file exists on disk (kept when present — resumable evidence). */
|
|
111
|
+
function sessionFileExists(sessionFile: string): boolean {
|
|
112
|
+
try {
|
|
113
|
+
return existsSync(sessionFile)
|
|
114
|
+
} catch {
|
|
115
|
+
return true
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Newest timestamp across a childId directory of records; null (fail closed)
|
|
121
|
+
* when the dir cannot be listed or any record lacks a parseable pick of
|
|
122
|
+
* `pick` fields (first parseable field wins per record).
|
|
123
|
+
*/
|
|
124
|
+
function newestTimestampAcrossDir(
|
|
125
|
+
dir: string,
|
|
126
|
+
pickFields: readonly string[],
|
|
127
|
+
): number | null {
|
|
128
|
+
const entries = dirEntries(dir)
|
|
129
|
+
if (entries === null) return null
|
|
130
|
+
let newest: number | null = null
|
|
131
|
+
for (const entry of entries) {
|
|
132
|
+
const record = readJson(join(dir, entry))
|
|
133
|
+
if (record === null) return null
|
|
134
|
+
let ts: number | null = null
|
|
135
|
+
for (const field of pickFields) {
|
|
136
|
+
const parsed = parseTimestamp(record[field])
|
|
137
|
+
if (parsed !== null) {
|
|
138
|
+
ts = parsed
|
|
139
|
+
break
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (ts === null) return null
|
|
143
|
+
if (newest === null || ts > newest) newest = ts
|
|
144
|
+
}
|
|
145
|
+
return newest
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Resolve a child's session file from the durable records: assignment first,
|
|
150
|
+
* then peer presence. Null when neither record yields a sessionFile.
|
|
151
|
+
*/
|
|
152
|
+
function resolveChildSessionFile(childId: string, root: string): string | null {
|
|
153
|
+
const assignment = readAssignment(childId, root)
|
|
154
|
+
if (assignment !== null) return assignment.sessionFile
|
|
155
|
+
const presence = readPresence(childId, root)
|
|
156
|
+
if (presence !== null) return presence.sessionFile
|
|
157
|
+
return null
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Liveness of a presence record via readProcessLockStatus, which throws
|
|
162
|
+
* "Unable to verify" by design when the claim cannot be inspected — the
|
|
163
|
+
* caller treats a throw as "not prunable".
|
|
164
|
+
*/
|
|
165
|
+
function presenceLockLive(
|
|
166
|
+
sessionFile: string,
|
|
167
|
+
): { live: boolean } | { error: true } {
|
|
168
|
+
try {
|
|
169
|
+
const status = readProcessLockStatus(peerLockPath(sessionFile))
|
|
170
|
+
return { live: status.live }
|
|
171
|
+
} catch {
|
|
172
|
+
return { error: true }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Shared policy for the two age-only, session-free classes (results,
|
|
177
|
+
// retired): newest activity is the record's single immutable timestamp and
|
|
178
|
+
// age past the cutoff is the whole eligibility rule.
|
|
179
|
+
function pruneImmutableTimestampedRecords(
|
|
180
|
+
dir: string,
|
|
181
|
+
cls: Extract<SubagentsDataDirName, 'results' | 'retired'>,
|
|
182
|
+
timestampField: string,
|
|
183
|
+
ledger: PruneLedger,
|
|
184
|
+
): void {
|
|
185
|
+
const entries = dirEntries(dir)
|
|
186
|
+
if (entries === null) {
|
|
187
|
+
markSkipped(ledger, cls, `${cls} dir unreadable`)
|
|
188
|
+
return
|
|
189
|
+
}
|
|
190
|
+
for (const entry of entries) {
|
|
191
|
+
if (!entry.endsWith('.json')) continue
|
|
192
|
+
const record = readJson(join(dir, entry))
|
|
193
|
+
if (record === null) {
|
|
194
|
+
markSkipped(ledger, cls, 'malformed record')
|
|
195
|
+
continue
|
|
196
|
+
}
|
|
197
|
+
const ts = parseTimestamp(record[timestampField])
|
|
198
|
+
if (ts === null) {
|
|
199
|
+
markSkipped(ledger, cls, `missing/unparseable ${timestampField}`)
|
|
200
|
+
continue
|
|
201
|
+
}
|
|
202
|
+
if (ts >= ledger.cutoffMs) {
|
|
203
|
+
markSkipped(ledger, cls)
|
|
204
|
+
continue
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
unlinkSync(join(dir, entry))
|
|
208
|
+
markRemoved(ledger, cls)
|
|
209
|
+
} catch {
|
|
210
|
+
markSkipped(ledger, cls, 'unlink failed')
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function pruneResults(dir: string, ledger: PruneLedger): void {
|
|
216
|
+
pruneImmutableTimestampedRecords(dir, 'results', 'createdAt', ledger)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function pruneAssignments(
|
|
220
|
+
dir: string,
|
|
221
|
+
ledger: PruneLedger,
|
|
222
|
+
root: string,
|
|
223
|
+
): void {
|
|
224
|
+
const entries = dirEntries(dir)
|
|
225
|
+
if (entries === null) {
|
|
226
|
+
markSkipped(ledger, 'assignments', 'assignments dir unreadable')
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
for (const entry of entries) {
|
|
230
|
+
if (!entry.endsWith('.json')) continue
|
|
231
|
+
const record = readJson(join(dir, entry))
|
|
232
|
+
if (record === null) {
|
|
233
|
+
markSkipped(ledger, 'assignments', 'malformed record')
|
|
234
|
+
continue
|
|
235
|
+
}
|
|
236
|
+
const updatedAt = parseTimestamp(record.updatedAt)
|
|
237
|
+
if (updatedAt === null) {
|
|
238
|
+
markSkipped(ledger, 'assignments', 'missing/unparseable updatedAt')
|
|
239
|
+
continue
|
|
240
|
+
}
|
|
241
|
+
if (updatedAt >= ledger.cutoffMs) {
|
|
242
|
+
markSkipped(ledger, 'assignments')
|
|
243
|
+
continue
|
|
244
|
+
}
|
|
245
|
+
const claim = record.claim
|
|
246
|
+
if (claim == null || typeof claim !== 'object') {
|
|
247
|
+
markSkipped(ledger, 'assignments', 'malformed record')
|
|
248
|
+
continue
|
|
249
|
+
}
|
|
250
|
+
const pid = (claim as Record<string, unknown>).pid
|
|
251
|
+
if (typeof pid !== 'number') {
|
|
252
|
+
markSkipped(ledger, 'assignments', 'malformed record')
|
|
253
|
+
continue
|
|
254
|
+
}
|
|
255
|
+
if (pidAlive(pid)) {
|
|
256
|
+
markSkipped(ledger, 'assignments', 'live claim pid')
|
|
257
|
+
continue
|
|
258
|
+
}
|
|
259
|
+
const sessionFile = stringField(record, 'sessionFile')
|
|
260
|
+
if (sessionFile === null) {
|
|
261
|
+
markSkipped(ledger, 'assignments', 'missing sessionFile')
|
|
262
|
+
continue
|
|
263
|
+
}
|
|
264
|
+
if (sessionFileExists(sessionFile)) {
|
|
265
|
+
markSkipped(
|
|
266
|
+
ledger,
|
|
267
|
+
'assignments',
|
|
268
|
+
'session file still exists (resumable)',
|
|
269
|
+
)
|
|
270
|
+
continue
|
|
271
|
+
}
|
|
272
|
+
try {
|
|
273
|
+
unlinkSync(join(dir, entry))
|
|
274
|
+
markRemoved(ledger, 'assignments')
|
|
275
|
+
} catch {
|
|
276
|
+
markSkipped(ledger, 'assignments', 'unlink failed')
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// AIDEV-NOTE (PMR-KT90): peers prune their presence file AND inbox dir as ONE
|
|
282
|
+
// candidate. An undrained inbox of a dead child WITH a session file on disk
|
|
283
|
+
// stays — at-least-once redelivery is intentional.
|
|
284
|
+
function prunePeers(dir: string, ledger: PruneLedger, root: string): void {
|
|
285
|
+
const entries = dirEntries(dir)
|
|
286
|
+
if (entries === null) {
|
|
287
|
+
markSkipped(ledger, 'peers', 'peers dir unreadable')
|
|
288
|
+
return
|
|
289
|
+
}
|
|
290
|
+
for (const entry of entries) {
|
|
291
|
+
if (!entry.endsWith('.json')) continue
|
|
292
|
+
const childId = entry.slice(0, -'.json'.length)
|
|
293
|
+
const record = readJson(join(dir, entry))
|
|
294
|
+
if (record === null) {
|
|
295
|
+
markSkipped(ledger, 'peers', 'malformed record')
|
|
296
|
+
continue
|
|
297
|
+
}
|
|
298
|
+
const updatedAt = parseTimestamp(record.updatedAt)
|
|
299
|
+
const sessionFile = stringField(record, 'sessionFile')
|
|
300
|
+
if (updatedAt === null || sessionFile === null) {
|
|
301
|
+
markSkipped(ledger, 'peers', 'malformed record')
|
|
302
|
+
continue
|
|
303
|
+
}
|
|
304
|
+
let newest = updatedAt
|
|
305
|
+
const inboxDirPath = join(dir, childId, 'inbox')
|
|
306
|
+
const inboxEntries = dirEntries(inboxDirPath)
|
|
307
|
+
// AIDEV-NOTE (PMR-KT90): an inbox dir that EXISTS but cannot be listed
|
|
308
|
+
// (EACCES, EIO) is not an empty inbox — fail closed and keep the whole
|
|
309
|
+
// candidate instead of force-removing an unread inbox.
|
|
310
|
+
if (inboxEntries === null && existsSync(inboxDirPath)) {
|
|
311
|
+
markSkipped(ledger, 'peers', 'inbox unreadable')
|
|
312
|
+
continue
|
|
313
|
+
}
|
|
314
|
+
if (inboxEntries !== null) {
|
|
315
|
+
for (const msg of inboxEntries) {
|
|
316
|
+
const message = readJson(join(dir, childId, 'inbox', msg))
|
|
317
|
+
if (message === null) {
|
|
318
|
+
markSkipped(ledger, 'peers', 'malformed inbox message')
|
|
319
|
+
newest = Number.NaN
|
|
320
|
+
break
|
|
321
|
+
}
|
|
322
|
+
const sentAt = parseTimestamp(message.sentAt)
|
|
323
|
+
if (sentAt === null) {
|
|
324
|
+
markSkipped(ledger, 'peers', 'malformed inbox message')
|
|
325
|
+
newest = Number.NaN
|
|
326
|
+
break
|
|
327
|
+
}
|
|
328
|
+
if (sentAt > newest) newest = sentAt
|
|
329
|
+
}
|
|
330
|
+
if (Number.isNaN(newest)) continue
|
|
331
|
+
}
|
|
332
|
+
if (newest >= ledger.cutoffMs) {
|
|
333
|
+
markSkipped(ledger, 'peers')
|
|
334
|
+
continue
|
|
335
|
+
}
|
|
336
|
+
const lockState = presenceLockLive(sessionFile)
|
|
337
|
+
if ('error' in lockState) {
|
|
338
|
+
markSkipped(ledger, 'peers', 'liveness inspection failed')
|
|
339
|
+
continue
|
|
340
|
+
}
|
|
341
|
+
if (lockState.live) {
|
|
342
|
+
markSkipped(ledger, 'peers', 'live presence lock')
|
|
343
|
+
continue
|
|
344
|
+
}
|
|
345
|
+
if (sessionFileExists(sessionFile)) {
|
|
346
|
+
markSkipped(ledger, 'peers', 'session file still exists (resumable)')
|
|
347
|
+
continue
|
|
348
|
+
}
|
|
349
|
+
let removedAny = false
|
|
350
|
+
let failed = false
|
|
351
|
+
try {
|
|
352
|
+
rmSync(join(dir, childId), { recursive: true, force: true })
|
|
353
|
+
removedAny = true
|
|
354
|
+
} catch {
|
|
355
|
+
failed = true
|
|
356
|
+
}
|
|
357
|
+
try {
|
|
358
|
+
unlinkSync(join(dir, entry))
|
|
359
|
+
removedAny = true
|
|
360
|
+
} catch {
|
|
361
|
+
failed = true
|
|
362
|
+
}
|
|
363
|
+
if (failed && !removedAny) {
|
|
364
|
+
markSkipped(ledger, 'peers', 'delete failed')
|
|
365
|
+
continue
|
|
366
|
+
}
|
|
367
|
+
if (removedAny) markRemoved(ledger, 'peers')
|
|
368
|
+
// AIDEV-NOTE: PMR-VWZB — a partial removal is reported as BOTH: the
|
|
369
|
+
// removed count reflects what did disappear, and a distinct skip reason
|
|
370
|
+
// surfaces the orphaned remainder instead of claiming a full removal.
|
|
371
|
+
if (failed) markSkipped(ledger, 'peers', 'delete failed (partial)')
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* True when the child behind an ask record is provably not live: assignment
|
|
377
|
+
* claim pid dead, or peer presence lock dead. When neither identity record
|
|
378
|
+
* exists the child has no live evidence left (both its records were already
|
|
379
|
+
* prunable/removed) and is treated as not live — the sessionFile-missing
|
|
380
|
+
* check below still applies. Any liveness inspection failure keeps.
|
|
381
|
+
*/
|
|
382
|
+
function askChildNotLive(
|
|
383
|
+
childId: string,
|
|
384
|
+
root: string,
|
|
385
|
+
ledger: PruneLedger,
|
|
386
|
+
): boolean | null {
|
|
387
|
+
const assignment = readAssignment(childId, root)
|
|
388
|
+
if (assignment !== null) {
|
|
389
|
+
let alive: boolean
|
|
390
|
+
try {
|
|
391
|
+
alive = pidAlive(assignment.claim.pid)
|
|
392
|
+
} catch {
|
|
393
|
+
markSkipped(ledger, 'asks', 'liveness inspection failed')
|
|
394
|
+
return null
|
|
395
|
+
}
|
|
396
|
+
if (alive) {
|
|
397
|
+
markSkipped(ledger, 'asks', 'live claim pid')
|
|
398
|
+
return false
|
|
399
|
+
}
|
|
400
|
+
return true
|
|
401
|
+
}
|
|
402
|
+
const presence = readPresence(childId, root)
|
|
403
|
+
if (presence !== null) {
|
|
404
|
+
const lockState = presenceLockLive(presence.sessionFile)
|
|
405
|
+
if ('error' in lockState) {
|
|
406
|
+
markSkipped(ledger, 'asks', 'liveness inspection failed')
|
|
407
|
+
return null
|
|
408
|
+
}
|
|
409
|
+
if (lockState.live) {
|
|
410
|
+
markSkipped(ledger, 'asks', 'live presence lock')
|
|
411
|
+
return false
|
|
412
|
+
}
|
|
413
|
+
return true
|
|
414
|
+
}
|
|
415
|
+
return true
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// AIDEV-NOTE (PMR-KT90): ask + reply + control records are one candidate —
|
|
419
|
+
// a blocked child waiting on a reply is never prunable (its session file
|
|
420
|
+
// exists on disk).
|
|
421
|
+
function pruneAsks(dir: string, ledger: PruneLedger, root: string): void {
|
|
422
|
+
const entries = dirEntries(dir)
|
|
423
|
+
if (entries === null) {
|
|
424
|
+
markSkipped(ledger, 'asks', 'asks dir unreadable')
|
|
425
|
+
return
|
|
426
|
+
}
|
|
427
|
+
for (const entry of entries) {
|
|
428
|
+
if (!entry.endsWith('.json')) continue
|
|
429
|
+
if (entry.endsWith('.reply.json')) continue
|
|
430
|
+
if (entry.endsWith('.control.json')) continue
|
|
431
|
+
const childId = entry.slice(0, -'.json'.length)
|
|
432
|
+
const record = readJson(join(dir, entry))
|
|
433
|
+
if (record === null) {
|
|
434
|
+
markSkipped(ledger, 'asks', 'malformed record')
|
|
435
|
+
continue
|
|
436
|
+
}
|
|
437
|
+
const createdAt = parseTimestamp(record.createdAt)
|
|
438
|
+
const sessionFile = stringField(record, 'sessionFile')
|
|
439
|
+
if (createdAt === null || sessionFile === null) {
|
|
440
|
+
markSkipped(ledger, 'asks', 'malformed record')
|
|
441
|
+
continue
|
|
442
|
+
}
|
|
443
|
+
let newest = createdAt
|
|
444
|
+
const reply = readJson(join(dir, `${childId}.reply.json`))
|
|
445
|
+
if (reply !== null) {
|
|
446
|
+
const repliedAt = parseTimestamp(reply.repliedAt)
|
|
447
|
+
if (repliedAt === null) {
|
|
448
|
+
markSkipped(ledger, 'asks', 'missing/unparseable repliedAt')
|
|
449
|
+
continue
|
|
450
|
+
}
|
|
451
|
+
if (repliedAt > newest) newest = repliedAt
|
|
452
|
+
}
|
|
453
|
+
if (newest >= ledger.cutoffMs) {
|
|
454
|
+
markSkipped(ledger, 'asks')
|
|
455
|
+
continue
|
|
456
|
+
}
|
|
457
|
+
const notLive = askChildNotLive(childId, root, ledger)
|
|
458
|
+
if (notLive === null) continue
|
|
459
|
+
if (!notLive) continue
|
|
460
|
+
if (sessionFileExists(sessionFile)) {
|
|
461
|
+
markSkipped(ledger, 'asks', 'session file still exists (resumable)')
|
|
462
|
+
continue
|
|
463
|
+
}
|
|
464
|
+
let removedAny = false
|
|
465
|
+
let failed = false
|
|
466
|
+
const targets = [
|
|
467
|
+
join(dir, entry),
|
|
468
|
+
join(dir, `${childId}.reply.json`),
|
|
469
|
+
join(dir, `${childId}.control.json`),
|
|
470
|
+
]
|
|
471
|
+
for (const target of targets) {
|
|
472
|
+
try {
|
|
473
|
+
unlinkSync(target)
|
|
474
|
+
removedAny = true
|
|
475
|
+
} catch (error) {
|
|
476
|
+
// AIDEV-NOTE (PMR-KT90): ENOENT is the expected missing-sibling case
|
|
477
|
+
// (no reply/control record). Any OTHER unlink failure (EACCES,
|
|
478
|
+
// EIO, ...) must surface — silently counting it as removed would
|
|
479
|
+
// report a record deleted that is still on disk (prunePeers sets
|
|
480
|
+
// `failed` the same way).
|
|
481
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') failed = true
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
if (failed && !removedAny) {
|
|
485
|
+
markSkipped(ledger, 'asks', 'delete failed')
|
|
486
|
+
continue
|
|
487
|
+
}
|
|
488
|
+
if (removedAny) markRemoved(ledger, 'asks')
|
|
489
|
+
// AIDEV-NOTE: PMR-VWZB — a partial removal is reported as BOTH: the
|
|
490
|
+
// removed count reflects the file(s) that did disappear, and a distinct
|
|
491
|
+
// skip reason surfaces the orphaned sibling. Without it the ledger
|
|
492
|
+
// claimed a full removal while an unlinkable .reply.json/.control.json
|
|
493
|
+
// stayed behind — uncollectable later, because pruneAsks only iterates
|
|
494
|
+
// <childId>.json candidates.
|
|
495
|
+
if (failed) markSkipped(ledger, 'asks', 'delete failed (partial)')
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Recursively collect SESSION IDS (not file names) under the sessions root.
|
|
501
|
+
* Pi session files are named `<ISO-timestamp>_<sessionId>.jsonl` (index.ts
|
|
502
|
+
* spawn), so each file contributes its base name AND the portion after the
|
|
503
|
+
* first underscore — both `<id>.jsonl` and `<ts>_<id>.jsonl` shapes resolve
|
|
504
|
+
* to their id. Files without an underscore contribute only the bare id.
|
|
505
|
+
* Null when the scan itself fails (fail closed — keep the inbox).
|
|
506
|
+
*/
|
|
507
|
+
function scanSessionIds(sessionsRoot: string): Set<string> | null {
|
|
508
|
+
const ids = new Set<string>()
|
|
509
|
+
const visit = (dir: string): boolean => {
|
|
510
|
+
let entries: import('node:fs').Dirent[]
|
|
511
|
+
try {
|
|
512
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
513
|
+
} catch {
|
|
514
|
+
return false
|
|
515
|
+
}
|
|
516
|
+
for (const entry of entries) {
|
|
517
|
+
if (entry.isDirectory()) {
|
|
518
|
+
if (!visit(join(dir, entry.name))) return false
|
|
519
|
+
} else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
|
|
520
|
+
const base = entry.name.slice(0, -'.jsonl'.length)
|
|
521
|
+
ids.add(base)
|
|
522
|
+
const underscore = base.indexOf('_')
|
|
523
|
+
if (underscore !== -1) ids.add(base.slice(underscore + 1))
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return true
|
|
527
|
+
}
|
|
528
|
+
if (!visit(sessionsRoot)) return null
|
|
529
|
+
return ids
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function pruneOwnerInbox(
|
|
533
|
+
dir: string,
|
|
534
|
+
ledger: PruneLedger,
|
|
535
|
+
sessionsRoot: string | null,
|
|
536
|
+
): void {
|
|
537
|
+
const entries = dirEntries(dir)
|
|
538
|
+
if (entries === null) {
|
|
539
|
+
markSkipped(ledger, 'inbox', 'inbox dir unreadable')
|
|
540
|
+
return
|
|
541
|
+
}
|
|
542
|
+
let cachedSessionIds: Set<string> | null | undefined
|
|
543
|
+
for (const entry of entries) {
|
|
544
|
+
const inboxDir = join(dir, entry)
|
|
545
|
+
let statIsDir = true
|
|
546
|
+
try {
|
|
547
|
+
statIsDir = statSync(inboxDir).isDirectory()
|
|
548
|
+
} catch {
|
|
549
|
+
markSkipped(ledger, 'inbox', 'stat failed')
|
|
550
|
+
continue
|
|
551
|
+
}
|
|
552
|
+
if (!statIsDir) continue
|
|
553
|
+
const msgEntries = dirEntries(inboxDir)
|
|
554
|
+
if (msgEntries === null) {
|
|
555
|
+
markSkipped(ledger, 'inbox', 'inbox dir unreadable')
|
|
556
|
+
continue
|
|
557
|
+
}
|
|
558
|
+
let newest: number | null = null
|
|
559
|
+
let malformed = false
|
|
560
|
+
for (const msg of msgEntries) {
|
|
561
|
+
const message = readJson(join(inboxDir, msg))
|
|
562
|
+
if (message === null) {
|
|
563
|
+
malformed = true
|
|
564
|
+
break
|
|
565
|
+
}
|
|
566
|
+
const sentAt = parseTimestamp(message.sentAt)
|
|
567
|
+
if (sentAt === null) {
|
|
568
|
+
malformed = true
|
|
569
|
+
break
|
|
570
|
+
}
|
|
571
|
+
if (newest === null || sentAt > newest) newest = sentAt
|
|
572
|
+
}
|
|
573
|
+
if (malformed || newest === null) {
|
|
574
|
+
markSkipped(ledger, 'inbox', 'malformed record')
|
|
575
|
+
continue
|
|
576
|
+
}
|
|
577
|
+
if (newest >= ledger.cutoffMs) {
|
|
578
|
+
markSkipped(ledger, 'inbox')
|
|
579
|
+
continue
|
|
580
|
+
}
|
|
581
|
+
if (sessionsRoot === null) {
|
|
582
|
+
markSkipped(ledger, 'inbox', 'sessions root unavailable')
|
|
583
|
+
continue
|
|
584
|
+
}
|
|
585
|
+
// AIDEV-NOTE (PMR-KT90): the recursive sessions walk is hoisted into a
|
|
586
|
+
// lazily-computed cache — the result cannot change during a single
|
|
587
|
+
// sweep, so it runs at most once per pruneOwnerInbox call instead of
|
|
588
|
+
// once per aged inbox dir. `undefined` = not yet scanned.
|
|
589
|
+
if (cachedSessionIds === undefined) {
|
|
590
|
+
cachedSessionIds = scanSessionIds(sessionsRoot)
|
|
591
|
+
}
|
|
592
|
+
if (cachedSessionIds === null) {
|
|
593
|
+
markSkipped(ledger, 'inbox', 'session scan failed')
|
|
594
|
+
continue
|
|
595
|
+
}
|
|
596
|
+
// AIDEV-NOTE (PMR-KT90): match the SESSION ID, not the file name — pi
|
|
597
|
+
// names session files `<ISO-ts>_<sessionId>.jsonl`, so a bare
|
|
598
|
+
// `${entry}.jsonl` name check never matches a real session file and the
|
|
599
|
+
// resumability guard would be dead code.
|
|
600
|
+
if (cachedSessionIds.has(entry)) {
|
|
601
|
+
markSkipped(ledger, 'inbox', 'parent session file still exists')
|
|
602
|
+
continue
|
|
603
|
+
}
|
|
604
|
+
try {
|
|
605
|
+
rmSync(inboxDir, { recursive: true, force: true })
|
|
606
|
+
markRemoved(ledger, 'inbox')
|
|
607
|
+
} catch {
|
|
608
|
+
markSkipped(ledger, 'inbox', 'delete failed')
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* Does a source mailbox record for this delivered marker still exist?
|
|
615
|
+
* Scopes in use (index.ts / subagent-done.ts): `<childId>` (ask replies +
|
|
616
|
+
* peer inbox), `<ownerSessionId>` (owner inbox), `control:<childId>`.
|
|
617
|
+
* Returns null when a source scan itself fails — keep the marker.
|
|
618
|
+
*
|
|
619
|
+
* AIDEV-NOTE (PMR-KT90): `scope` here is the ON-DISK marker dir name, which
|
|
620
|
+
* was written through delivered.ts sanitizeScope — ':' maps to '_', so the
|
|
621
|
+
* control scope arrives as `control_<childId>`, never `control:<childId>`.
|
|
622
|
+
* Match the sanitized prefix and slice the (already sanitized) childId off;
|
|
623
|
+
* controlRecordPath re-applies the same mapping, so this mirrors the write
|
|
624
|
+
* side exactly.
|
|
625
|
+
*/
|
|
626
|
+
function deliveredSourceExists(
|
|
627
|
+
scope: string,
|
|
628
|
+
requestId: string,
|
|
629
|
+
root: string,
|
|
630
|
+
): boolean | null {
|
|
631
|
+
// Ask reply source: asks/<childId>.reply.json with matching askId.
|
|
632
|
+
const reply = readJson(join(root, 'asks', `${scope}.reply.json`))
|
|
633
|
+
if (reply !== null && reply.askId === requestId) return true
|
|
634
|
+
|
|
635
|
+
// Peer inbox source: peers/<childId>/inbox/*.json with matching messageId.
|
|
636
|
+
const peerInbox = dirEntries(join(root, 'peers', scope, 'inbox'))
|
|
637
|
+
if (peerInbox !== null) {
|
|
638
|
+
for (const msg of peerInbox) {
|
|
639
|
+
const message = readJson(join(root, 'peers', scope, 'inbox', msg))
|
|
640
|
+
if (message !== null && message.messageId === requestId) return true
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// Owner inbox source: inbox/<ownerSessionId>/*.json with matching messageId.
|
|
645
|
+
const ownerInbox = dirEntries(join(root, 'inbox', scope))
|
|
646
|
+
if (ownerInbox !== null) {
|
|
647
|
+
for (const msg of ownerInbox) {
|
|
648
|
+
const message = readJson(join(root, 'inbox', scope, msg))
|
|
649
|
+
if (message !== null && message.messageId === requestId) return true
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// Control source: control_<childId> scope (sanitized on disk),
|
|
654
|
+
// asks/<childId>.control.json.
|
|
655
|
+
if (scope.startsWith('control_')) {
|
|
656
|
+
const childId = scope.slice('control_'.length)
|
|
657
|
+
const control = readJson(controlRecordPath(childId, root))
|
|
658
|
+
if (control !== null && control.requestId === requestId) return true
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// Distinguish "scanned everything, no match" from "a scan failed".
|
|
662
|
+
const replyExists = existsSync(join(root, 'asks', `${scope}.reply.json`))
|
|
663
|
+
// AIDEV-NOTE (PMR-KT90): a reply record that EXISTS but is unreadable or
|
|
664
|
+
// malformed (readJson → null) is not "no source" — fail closed and keep
|
|
665
|
+
// the marker rather than re-opening the duplicate-delivery window.
|
|
666
|
+
if (replyExists && reply === null) return null
|
|
667
|
+
if (replyExists) return false
|
|
668
|
+
const peerInboxMissing = !existsSync(join(root, 'peers', scope, 'inbox'))
|
|
669
|
+
const ownerInboxMissing = !existsSync(join(root, 'inbox', scope))
|
|
670
|
+
const controlMissing =
|
|
671
|
+
!scope.startsWith('control_') ||
|
|
672
|
+
!existsSync(controlRecordPath(scope.slice('control_'.length), root))
|
|
673
|
+
if (peerInboxMissing && ownerInboxMissing && controlMissing) return false
|
|
674
|
+
return null
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// AIDEV-NOTE (PMR-KT90): pruning a delivered marker while its source record
|
|
678
|
+
// still exists re-opens the exactly-once duplicate-delivery window — any
|
|
679
|
+
// doubt keeps the marker.
|
|
680
|
+
function pruneDelivered(dir: string, ledger: PruneLedger, root: string): void {
|
|
681
|
+
const entries = dirEntries(dir)
|
|
682
|
+
if (entries === null) {
|
|
683
|
+
markSkipped(ledger, 'delivered', 'delivered dir unreadable')
|
|
684
|
+
return
|
|
685
|
+
}
|
|
686
|
+
for (const scope of entries) {
|
|
687
|
+
const scopeDir = join(dir, scope)
|
|
688
|
+
let requestIds: string[] | null
|
|
689
|
+
try {
|
|
690
|
+
if (!statSync(scopeDir).isDirectory()) continue
|
|
691
|
+
requestIds = readdirSync(scopeDir)
|
|
692
|
+
} catch {
|
|
693
|
+
markSkipped(ledger, 'delivered', 'stat failed')
|
|
694
|
+
continue
|
|
695
|
+
}
|
|
696
|
+
for (const requestId of requestIds) {
|
|
697
|
+
const markerPath = join(scopeDir, requestId)
|
|
698
|
+
let mtimeMs: number
|
|
699
|
+
try {
|
|
700
|
+
mtimeMs = statSync(markerPath).mtimeMs
|
|
701
|
+
} catch {
|
|
702
|
+
markSkipped(ledger, 'delivered', 'stat failed')
|
|
703
|
+
continue
|
|
704
|
+
}
|
|
705
|
+
if (mtimeMs >= ledger.cutoffMs) {
|
|
706
|
+
markSkipped(ledger, 'delivered')
|
|
707
|
+
continue
|
|
708
|
+
}
|
|
709
|
+
const sourceExists = deliveredSourceExists(scope, requestId, root)
|
|
710
|
+
if (sourceExists === null) {
|
|
711
|
+
markSkipped(ledger, 'delivered', 'source scan failed')
|
|
712
|
+
continue
|
|
713
|
+
}
|
|
714
|
+
if (sourceExists) {
|
|
715
|
+
markSkipped(ledger, 'delivered', 'source record still exists')
|
|
716
|
+
continue
|
|
717
|
+
}
|
|
718
|
+
try {
|
|
719
|
+
unlinkSync(markerPath)
|
|
720
|
+
markRemoved(ledger, 'delivered')
|
|
721
|
+
} catch {
|
|
722
|
+
markSkipped(ledger, 'delivered', 'unlink failed')
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
function pruneInterrupts(dir: string, ledger: PruneLedger): void {
|
|
729
|
+
const entries = dirEntries(dir)
|
|
730
|
+
if (entries === null) {
|
|
731
|
+
markSkipped(ledger, 'interrupts', 'interrupts dir unreadable')
|
|
732
|
+
return
|
|
733
|
+
}
|
|
734
|
+
for (const entry of entries) {
|
|
735
|
+
if (!entry.endsWith('.json')) continue
|
|
736
|
+
const record = readJson(join(dir, entry))
|
|
737
|
+
if (record === null) {
|
|
738
|
+
markSkipped(ledger, 'interrupts', 'malformed record')
|
|
739
|
+
continue
|
|
740
|
+
}
|
|
741
|
+
const sentAt = parseTimestamp(record.sentAt)
|
|
742
|
+
const sessionFile = stringField(record, 'sessionFile')
|
|
743
|
+
if (sentAt === null || sessionFile === null) {
|
|
744
|
+
markSkipped(ledger, 'interrupts', 'malformed record')
|
|
745
|
+
continue
|
|
746
|
+
}
|
|
747
|
+
if (sentAt >= ledger.cutoffMs) {
|
|
748
|
+
markSkipped(ledger, 'interrupts')
|
|
749
|
+
continue
|
|
750
|
+
}
|
|
751
|
+
if (sessionFileExists(sessionFile)) {
|
|
752
|
+
markSkipped(
|
|
753
|
+
ledger,
|
|
754
|
+
'interrupts',
|
|
755
|
+
'session file still exists (replay source)',
|
|
756
|
+
)
|
|
757
|
+
continue
|
|
758
|
+
}
|
|
759
|
+
try {
|
|
760
|
+
unlinkSync(join(dir, entry))
|
|
761
|
+
markRemoved(ledger, 'interrupts')
|
|
762
|
+
} catch {
|
|
763
|
+
markSkipped(ledger, 'interrupts', 'unlink failed')
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Shared policy for the childId-keyed replay-evidence classes
|
|
770
|
+
* (tool-effects, peer-bindings): eligible ONLY when the child's session
|
|
771
|
+
* file is gone and the dir's newest activity is older than the cutoff.
|
|
772
|
+
* The childId dir is pruned as one candidate; the session file resolves
|
|
773
|
+
* through assignments/<childId>.json then peers/<childId>.json —
|
|
774
|
+
* unresolvable keeps.
|
|
775
|
+
*/
|
|
776
|
+
function pruneChildIdKeyedDir(
|
|
777
|
+
baseDir: string,
|
|
778
|
+
cls: Extract<SubagentsDataDirName, 'tool-effects' | 'peer-bindings'>,
|
|
779
|
+
pickFields: readonly string[],
|
|
780
|
+
ledger: PruneLedger,
|
|
781
|
+
root: string,
|
|
782
|
+
): void {
|
|
783
|
+
const entries = dirEntries(baseDir)
|
|
784
|
+
if (entries === null) {
|
|
785
|
+
markSkipped(ledger, cls, `${cls} dir unreadable`)
|
|
786
|
+
return
|
|
787
|
+
}
|
|
788
|
+
for (const childId of entries) {
|
|
789
|
+
const childDir = join(baseDir, childId)
|
|
790
|
+
let isDir = true
|
|
791
|
+
try {
|
|
792
|
+
isDir = statSync(childDir).isDirectory()
|
|
793
|
+
} catch {
|
|
794
|
+
markSkipped(ledger, cls, 'stat failed')
|
|
795
|
+
continue
|
|
796
|
+
}
|
|
797
|
+
if (!isDir) continue
|
|
798
|
+
// AIDEV-NOTE: PMR-S7TF — an EMPTY childId dir (zero records, e.g. left
|
|
799
|
+
// behind by an interrupted rmSync) is not a malformed record: it lists
|
|
800
|
+
// fine and carries no replay evidence, so it skips the timestamp check
|
|
801
|
+
// and stays prunable under the same session-file guard instead of being
|
|
802
|
+
// kept forever with a misleading reason. Unreadable and malformed stay
|
|
803
|
+
// distinct fail-closed cases.
|
|
804
|
+
const childEntries = dirEntries(childDir)
|
|
805
|
+
if (childEntries === null) {
|
|
806
|
+
markSkipped(ledger, cls, 'child dir unreadable')
|
|
807
|
+
continue
|
|
808
|
+
}
|
|
809
|
+
if (childEntries.length > 0) {
|
|
810
|
+
const newest = newestTimestampAcrossDir(childDir, pickFields)
|
|
811
|
+
if (newest === null) {
|
|
812
|
+
markSkipped(ledger, cls, 'malformed record')
|
|
813
|
+
continue
|
|
814
|
+
}
|
|
815
|
+
if (newest >= ledger.cutoffMs) {
|
|
816
|
+
markSkipped(ledger, cls)
|
|
817
|
+
continue
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
const sessionFile = resolveChildSessionFile(childId, root)
|
|
821
|
+
if (sessionFile === null) {
|
|
822
|
+
markSkipped(ledger, cls, 'session file unresolvable')
|
|
823
|
+
continue
|
|
824
|
+
}
|
|
825
|
+
if (sessionFileExists(sessionFile)) {
|
|
826
|
+
markSkipped(ledger, cls, 'session file still exists (replay source)')
|
|
827
|
+
continue
|
|
828
|
+
}
|
|
829
|
+
try {
|
|
830
|
+
rmSync(childDir, { recursive: true, force: true })
|
|
831
|
+
markRemoved(ledger, cls)
|
|
832
|
+
} catch {
|
|
833
|
+
markSkipped(ledger, cls, 'delete failed')
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Retention sweep across the subagents data root. Never enumerates
|
|
840
|
+
* result-ref-reservations or spawn-seq for deletion; every class fails
|
|
841
|
+
* closed (see module AIDEV-NOTEs). One malformed/unreadable record never
|
|
842
|
+
* aborts the sweep.
|
|
843
|
+
*/
|
|
844
|
+
export function pruneSubagentsData(options: {
|
|
845
|
+
retentionDays: number
|
|
846
|
+
now?: () => Date
|
|
847
|
+
root?: string
|
|
848
|
+
agentDir?: string
|
|
849
|
+
}): PruneReport {
|
|
850
|
+
const nowFn = options.now ?? ((): Date => new Date())
|
|
851
|
+
const nowMs = nowFn().getTime()
|
|
852
|
+
const cutoffMs = nowMs - options.retentionDays * DAY_MS
|
|
853
|
+
const root = options.root ?? subagentsDataRoot()
|
|
854
|
+
|
|
855
|
+
const ledger: PruneLedger = {
|
|
856
|
+
cutoffMs,
|
|
857
|
+
removed: {},
|
|
858
|
+
skipped: {},
|
|
859
|
+
reasonCounts: new Map<string, number>(),
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// Order matters: classes whose liveness/session resolution reads another
|
|
863
|
+
// class's records (asks reads assignments/peers; tool-effects and
|
|
864
|
+
// peer-bindings resolve via assignments/peers) run BEFORE those source
|
|
865
|
+
// classes are pruned, so one sweep never prunes its own evidence mid-pass.
|
|
866
|
+
// Concretely: pruneAsks runs BEFORE prunePeers — a peer pruned first
|
|
867
|
+
// would drop askChildNotLive into its no-evidence fallback instead of the
|
|
868
|
+
// accurate presence-lock check. pruneDelivered scans asks/peers/inbox
|
|
869
|
+
// sources, so it also runs before all three. prunePeers itself reads no
|
|
870
|
+
// other pruned class, so moving it after pruneAsks breaks nothing.
|
|
871
|
+
pruneResults(join(root, 'results'), ledger)
|
|
872
|
+
pruneImmutableTimestampedRecords(
|
|
873
|
+
join(root, 'retired'),
|
|
874
|
+
'retired',
|
|
875
|
+
'retiredAt',
|
|
876
|
+
ledger,
|
|
877
|
+
)
|
|
878
|
+
pruneInterrupts(join(root, 'interrupts'), ledger)
|
|
879
|
+
pruneDelivered(join(root, 'delivered'), ledger, root)
|
|
880
|
+
pruneChildIdKeyedDir(
|
|
881
|
+
join(root, 'tool-effects'),
|
|
882
|
+
'tool-effects',
|
|
883
|
+
['createdAt'],
|
|
884
|
+
ledger,
|
|
885
|
+
root,
|
|
886
|
+
)
|
|
887
|
+
pruneChildIdKeyedDir(
|
|
888
|
+
join(root, 'peer-bindings'),
|
|
889
|
+
'peer-bindings',
|
|
890
|
+
['lastActivityAt', 'createdAt'],
|
|
891
|
+
ledger,
|
|
892
|
+
root,
|
|
893
|
+
)
|
|
894
|
+
pruneAsks(join(root, 'asks'), ledger, root)
|
|
895
|
+
prunePeers(join(root, 'peers'), ledger, root)
|
|
896
|
+
pruneAssignments(join(root, 'assignments'), ledger, root)
|
|
897
|
+
|
|
898
|
+
// Owner inbox needs the sessions root OUTSIDE the data root. Only this
|
|
899
|
+
// default resolution reads getAgentDir(); the injectable agentDir keeps
|
|
900
|
+
// tests (and any non-default install) off the default path.
|
|
901
|
+
let sessionsRoot: string | null = null
|
|
902
|
+
const agentDir = options.agentDir ?? getAgentDir()
|
|
903
|
+
sessionsRoot = join(agentDir, 'sessions')
|
|
904
|
+
pruneOwnerInbox(join(root, 'inbox'), ledger, sessionsRoot)
|
|
905
|
+
|
|
906
|
+
const skipReasons: string[] = []
|
|
907
|
+
for (const [key, count] of ledger.reasonCounts) {
|
|
908
|
+
skipReasons.push(`${key} (${count})`)
|
|
909
|
+
}
|
|
910
|
+
skipReasons.sort()
|
|
911
|
+
|
|
912
|
+
return {
|
|
913
|
+
cutoffIso: new Date(cutoffMs).toISOString(),
|
|
914
|
+
removed: ledger.removed,
|
|
915
|
+
skipped: ledger.skipped,
|
|
916
|
+
skipReasons,
|
|
917
|
+
}
|
|
918
|
+
}
|