@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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.
Files changed (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,2044 @@
1
+ /**
2
+ * report-cleanup.ts — read-only inventory, then explicitly confirmed file removal.
3
+ *
4
+ * This module is the backend half of `/subagents cleanup`: it never renders UI,
5
+ * never recursively deletes a directory and never uses `force`. A plan is an
6
+ * immutable snapshot of candidate paths, sizes, mtimes, hashes and read states.
7
+ * Apply is the only mutating half, and it revalidates every candidate — roots,
8
+ * ownership, symlink ancestors, file identity, root generation, dynamic live
9
+ * state and selected shared paths — immediately before each unlink.
10
+ *
11
+ * Ordering is deliberate:
12
+ * 1. cleanup acquires the exclusive per-root lock and rechecks foreign leases;
13
+ * 2. preparation (the integration owner's explicit teardown) returns ready and
14
+ * blocked sets; uncertain items are never unlinked;
15
+ * 3. live state is refreshed again, then a report body is replaced by a
16
+ * deletion receipt BEFORE its artifacts are unlinked, so parent-history or
17
+ * transcript re-import cannot resurrect it;
18
+ * 4. only unchanged, proven-owned regular files are unlinked one by one;
19
+ * 5. root session files and external/saved workflow sources are never candidates.
20
+ */
21
+
22
+ import { randomBytes } from "node:crypto";
23
+ import { readdir, rmdir, unlink } from "node:fs/promises";
24
+ import { basename, dirname, join, resolve } from "node:path";
25
+ import { flushIssueLog } from "./error-log.ts";
26
+ import {
27
+ type CleanupLockHandle,
28
+ type CleanupScope,
29
+ inspectRegularFile,
30
+ isCanonicalAgentId,
31
+ isPathWithin,
32
+ isSafePathComponent,
33
+ normalizeReportPath,
34
+ type ReportEntry,
35
+ type ReportRootState,
36
+ type ReportSnapshot,
37
+ type ReportStore,
38
+ readSessionOwnershipData,
39
+ type WorkflowArtifactEntry,
40
+ } from "./report-store.ts";
41
+
42
+ export type CleanupFileKind =
43
+ | "report-entry"
44
+ | "report-output"
45
+ | "workflow-generated"
46
+ | "workflow-registration"
47
+ | "child-session"
48
+ | "legacy-output"
49
+ | "diagnostics-log"
50
+ | "root-metadata";
51
+
52
+ export type CleanupReadState = "read" | "unread" | "unknown";
53
+
54
+ /** What the live integration layer knows at the moment of the call. */
55
+ export interface CleanupLiveState {
56
+ /** Running/queued/starting/settling agent ids — never candidates. */
57
+ activeAgentIds?: Iterable<string>;
58
+ /** Running/paused workflow ids — never candidates. */
59
+ activeWorkflowIds?: Iterable<string>;
60
+ /** Exact transcript/output/shared paths referenced by active work. */
61
+ protectedPaths?: Iterable<string>;
62
+ /** Live results the parent has not consumed yet (`resultConsumed !== true`). */
63
+ unreadAgentIds?: Iterable<string>;
64
+ /** A protected writer still owns the shared diagnostics aggregate. */
65
+ diagnosticsBusy?: boolean;
66
+ /**
67
+ * Own roots with live SDK work (busy/startup/finalizer/uncertain) or a
68
+ * resumable owner dependency. Their whole root is refused: no lock is taken
69
+ * and no artifact of it is touched, so running/queued work keeps writing.
70
+ */
71
+ protectedRootSessionIds?: Iterable<string>;
72
+ }
73
+
74
+ /** Refreshed after teardown and at every final mutation boundary, including retries. */
75
+ export type CleanupLiveStateGetter = () => CleanupLiveState | Promise<CleanupLiveState>;
76
+
77
+ interface NormalizedLiveState {
78
+ activeAgents: ReadonlySet<string>;
79
+ activeWorkflows: ReadonlySet<string>;
80
+ protectedPaths: ReadonlySet<string>;
81
+ unreadAgents: ReadonlySet<string>;
82
+ diagnosticsBusy: boolean;
83
+ protectedRoots: ReadonlySet<string>;
84
+ }
85
+
86
+ export interface CleanupFileInventory {
87
+ path: string;
88
+ kind: CleanupFileKind;
89
+ rootSessionId: string;
90
+ size: number;
91
+ mtimeMs: number;
92
+ fingerprint: string;
93
+ readState: CleanupReadState;
94
+ legacy: boolean;
95
+ shared: boolean;
96
+ agentId?: string;
97
+ workflowId?: string;
98
+ /** Registered child session path, present for `child-session` candidates. */
99
+ sessionFile?: string;
100
+ entryGeneration?: number;
101
+ workflowUpdatedAt?: number;
102
+ }
103
+
104
+ export interface CleanupSkip {
105
+ path?: string;
106
+ kind?: CleanupFileKind;
107
+ rootSessionId?: string;
108
+ agentId?: string;
109
+ workflowId?: string;
110
+ reason: string;
111
+ legacy?: boolean;
112
+ }
113
+
114
+ export interface CleanupPlanCounts {
115
+ files: number;
116
+ bytes: number;
117
+ reports: number;
118
+ legacy: number;
119
+ taskOutputs: number;
120
+ workflowFiles: number;
121
+ childSessions: number;
122
+ diagnostics: number;
123
+ rootMetadata: number;
124
+ unread: number;
125
+ unknownReadState: number;
126
+ }
127
+
128
+ export interface CleanupRootFingerprint {
129
+ rootSessionId: string;
130
+ generation: number;
131
+ rootSessionFile?: string;
132
+ }
133
+
134
+ export interface CleanupPlan {
135
+ planId: string;
136
+ scope: CleanupScope;
137
+ createdAt: number;
138
+ roots: readonly CleanupRootFingerprint[];
139
+ files: readonly CleanupFileInventory[];
140
+ skipped: readonly CleanupSkip[];
141
+ counts: CleanupPlanCounts;
142
+ agentIds: readonly string[];
143
+ sessionFiles: readonly string[];
144
+ /**
145
+ * Set when the global main-session inventory was incomplete at preview. Apply
146
+ * refuses identity-sensitive deletions under the same condition.
147
+ */
148
+ identityUncertainty?: string;
149
+ }
150
+
151
+ export interface CleanupPlanOptions {
152
+ /**
153
+ * Add legacy `.output` candidates. Even then they are only eligible for
154
+ * deletion after `confirmedLegacy` proves older unleased instances are closed.
155
+ */
156
+ includeLegacy?: boolean;
157
+ /** Read-only session preview root; apply continues to use the bound store. */
158
+ previewRootSessionId?: string;
159
+ }
160
+
161
+ export interface CleanupPrepareRequest {
162
+ scope: CleanupScope;
163
+ agentIds: readonly string[];
164
+ sessionFiles: readonly string[];
165
+ rootSessionIds: readonly string[];
166
+ }
167
+
168
+ /**
169
+ * Explicit teardown result from the integration layer. Omitted ready sets mean
170
+ * "not proven ready" for the resource class they cover (fail closed).
171
+ */
172
+ export interface CleanupPreparation {
173
+ readyAgentIds?: readonly string[];
174
+ blockedAgentIds?: Readonly<Record<string, string>>;
175
+ readySessionFiles?: readonly string[];
176
+ blockedSessionFiles?: Readonly<Record<string, string>>;
177
+ readyRootSessionIds?: readonly string[];
178
+ blockedRootSessionIds?: Readonly<Record<string, string>>;
179
+ }
180
+
181
+ export type CleanupPrepare = (
182
+ request: CleanupPrepareRequest,
183
+ ) => Promise<CleanupPreparation> | CleanupPreparation;
184
+
185
+ export interface CleanupApplyOptions {
186
+ confirmed: boolean;
187
+ /** Extra user confirmation that older unleased pi instances are closed. */
188
+ confirmedLegacy?: boolean;
189
+ liveStateGetter: CleanupLiveStateGetter;
190
+ /** Successful teardown/ready-blocked handoff. Uncertain items stay protected. */
191
+ prepare?: CleanupPrepare;
192
+ }
193
+
194
+ export interface CleanupDeletedItem {
195
+ path: string;
196
+ kind: CleanupFileKind;
197
+ bytes: number;
198
+ readState: CleanupReadState;
199
+ rootSessionId?: string;
200
+ agentId?: string;
201
+ workflowId?: string;
202
+ }
203
+
204
+ export interface CleanupFailure {
205
+ path?: string;
206
+ kind?: CleanupFileKind;
207
+ agentId?: string;
208
+ workflowId?: string;
209
+ reason: string;
210
+ }
211
+
212
+ export interface CleanupResult {
213
+ scope: CleanupScope;
214
+ deleted: CleanupDeletedItem[];
215
+ failed: CleanupFailure[];
216
+ skipped: CleanupSkip[];
217
+ deletedAgentIds: string[];
218
+ bytesDeleted: number;
219
+ }
220
+
221
+ /**
222
+ * A rejected apply that may still have mutated the disk. `result` is the exact
223
+ * partial progress of the rejecting apply call (never a re-plan or a guess), so
224
+ * the caller can forget/report the proven deletions before releasing its own
225
+ * barriers. Intentional refusals and normal failures are ordinary results.
226
+ */
227
+ export class CleanupApplyError extends Error {
228
+ readonly result: CleanupResult;
229
+
230
+ constructor(message: string, result: CleanupResult, options: { cause?: unknown } = {}) {
231
+ super(message, options);
232
+ this.name = "CleanupApplyError";
233
+ this.result = result;
234
+ }
235
+ }
236
+
237
+ function errorCode(error: unknown): string | undefined {
238
+ if (typeof error !== "object" || error === null) return undefined;
239
+ const code = (error as { code?: unknown }).code;
240
+ return typeof code === "string" ? code : undefined;
241
+ }
242
+
243
+ function setOf(values: Iterable<string> | undefined): Set<string> {
244
+ return new Set(values ?? []);
245
+ }
246
+
247
+ function pathSetOf(values: Iterable<string> | undefined): Set<string> {
248
+ const set = new Set<string>();
249
+ for (const value of values ?? []) set.add(normalizeReportPath(value));
250
+ return set;
251
+ }
252
+
253
+ function normalizeLive(state: CleanupLiveState): NormalizedLiveState {
254
+ return {
255
+ activeAgents: setOf(state.activeAgentIds),
256
+ activeWorkflows: setOf(state.activeWorkflowIds),
257
+ protectedPaths: pathSetOf(state.protectedPaths),
258
+ unreadAgents: setOf(state.unreadAgentIds),
259
+ diagnosticsBusy: state.diagnosticsBusy === true,
260
+ protectedRoots: setOf(state.protectedRootSessionIds),
261
+ };
262
+ }
263
+
264
+ async function readLive(getter: CleanupLiveStateGetter): Promise<NormalizedLiveState> {
265
+ return normalizeLive(await getter());
266
+ }
267
+
268
+ function emptyCounts(): CleanupPlanCounts {
269
+ return {
270
+ files: 0,
271
+ bytes: 0,
272
+ reports: 0,
273
+ legacy: 0,
274
+ taskOutputs: 0,
275
+ workflowFiles: 0,
276
+ childSessions: 0,
277
+ diagnostics: 0,
278
+ rootMetadata: 0,
279
+ unread: 0,
280
+ unknownReadState: 0,
281
+ };
282
+ }
283
+
284
+ function countFile(counts: CleanupPlanCounts, file: CleanupFileInventory): void {
285
+ counts.files++;
286
+ counts.bytes += file.size;
287
+ if (file.kind === "report-entry") counts.reports++;
288
+ if (file.legacy) counts.legacy++;
289
+ if (file.kind === "report-output" || file.kind === "legacy-output") counts.taskOutputs++;
290
+ if (file.kind === "workflow-generated" || file.kind === "workflow-registration") {
291
+ counts.workflowFiles++;
292
+ }
293
+ if (file.kind === "child-session") counts.childSessions++;
294
+ if (file.kind === "diagnostics-log") counts.diagnostics++;
295
+ if (file.kind === "root-metadata") counts.rootMetadata++;
296
+ if (file.readState === "unread") counts.unread++;
297
+ if (file.readState === "unknown") counts.unknownReadState++;
298
+ }
299
+
300
+ function isActiveAgent(live: NormalizedLiveState, agentId: string | undefined): boolean {
301
+ return agentId !== undefined && live.activeAgents.has(agentId);
302
+ }
303
+
304
+ function isActiveWorkflow(live: NormalizedLiveState, workflowId: string | undefined): boolean {
305
+ return workflowId !== undefined && live.activeWorkflows.has(workflowId);
306
+ }
307
+
308
+ function isProtected(live: NormalizedLiveState, path: string | undefined): boolean {
309
+ return path !== undefined && live.protectedPaths.has(normalizeReportPath(path));
310
+ }
311
+
312
+ /**
313
+ * A whole-root refusal shared by preview, lock acquisition and every unlink
314
+ * gate. Root protection is coarser than per-agent/per-path protection on
315
+ * purpose: locking or writing this root during cleanup would block unrelated
316
+ * live work in it, and deleting part of it could split a live artifact set.
317
+ */
318
+ const PROTECTED_ROOT_REASON = "root-work-active";
319
+
320
+ function isProtectedRoot(
321
+ protectedRoots: ReadonlySet<string>,
322
+ rootSessionId: string,
323
+ ): boolean {
324
+ return rootSessionId.length > 0 && protectedRoots.has(rootSessionId);
325
+ }
326
+
327
+ /**
328
+ * A report is protected while any ancestor owner is active, even after the
329
+ * intermediate parent record itself was evicted. The spawn-time ownerIds chain
330
+ * is what makes that survive; legacy entries fall back to their immediate
331
+ * parent/workflow fields.
332
+ */
333
+ type CleanupOwner = Pick<ReportEntry, "ownerIds" | "parentAgentId" | "workflowId">;
334
+
335
+ function hasActiveOwner(entry: CleanupOwner, live: NormalizedLiveState): boolean {
336
+ if (entry.ownerIds.some((ownerId) => live.activeAgents.has(ownerId))) return true;
337
+ if (entry.parentAgentId !== undefined && live.activeAgents.has(entry.parentAgentId)) {
338
+ return true;
339
+ }
340
+ return entry.workflowId !== undefined && live.activeWorkflows.has(entry.workflowId);
341
+ }
342
+
343
+ function isRootSessionPath(path: string, rootSessionFiles: ReadonlySet<string>): boolean {
344
+ return rootSessionFiles.has(normalizeReportPath(path));
345
+ }
346
+
347
+ /** The `.output` must be the exact registered path under this root's tasks dir. */
348
+ function isRegisteredOutputPath(path: string, entry: ReportEntry): boolean {
349
+ if (basename(path) !== `${entry.id}.output`) return false;
350
+ if (basename(dirname(path)) !== "tasks") return false;
351
+ return basename(dirname(dirname(path))) === entry.rootSessionId;
352
+ }
353
+
354
+ /** Generated inline workflow copies/journals only; never the saved source path. */
355
+ function isRegisteredWorkflowPath(
356
+ path: string,
357
+ entry: Pick<WorkflowArtifactEntry, "id" | "rootSessionId">,
358
+ ): boolean {
359
+ const name = basename(path);
360
+ if (!name.startsWith(`${entry.id}.workflow.`)) return false;
361
+ if (basename(dirname(path)) !== "tasks") return false;
362
+ return basename(dirname(dirname(path))) === entry.rootSessionId;
363
+ }
364
+
365
+ interface ChildSessionCheck {
366
+ ok: boolean;
367
+ reason?: string;
368
+ }
369
+
370
+ /**
371
+ * Modern child-history eligibility: registered exact path, matching session
372
+ * header id, and a pi-subagents ownership custom entry. No marker — including
373
+ * every pre-upgrade transcript — stays skipped, and main/root session files are
374
+ * never candidates.
375
+ */
376
+ async function verifyChildSession(
377
+ store: ReportStore,
378
+ entry: ReportEntry,
379
+ identity: RootIdentityInventory,
380
+ ): Promise<ChildSessionCheck> {
381
+ const path = entry.sessionFile;
382
+ if (!path) return { ok: false, reason: "no-registered-session-file" };
383
+ if (isRootSessionPath(path, identity.rootSessionFiles)) {
384
+ return { ok: false, reason: "root-session-file-is-never-deletable" };
385
+ }
386
+ const storage = store.storage();
387
+ if (!storage.sessionRoots.some((root) => isPathWithin(path, root))) {
388
+ return { ok: false, reason: "session-file-outside-known-session-roots" };
389
+ }
390
+ const inspected = await inspectRegularFile(path, storage.sessionRoots);
391
+ if (!inspected.ok) return { ok: false, reason: inspected.reason };
392
+ const parsed = await store.readSessionFile(path);
393
+ if (!parsed) return { ok: false, reason: "session-file-unreadable-or-unidentified" };
394
+ if (parsed.header.id === entry.rootSessionId) {
395
+ return { ok: false, reason: "root-session-header" };
396
+ }
397
+ // An alternate-path copy of a main conversation carries the same SDK session
398
+ // id: the exact-path check above cannot see it, this can.
399
+ if (identity.rootSessionIds.has(parsed.header.id)) {
400
+ return { ok: false, reason: "known-root-session-header" };
401
+ }
402
+ if (entry.sessionId !== undefined && parsed.header.id !== entry.sessionId) {
403
+ return { ok: false, reason: "session-header-id-mismatch" };
404
+ }
405
+ const markers = parsed.entries
406
+ .map((item) => {
407
+ if (typeof item !== "object" || item === null) return undefined;
408
+ const record = item as { type?: unknown; customType?: unknown; data?: unknown };
409
+ if (record.type !== "custom" || record.customType !== "pi-subagents:ownership") {
410
+ return undefined;
411
+ }
412
+ return readSessionOwnershipData(record.data);
413
+ })
414
+ .filter((marker) => marker !== undefined);
415
+ const marker = markers[0];
416
+ if (!marker) return { ok: false, reason: "missing-pi-subagents-ownership-marker" };
417
+ if (marker.agentId !== entry.id) return { ok: false, reason: "ownership-agent-id-mismatch" };
418
+ if (marker.rootSessionId !== entry.rootSessionId) {
419
+ return { ok: false, reason: "ownership-root-session-mismatch" };
420
+ }
421
+ if (marker.childSessionId !== parsed.header.id) {
422
+ return { ok: false, reason: "ownership-child-session-mismatch" };
423
+ }
424
+ if (normalizeReportPath(marker.rootCwd) !== normalizeReportPath(entry.rootCwd)) {
425
+ return { ok: false, reason: "ownership-root-cwd-mismatch" };
426
+ }
427
+ if (
428
+ entry.rootSessionFile !== undefined &&
429
+ marker.rootSessionFile !== undefined &&
430
+ normalizeReportPath(marker.rootSessionFile) !== normalizeReportPath(entry.rootSessionFile)
431
+ ) {
432
+ return { ok: false, reason: "ownership-root-session-file-mismatch" };
433
+ }
434
+ return { ok: true };
435
+ }
436
+
437
+ function isTerminalWorkflow(entry: WorkflowArtifactEntry): boolean {
438
+ return entry.status === "completed" || entry.status === "failed" || entry.status === "killed";
439
+ }
440
+
441
+ interface PlanAccumulator {
442
+ files: CleanupFileInventory[];
443
+ skipped: CleanupSkip[];
444
+ counts: CleanupPlanCounts;
445
+ seenPaths: Set<string>;
446
+ }
447
+
448
+ function skip(
449
+ accumulator: PlanAccumulator,
450
+ skipReason: string,
451
+ details: Omit<CleanupSkip, "reason"> = {},
452
+ ): void {
453
+ accumulator.skipped.push({ ...details, reason: skipReason });
454
+ }
455
+
456
+ interface InventoryResult {
457
+ added: boolean;
458
+ reason?: string;
459
+ }
460
+
461
+ async function inventory(
462
+ accumulator: PlanAccumulator,
463
+ path: string,
464
+ allowedRoots: readonly string[],
465
+ details: Omit<CleanupFileInventory, "path" | "size" | "mtimeMs" | "fingerprint">,
466
+ options: { alreadyMissingIsSatisfied?: boolean } = {},
467
+ ): Promise<InventoryResult> {
468
+ const key = normalizeReportPath(path);
469
+ if (accumulator.seenPaths.has(key)) return { added: false, reason: "duplicate-candidate" };
470
+ const inspected = await inspectRegularFile(path, allowedRoots);
471
+ if (!inspected.ok) {
472
+ const satisfied =
473
+ options.alreadyMissingIsSatisfied === true && inspected.reason === "already-missing";
474
+ if (!satisfied) {
475
+ skip(accumulator, inspected.reason, {
476
+ path,
477
+ kind: details.kind,
478
+ ...(details.rootSessionId === undefined ? {} : { rootSessionId: details.rootSessionId }),
479
+ ...(details.agentId === undefined ? {} : { agentId: details.agentId }),
480
+ ...(details.workflowId === undefined ? {} : { workflowId: details.workflowId }),
481
+ ...(details.legacy ? { legacy: true } : {}),
482
+ });
483
+ }
484
+ return { added: false, reason: inspected.reason };
485
+ }
486
+ accumulator.seenPaths.add(key);
487
+ const file: CleanupFileInventory = {
488
+ ...details,
489
+ path: inspected.identity.path,
490
+ size: inspected.identity.size,
491
+ mtimeMs: inspected.identity.mtimeMs,
492
+ fingerprint: inspected.identity.fingerprint,
493
+ };
494
+ accumulator.files.push(file);
495
+ countFile(accumulator.counts, file);
496
+ return { added: true };
497
+ }
498
+
499
+ interface RootIdentityInventory {
500
+ rootSessionFiles: Set<string>;
501
+ /**
502
+ * Every strictly known root session id. An SDK session header carrying one of
503
+ * these is a main conversation, whichever path the transcript now lives at.
504
+ */
505
+ rootSessionIds: Set<string>;
506
+ /** Present when any global identity source could not be fully read. */
507
+ uncertainty?: string;
508
+ }
509
+
510
+ function planningRootFiles(states: readonly ReportRootState[]): RootIdentityInventory {
511
+ const rootSessionFiles = new Set<string>();
512
+ const rootSessionIds = new Set<string>();
513
+ let uncertainty: string | undefined;
514
+ for (const state of states) {
515
+ rootSessionIds.add(state.rootSessionId);
516
+ if (state.leasesUncertain !== undefined) {
517
+ uncertainty ??= `lease-uncertainty:${state.leasesUncertain}`;
518
+ }
519
+ if (state.rootSessionFile) rootSessionFiles.add(normalizeReportPath(state.rootSessionFile));
520
+ for (const entry of state.reportEntries) {
521
+ if (entry.rootSessionFile) rootSessionFiles.add(normalizeReportPath(entry.rootSessionFile));
522
+ }
523
+ for (const workflow of state.workflows) {
524
+ if (workflow.rootSessionFile) rootSessionFiles.add(normalizeReportPath(workflow.rootSessionFile));
525
+ }
526
+ // A lease is published at bind even before root metadata exists; its plain
527
+ // identity protects a main session that later becomes another root.
528
+ for (const lease of state.leases) {
529
+ if (lease.rootSessionFile) rootSessionFiles.add(normalizeReportPath(lease.rootSessionFile));
530
+ }
531
+ }
532
+ return uncertainty === undefined
533
+ ? { rootSessionFiles, rootSessionIds }
534
+ : { rootSessionFiles, rootSessionIds, uncertainty };
535
+ }
536
+
537
+ /**
538
+ * Global main-session identities for cleanup protection. A partial inventory is
539
+ * reported as uncertainty: a child history in one root may be the main session
540
+ * of another root that could not be read, so "empty" is never proof of safety.
541
+ */
542
+ async function collectGlobalIdentities(store: ReportStore): Promise<RootIdentityInventory> {
543
+ const scan = await store.scanRootIdentities();
544
+ const inventory = planningRootFiles(scan.states);
545
+ if (scan.uncertainty !== undefined) {
546
+ inventory.uncertainty ??= `inventory-uncertain:${scan.uncertainty}`;
547
+ }
548
+ return inventory;
549
+ }
550
+
551
+ /**
552
+ * Read-only inventory. No file is changed, no directory is created and no lock
553
+ * is acquired; the caller may render counts and cancel without side effects.
554
+ */
555
+ export async function planCleanup(
556
+ store: ReportStore,
557
+ scope: CleanupScope,
558
+ liveStateGetter: CleanupLiveStateGetter,
559
+ options: CleanupPlanOptions = {},
560
+ ): Promise<CleanupPlan> {
561
+ const live = await readLive(liveStateGetter);
562
+ const states = await store.list(scope, options.previewRootSessionId);
563
+ const storage = store.storage();
564
+ // Protection identities are global even for a session-scoped deletion: a
565
+ // child history in this root may already be another root's main session
566
+ // (including a lease-only binding that has no root metadata yet). An
567
+ // incomplete global inventory is uncertainty, never "no other roots".
568
+ const identity = await collectGlobalIdentities(store);
569
+ const rootSessionFiles = identity.rootSessionFiles;
570
+ const legacyInspections = options.includeLegacy ? await store.inspectLegacyOutputs() : [];
571
+ for (const legacy of legacyInspections) {
572
+ const rootSessionFile = legacy.snapshot?.rootSessionFile;
573
+ if (rootSessionFile) rootSessionFiles.add(normalizeReportPath(rootSessionFile));
574
+ }
575
+ const accumulator: PlanAccumulator = {
576
+ files: [],
577
+ skipped: [],
578
+ counts: emptyCounts(),
579
+ seenPaths: new Set<string>(),
580
+ };
581
+ const plannedReportIds = new Set<string>();
582
+ const archivedArtifactPaths = new Set<string>();
583
+ for (const state of states) {
584
+ for (const entry of state.reportEntries) {
585
+ if (entry.outputFile !== undefined) {
586
+ archivedArtifactPaths.add(normalizeReportPath(entry.outputFile));
587
+ }
588
+ if (entry.sessionFile !== undefined) {
589
+ archivedArtifactPaths.add(normalizeReportPath(entry.sessionFile));
590
+ }
591
+ }
592
+ }
593
+ const roots: CleanupRootFingerprint[] = [];
594
+
595
+ for (const state of states) {
596
+ roots.push({
597
+ rootSessionId: state.rootSessionId,
598
+ generation: state.generation,
599
+ ...(state.rootSessionFile === undefined
600
+ ? {}
601
+ : { rootSessionFile: state.rootSessionFile }),
602
+ });
603
+ if (state.cleanupLockState === "live") {
604
+ skip(accumulator, "cleanup-lock-held", { rootSessionId: state.rootSessionId });
605
+ continue;
606
+ }
607
+ if (isProtectedRoot(live.protectedRoots, state.rootSessionId)) {
608
+ skip(accumulator, PROTECTED_ROOT_REASON, { rootSessionId: state.rootSessionId });
609
+ continue;
610
+ }
611
+ if (state.cleanupLockState === "uncertain") {
612
+ skip(accumulator, "cleanup-lock-unreadable", { rootSessionId: state.rootSessionId });
613
+ continue;
614
+ }
615
+ const protection = await store.rootProtectionReason(state.rootSessionId);
616
+ if (protection) {
617
+ skip(accumulator, protection, { rootSessionId: state.rootSessionId });
618
+ continue;
619
+ }
620
+
621
+ for (const entry of state.reportEntries) {
622
+ const readState: CleanupReadState = live.unreadAgents.has(entry.id)
623
+ ? "unread"
624
+ : "unknown";
625
+ if (isActiveAgent(live, entry.id) || hasActiveOwner(entry, live)) {
626
+ skip(accumulator, isActiveAgent(live, entry.id) ? "active-agent" : "active-owner", {
627
+ rootSessionId: state.rootSessionId,
628
+ agentId: entry.id,
629
+ kind: "report-entry",
630
+ });
631
+ continue;
632
+ }
633
+ if (entry.state !== "deleted") {
634
+ const entryPath = join(state.rootDir, "agents", `${entry.id}.json`);
635
+ const reportInventory = await inventory(accumulator, entryPath, [storage.reportsRoot], {
636
+ kind: "report-entry",
637
+ rootSessionId: state.rootSessionId,
638
+ agentId: entry.id,
639
+ readState,
640
+ legacy: false,
641
+ shared: false,
642
+ entryGeneration: entry.entryGeneration,
643
+ ...(entry.workflowId === undefined ? {} : { workflowId: entry.workflowId }),
644
+ });
645
+ if (reportInventory.added) plannedReportIds.add(entry.id);
646
+ if (!reportInventory.added) continue;
647
+ }
648
+ // A deletion receipt keeps the minimal artifact ownership so a failed
649
+ // artifact unlink can be retried by a later cleanup; the body is already gone.
650
+ if (entry.outputFile !== undefined) {
651
+ if (isProtected(live, entry.outputFile)) {
652
+ skip(accumulator, "protected-output-path", {
653
+ path: entry.outputFile,
654
+ rootSessionId: state.rootSessionId,
655
+ agentId: entry.id,
656
+ kind: "report-output",
657
+ });
658
+ } else if (!isRegisteredOutputPath(entry.outputFile, entry)) {
659
+ skip(accumulator, "output-path-not-registered-to-this-root", {
660
+ path: entry.outputFile,
661
+ rootSessionId: state.rootSessionId,
662
+ agentId: entry.id,
663
+ kind: "report-output",
664
+ });
665
+ } else {
666
+ await inventory(accumulator, entry.outputFile, [storage.tempRoot], {
667
+ kind: "report-output",
668
+ rootSessionId: state.rootSessionId,
669
+ agentId: entry.id,
670
+ readState,
671
+ legacy: false,
672
+ shared: false,
673
+ });
674
+ }
675
+ }
676
+
677
+ if (entry.sessionFile !== undefined) {
678
+ if (isProtected(live, entry.sessionFile)) {
679
+ skip(accumulator, "protected-session-file", {
680
+ path: entry.sessionFile,
681
+ rootSessionId: state.rootSessionId,
682
+ agentId: entry.id,
683
+ kind: "child-session",
684
+ });
685
+ } else if (identity.uncertainty !== undefined) {
686
+ skip(accumulator, `root-identity-uncertain:${identity.uncertainty}`, {
687
+ path: entry.sessionFile,
688
+ rootSessionId: state.rootSessionId,
689
+ agentId: entry.id,
690
+ kind: "child-session",
691
+ });
692
+ } else {
693
+ const check = await verifyChildSession(store, entry, identity);
694
+ if (!check.ok) {
695
+ skip(accumulator, check.reason ?? "child-session-unverified", {
696
+ path: entry.sessionFile,
697
+ rootSessionId: state.rootSessionId,
698
+ agentId: entry.id,
699
+ kind: "child-session",
700
+ });
701
+ } else {
702
+ await inventory(accumulator, entry.sessionFile, storage.sessionRoots, {
703
+ kind: "child-session",
704
+ rootSessionId: state.rootSessionId,
705
+ agentId: entry.id,
706
+ readState,
707
+ legacy: false,
708
+ shared: false,
709
+ sessionFile: entry.sessionFile,
710
+ });
711
+ }
712
+ }
713
+ }
714
+ }
715
+
716
+ for (const workflow of state.workflows) {
717
+ if (!isTerminalWorkflow(workflow)) {
718
+ skip(accumulator, "workflow-not-settled", {
719
+ rootSessionId: state.rootSessionId,
720
+ workflowId: workflow.id,
721
+ kind: "workflow-generated",
722
+ });
723
+ continue;
724
+ }
725
+ if (isActiveWorkflow(live, workflow.id)) {
726
+ skip(accumulator, "active-workflow", {
727
+ rootSessionId: state.rootSessionId,
728
+ workflowId: workflow.id,
729
+ kind: "workflow-generated",
730
+ });
731
+ continue;
732
+ }
733
+ const external = new Set((workflow.externalPaths ?? []).map((path) => normalizeReportPath(path)));
734
+ let workflowBlocked = false;
735
+ for (const generated of workflow.generatedPaths) {
736
+ if (external.has(normalizeReportPath(generated))) {
737
+ skip(accumulator, "external-workflow-source-never-deleted", {
738
+ path: generated,
739
+ rootSessionId: state.rootSessionId,
740
+ workflowId: workflow.id,
741
+ kind: "workflow-generated",
742
+ });
743
+ workflowBlocked = true;
744
+ continue;
745
+ }
746
+ if (isProtected(live, generated)) {
747
+ skip(accumulator, "protected-workflow-artifact", {
748
+ path: generated,
749
+ rootSessionId: state.rootSessionId,
750
+ workflowId: workflow.id,
751
+ kind: "workflow-generated",
752
+ });
753
+ workflowBlocked = true;
754
+ continue;
755
+ }
756
+ if (!isRegisteredWorkflowPath(generated, workflow)) {
757
+ skip(accumulator, "workflow-path-not-registered-to-this-run", {
758
+ path: generated,
759
+ rootSessionId: state.rootSessionId,
760
+ workflowId: workflow.id,
761
+ kind: "workflow-generated",
762
+ });
763
+ workflowBlocked = true;
764
+ continue;
765
+ }
766
+ const generatedInventory = await inventory(
767
+ accumulator,
768
+ generated,
769
+ [storage.tempRoot],
770
+ {
771
+ kind: "workflow-generated",
772
+ rootSessionId: state.rootSessionId,
773
+ workflowId: workflow.id,
774
+ readState: "unknown",
775
+ legacy: false,
776
+ shared: false,
777
+ },
778
+ { alreadyMissingIsSatisfied: true },
779
+ );
780
+ // A proven already-missing generated path is satisfied; only an unsafe
781
+ // or unreadable path keeps ownership registered.
782
+ if (!generatedInventory.added && generatedInventory.reason !== "already-missing") {
783
+ workflowBlocked = true;
784
+ }
785
+ }
786
+ if (workflowBlocked) {
787
+ skip(accumulator, "workflow-registration-kept-for-remaining-artifacts", {
788
+ rootSessionId: state.rootSessionId,
789
+ workflowId: workflow.id,
790
+ kind: "workflow-registration",
791
+ });
792
+ continue;
793
+ }
794
+ const registrationPath = join(state.rootDir, "workflows", `${workflow.id}.json`);
795
+ await inventory(accumulator, registrationPath, [storage.reportsRoot], {
796
+ kind: "workflow-registration",
797
+ rootSessionId: state.rootSessionId,
798
+ workflowId: workflow.id,
799
+ readState: "unknown",
800
+ legacy: false,
801
+ shared: false,
802
+ workflowUpdatedAt: workflow.updatedAt,
803
+ });
804
+ }
805
+
806
+ if (
807
+ state.metadataPresent &&
808
+ // A root that records its main session is an identity keeper, never a
809
+ // removable empty-root candidate (its absence would unprotect that history).
810
+ state.rootSessionFile === undefined &&
811
+ state.reportEntries.length === 0 &&
812
+ state.workflows.length === 0 &&
813
+ state.leasesUncertain === undefined &&
814
+ state.leases.every((lease) => lease.own)
815
+ ) {
816
+ await inventory(accumulator, join(state.rootDir, "root.json"), [storage.reportsRoot], {
817
+ kind: "root-metadata",
818
+ rootSessionId: state.rootSessionId,
819
+ readState: "unknown",
820
+ legacy: false,
821
+ shared: false,
822
+ });
823
+ }
824
+ }
825
+
826
+ if (scope === "global") {
827
+ if (live.diagnosticsBusy) {
828
+ skip(accumulator, "shared-diagnostics-writer-active", { kind: "diagnostics-log" });
829
+ } else {
830
+ const logPath = join(storage.agentDir, "pi-subagents", "agent-errors.jsonl");
831
+ const inspected = await inspectRegularFile(logPath, [join(storage.agentDir, "pi-subagents")]);
832
+ if (inspected.ok) {
833
+ const file: CleanupFileInventory = {
834
+ path: inspected.identity.path,
835
+ kind: "diagnostics-log",
836
+ rootSessionId: "",
837
+ size: inspected.identity.size,
838
+ mtimeMs: inspected.identity.mtimeMs,
839
+ fingerprint: inspected.identity.fingerprint,
840
+ readState: "unknown",
841
+ legacy: false,
842
+ shared: true,
843
+ };
844
+ accumulator.files.push(file);
845
+ countFile(accumulator.counts, file);
846
+ }
847
+ }
848
+ }
849
+
850
+ if (options.includeLegacy) {
851
+ const boundRoot = scope === "session"
852
+ ? options.previewRootSessionId ?? store.bindingContext?.rootSessionId
853
+ : undefined;
854
+ const protectionCache = new Map<string, string | undefined>();
855
+ for (const legacy of legacyInspections) {
856
+ if (legacy.snapshot === undefined) {
857
+ skip(accumulator, legacy.reason ?? "legacy-output-unverified", {
858
+ path: legacy.path,
859
+ agentId: legacy.agentId,
860
+ kind: "legacy-output",
861
+ legacy: true,
862
+ });
863
+ continue;
864
+ }
865
+ if (scope === "session" && legacy.snapshot.rootSessionId !== boundRoot) {
866
+ skip(accumulator, "legacy-outside-session-scope", {
867
+ path: legacy.path,
868
+ rootSessionId: legacy.snapshot.rootSessionId,
869
+ agentId: legacy.agentId,
870
+ kind: "legacy-output",
871
+ legacy: true,
872
+ });
873
+ continue;
874
+ }
875
+ if (archivedArtifactPaths.has(normalizeReportPath(legacy.path))) continue;
876
+ if (plannedReportIds.has(legacy.agentId)) continue;
877
+ if (isProtectedRoot(live.protectedRoots, legacy.snapshot.rootSessionId)) {
878
+ skip(accumulator, PROTECTED_ROOT_REASON, {
879
+ path: legacy.path,
880
+ rootSessionId: legacy.snapshot.rootSessionId,
881
+ agentId: legacy.agentId,
882
+ kind: "legacy-output",
883
+ legacy: true,
884
+ });
885
+ continue;
886
+ }
887
+ if (isActiveAgent(live, legacy.agentId)) {
888
+ skip(accumulator, "active-agent", {
889
+ path: legacy.path,
890
+ agentId: legacy.agentId,
891
+ kind: "legacy-output",
892
+ legacy: true,
893
+ });
894
+ continue;
895
+ }
896
+ if (isProtected(live, legacy.path)) {
897
+ skip(accumulator, "protected-output-path", {
898
+ path: legacy.path,
899
+ agentId: legacy.agentId,
900
+ kind: "legacy-output",
901
+ legacy: true,
902
+ });
903
+ continue;
904
+ }
905
+ const rootSessionId = legacy.snapshot.rootSessionId;
906
+ let protection = protectionCache.get(rootSessionId);
907
+ if (!protectionCache.has(rootSessionId)) {
908
+ protection = await store.rootProtectionReason(rootSessionId);
909
+ protectionCache.set(rootSessionId, protection);
910
+ }
911
+ // A legacy root without a managed folder reports "no-root"; that is not a
912
+ // lease and apply still creates a control namespace under legacy confirmation.
913
+ if (protection !== undefined && protection !== "no-root") {
914
+ skip(accumulator, protection, {
915
+ path: legacy.path,
916
+ rootSessionId,
917
+ agentId: legacy.agentId,
918
+ kind: "legacy-output",
919
+ legacy: true,
920
+ });
921
+ continue;
922
+ }
923
+ await inventory(accumulator, legacy.path, [storage.tempRoot], {
924
+ kind: "legacy-output",
925
+ rootSessionId,
926
+ agentId: legacy.agentId,
927
+ readState: "unknown",
928
+ legacy: true,
929
+ shared: false,
930
+ });
931
+ }
932
+ }
933
+
934
+ const agentIds = [
935
+ ...new Set(
936
+ accumulator.files
937
+ .map((file) => file.agentId)
938
+ .filter((id): id is string => id !== undefined),
939
+ ),
940
+ ].sort();
941
+ const sessionFiles = [
942
+ ...new Set(
943
+ accumulator.files
944
+ .filter((file) => file.kind === "child-session" && file.sessionFile !== undefined)
945
+ .map((file) => file.sessionFile as string),
946
+ ),
947
+ ].sort();
948
+
949
+ return {
950
+ planId: randomBytes(8).toString("hex"),
951
+ scope,
952
+ createdAt: Date.now(),
953
+ roots,
954
+ files: accumulator.files,
955
+ skipped: accumulator.skipped,
956
+ counts: accumulator.counts,
957
+ agentIds,
958
+ sessionFiles,
959
+ ...(identity.uncertainty === undefined
960
+ ? {}
961
+ : { identityUncertainty: identity.uncertainty }),
962
+ };
963
+ }
964
+
965
+ interface PreparationView {
966
+ blockedAgents: Map<string, string>;
967
+ readyAgents?: Set<string>;
968
+ blockedSessions: Map<string, string>;
969
+ readySessions?: Set<string>;
970
+ blockedRoots: Map<string, string>;
971
+ readyRoots?: Set<string>;
972
+ }
973
+
974
+ function preparationView(preparation: CleanupPreparation | undefined): PreparationView {
975
+ if (!preparation) {
976
+ return {
977
+ blockedAgents: new Map(),
978
+ blockedSessions: new Map(),
979
+ blockedRoots: new Map(),
980
+ };
981
+ }
982
+ const sessionMap = new Map<string, string>();
983
+ for (const [path, reason] of Object.entries(preparation.blockedSessionFiles ?? {})) {
984
+ sessionMap.set(normalizeReportPath(path), reason);
985
+ }
986
+ return {
987
+ blockedAgents: new Map(Object.entries(preparation.blockedAgentIds ?? {})),
988
+ ...(preparation.readyAgentIds === undefined
989
+ ? {}
990
+ : { readyAgents: new Set(preparation.readyAgentIds) }),
991
+ blockedSessions: sessionMap,
992
+ ...(preparation.readySessionFiles === undefined
993
+ ? {}
994
+ : { readySessions: new Set(preparation.readySessionFiles.map((path) => normalizeReportPath(path))) }),
995
+ blockedRoots: new Map(Object.entries(preparation.blockedRootSessionIds ?? {})),
996
+ ...(preparation.readyRootSessionIds === undefined
997
+ ? {}
998
+ : { readyRoots: new Set(preparation.readyRootSessionIds) }),
999
+ };
1000
+ }
1001
+
1002
+ function failureReason(
1003
+ view: PreparationView,
1004
+ rootSessionId: string,
1005
+ agentId: string | undefined,
1006
+ sessionFile: string | undefined,
1007
+ ): string | undefined {
1008
+ if (view.blockedRoots.has(rootSessionId)) {
1009
+ return `preparation-blocked-root:${view.blockedRoots.get(rootSessionId)}`;
1010
+ }
1011
+ if (agentId !== undefined) {
1012
+ if (view.blockedAgents.has(agentId)) {
1013
+ return `preparation-blocked-agent:${view.blockedAgents.get(agentId)}`;
1014
+ }
1015
+ if (view.readyAgents !== undefined && !view.readyAgents.has(agentId)) {
1016
+ return "preparation-agent-not-ready";
1017
+ }
1018
+ }
1019
+ if (sessionFile !== undefined) {
1020
+ const key = normalizeReportPath(sessionFile);
1021
+ if (view.blockedSessions.has(key)) {
1022
+ return `preparation-blocked-session:${view.blockedSessions.get(key)}`;
1023
+ }
1024
+ if (view.readySessions === undefined || !view.readySessions.has(key)) {
1025
+ return "preparation-session-not-ready";
1026
+ }
1027
+ }
1028
+ return undefined;
1029
+ }
1030
+
1031
+ interface ApplyAccumulator {
1032
+ deleted: CleanupDeletedItem[];
1033
+ failed: CleanupFailure[];
1034
+ skipped: CleanupSkip[];
1035
+ deletedAgentIds: Set<string>;
1036
+ bytesDeleted: number;
1037
+ }
1038
+
1039
+ function skipFile(accumulator: ApplyAccumulator, file: CleanupFileInventory, reason: string): void {
1040
+ accumulator.skipped.push({
1041
+ path: file.path,
1042
+ kind: file.kind,
1043
+ rootSessionId: file.rootSessionId,
1044
+ ...(file.agentId === undefined ? {} : { agentId: file.agentId }),
1045
+ ...(file.workflowId === undefined ? {} : { workflowId: file.workflowId }),
1046
+ ...(file.legacy ? { legacy: true } : {}),
1047
+ reason,
1048
+ });
1049
+ }
1050
+
1051
+ function failFile(accumulator: ApplyAccumulator, file: CleanupFileInventory, reason: string): void {
1052
+ accumulator.failed.push({
1053
+ path: file.path,
1054
+ kind: file.kind,
1055
+ ...(file.agentId === undefined ? {} : { agentId: file.agentId }),
1056
+ ...(file.workflowId === undefined ? {} : { workflowId: file.workflowId }),
1057
+ reason,
1058
+ });
1059
+ }
1060
+
1061
+ function markDeleted(accumulator: ApplyAccumulator, file: CleanupFileInventory, bytes: number): void {
1062
+ accumulator.deleted.push({
1063
+ path: file.path,
1064
+ kind: file.kind,
1065
+ bytes,
1066
+ readState: file.readState,
1067
+ ...(file.rootSessionId.length === 0 ? {} : { rootSessionId: file.rootSessionId }),
1068
+ ...(file.agentId === undefined ? {} : { agentId: file.agentId }),
1069
+ ...(file.workflowId === undefined ? {} : { workflowId: file.workflowId }),
1070
+ });
1071
+ accumulator.bytesDeleted += bytes;
1072
+ if (file.kind === "report-entry" && file.agentId !== undefined) {
1073
+ accumulator.deletedAgentIds.add(file.agentId);
1074
+ }
1075
+ }
1076
+
1077
+ function cleanupResult(plan: CleanupPlan, accumulator: ApplyAccumulator): CleanupResult {
1078
+ return {
1079
+ scope: plan.scope,
1080
+ deleted: [...accumulator.deleted],
1081
+ failed: [...accumulator.failed],
1082
+ skipped: [...accumulator.skipped],
1083
+ deletedAgentIds: [...accumulator.deletedAgentIds].sort(),
1084
+ bytesDeleted: accumulator.bytesDeleted,
1085
+ };
1086
+ }
1087
+
1088
+ function cleanupApplyFailure(
1089
+ plan: CleanupPlan,
1090
+ accumulator: ApplyAccumulator,
1091
+ error: unknown,
1092
+ ): CleanupApplyError {
1093
+ const result = cleanupResult(plan, accumulator);
1094
+ if (error instanceof CleanupApplyError) {
1095
+ // Re-snapshot after lock release so release failures stay visible.
1096
+ return new CleanupApplyError(error.message, result, { cause: error.cause });
1097
+ }
1098
+ const message =
1099
+ error instanceof Error && error.message.length > 0
1100
+ ? error.message
1101
+ : `cleanup-apply-failed:${String(error)}`;
1102
+ return new CleanupApplyError(message, result, { cause: error });
1103
+ }
1104
+
1105
+ function errorDetail(error: unknown): string {
1106
+ const code = errorCode(error);
1107
+ if (code !== undefined) return code;
1108
+ return error instanceof Error && error.message.length > 0 ? error.message : "unknown";
1109
+ }
1110
+
1111
+ /**
1112
+ * Bytes freed by replacing a report body with its deletion receipt. An
1113
+ * unreadable receipt contributes zero instead of a guessed size.
1114
+ */
1115
+ async function freedReportBytes(
1116
+ store: ReportStore,
1117
+ candidate: CleanupFileInventory,
1118
+ ): Promise<number> {
1119
+ const receiptFile = await inspectRegularFile(candidate.path, [store.storage().reportsRoot]);
1120
+ return receiptFile.ok ? Math.max(0, candidate.size - receiptFile.identity.size) : 0;
1121
+ }
1122
+
1123
+ /**
1124
+ * `writeDeletionReceipt` publishes the receipt before it bumps the root
1125
+ * generation, so a rejected call is not proof that the body survived. Under the
1126
+ * held cleanup lock, a durable deleted entry is an actual deletion; anything
1127
+ * unproven is recorded as a failure and handed back without a deleted id.
1128
+ */
1129
+ async function receiptFailure(
1130
+ store: ReportStore,
1131
+ plan: CleanupPlan,
1132
+ accumulator: ApplyAccumulator,
1133
+ heldRoots: ReadonlySet<string>,
1134
+ candidate: CleanupFileInventory,
1135
+ agentId: string,
1136
+ error: unknown,
1137
+ ): Promise<CleanupApplyError> {
1138
+ const detail = errorDetail(error);
1139
+ if (heldRoots.has(candidate.rootSessionId)) {
1140
+ let durable: ReportEntry | undefined;
1141
+ try {
1142
+ durable = await store.readEntry(candidate.rootSessionId, agentId);
1143
+ } catch (inspectError) {
1144
+ failFile(accumulator, candidate, `receipt-state-uncertain:${errorDetail(inspectError)}`);
1145
+ return new CleanupApplyError(
1146
+ `cleanup-receipt-state-uncertain:${detail}`,
1147
+ cleanupResult(plan, accumulator),
1148
+ { cause: inspectError },
1149
+ );
1150
+ }
1151
+ if (durable?.state === "deleted") {
1152
+ markDeleted(accumulator, candidate, await freedReportBytes(store, candidate));
1153
+ return new CleanupApplyError(
1154
+ `cleanup-receipt-committed-generation-failed:${detail}`,
1155
+ cleanupResult(plan, accumulator),
1156
+ { cause: error },
1157
+ );
1158
+ }
1159
+ }
1160
+ failFile(accumulator, candidate, `receipt-failed:${detail}`);
1161
+ return new CleanupApplyError(
1162
+ `cleanup-receipt-failed:${detail}`,
1163
+ cleanupResult(plan, accumulator),
1164
+ { cause: error },
1165
+ );
1166
+ }
1167
+
1168
+ /**
1169
+ * `removeWorkflowRegistration` unlinks the canonical registration before it
1170
+ * bumps the root generation. The file was validated as present immediately
1171
+ * before the mutator, so a verified now-missing canonical registration is an
1172
+ * actual deletion even though the call rejected.
1173
+ */
1174
+ async function workflowRegistrationFailure(
1175
+ store: ReportStore,
1176
+ plan: CleanupPlan,
1177
+ accumulator: ApplyAccumulator,
1178
+ heldRoots: ReadonlySet<string>,
1179
+ candidate: CleanupFileInventory,
1180
+ error: unknown,
1181
+ ): Promise<CleanupApplyError> {
1182
+ const detail = errorDetail(error);
1183
+ const workflowId = candidate.workflowId;
1184
+ const canonical =
1185
+ workflowId !== undefined &&
1186
+ normalizeReportPath(candidate.path) ===
1187
+ normalizeReportPath(
1188
+ join(store.storage().reportsRoot, candidate.rootSessionId, "workflows", `${workflowId}.json`),
1189
+ );
1190
+ if (heldRoots.has(candidate.rootSessionId) && canonical) {
1191
+ const after = await inspectRegularFile(candidate.path, [store.storage().reportsRoot]);
1192
+ if (!after.ok && after.reason === "already-missing") {
1193
+ markDeleted(accumulator, candidate, candidate.size);
1194
+ await pruneManagedParents(candidate, store);
1195
+ return new CleanupApplyError(
1196
+ `cleanup-workflow-registration-removed-generation-failed:${detail}`,
1197
+ cleanupResult(plan, accumulator),
1198
+ { cause: error },
1199
+ );
1200
+ }
1201
+ }
1202
+ failFile(accumulator, candidate, `registration-remove-failed:${detail}`);
1203
+ return new CleanupApplyError(
1204
+ `cleanup-workflow-registration-remove-failed:${detail}`,
1205
+ cleanupResult(plan, accumulator),
1206
+ { cause: error },
1207
+ );
1208
+ }
1209
+
1210
+ function allowedRootsFor(kind: CleanupFileKind, store: ReportStore): readonly string[] {
1211
+ const storage = store.storage();
1212
+ switch (kind) {
1213
+ case "report-entry":
1214
+ case "workflow-registration":
1215
+ case "root-metadata":
1216
+ return [storage.reportsRoot];
1217
+ case "report-output":
1218
+ case "workflow-generated":
1219
+ case "legacy-output":
1220
+ return [storage.tempRoot];
1221
+ case "child-session":
1222
+ return storage.sessionRoots;
1223
+ case "diagnostics-log":
1224
+ return [join(storage.agentDir, "pi-subagents")];
1225
+ default:
1226
+ return [];
1227
+ }
1228
+ }
1229
+
1230
+ interface ValidationContext {
1231
+ store: ReportStore;
1232
+ liveStateGetter: CleanupLiveStateGetter;
1233
+ expectedGenerations: ReadonlyMap<string, number>;
1234
+ rootSessionFiles: ReadonlySet<string>;
1235
+ protectedRoots: Set<string>;
1236
+ }
1237
+
1238
+ async function validateFile(
1239
+ context: ValidationContext,
1240
+ file: CleanupFileInventory,
1241
+ ): Promise<string | undefined> {
1242
+ // Last-moment root guard: a root protected after preview/preparation must not
1243
+ // lose any candidate, including ones validated just before an unlink.
1244
+ if (isProtectedRoot(context.protectedRoots, file.rootSessionId)) {
1245
+ return PROTECTED_ROOT_REASON;
1246
+ }
1247
+ if (isRootSessionPath(file.path, context.rootSessionFiles)) return "root-session-file";
1248
+ const expected = context.expectedGenerations.get(file.rootSessionId);
1249
+ if (expected !== undefined) {
1250
+ const current = (await context.store.getRootGeneration(file.rootSessionId)) ?? 0;
1251
+ if (current !== expected) return "root-generation-changed";
1252
+ }
1253
+ const inspected = await inspectRegularFile(file.path, allowedRootsFor(file.kind, context.store));
1254
+ if (!inspected.ok) return inspected.reason;
1255
+ if (
1256
+ inspected.identity.size !== file.size ||
1257
+ inspected.identity.mtimeMs !== file.mtimeMs ||
1258
+ inspected.identity.fingerprint !== file.fingerprint
1259
+ ) {
1260
+ return "file-changed-since-preview";
1261
+ }
1262
+ return undefined;
1263
+ }
1264
+
1265
+ class CleanupRefusal extends Error {
1266
+ constructor(readonly reason: string) {
1267
+ super(reason);
1268
+ }
1269
+ }
1270
+
1271
+ async function freshProtectionReason(
1272
+ context: ValidationContext,
1273
+ file: CleanupFileInventory,
1274
+ owner?: CleanupOwner,
1275
+ ): Promise<string | undefined> {
1276
+ let live: NormalizedLiveState;
1277
+ try {
1278
+ live = await readLive(context.liveStateGetter);
1279
+ } catch {
1280
+ return "live-state-unavailable";
1281
+ }
1282
+ for (const root of live.protectedRoots) context.protectedRoots.add(root);
1283
+ if (isProtectedRoot(context.protectedRoots, file.rootSessionId)) return PROTECTED_ROOT_REASON;
1284
+ if (isActiveAgent(live, file.agentId)) return "active-agent";
1285
+ if (isActiveWorkflow(live, file.workflowId)) return "active-workflow";
1286
+ if (isProtected(live, file.path)) return "protected-path";
1287
+ if (owner !== undefined && hasActiveOwner(owner, live)) return "active-owner";
1288
+ if (file.kind === "diagnostics-log" && live.diagnosticsBusy) return "shared-diagnostics-writer-active";
1289
+ return undefined;
1290
+ }
1291
+
1292
+ /** Revalidate after queued store reads, then refresh live authorization last. */
1293
+ async function assertRemovable(
1294
+ context: ValidationContext,
1295
+ file: CleanupFileInventory,
1296
+ owner?: CleanupOwner,
1297
+ ): Promise<void> {
1298
+ const changed = await validateFile(context, file);
1299
+ const reason = changed ?? await freshProtectionReason(context, file, owner);
1300
+ if (reason !== undefined) throw new CleanupRefusal(reason);
1301
+ }
1302
+
1303
+ type UnlinkOutcome = "deleted" | "missing" | "failed" | "skipped";
1304
+
1305
+ async function unlinkFile(
1306
+ accumulator: ApplyAccumulator,
1307
+ file: CleanupFileInventory,
1308
+ context: ValidationContext,
1309
+ owner?: CleanupOwner,
1310
+ ): Promise<UnlinkOutcome> {
1311
+ try {
1312
+ await assertRemovable(context, file, owner);
1313
+ } catch (error) {
1314
+ if (!(error instanceof CleanupRefusal)) throw error;
1315
+ skipFile(accumulator, file, error.reason);
1316
+ return error.reason === "already-missing" ? "missing" : "skipped";
1317
+ }
1318
+ try {
1319
+ await unlink(file.path);
1320
+ } catch (error) {
1321
+ if (errorCode(error) === "ENOENT") {
1322
+ skipFile(accumulator, file, "already-missing");
1323
+ return "missing";
1324
+ }
1325
+ failFile(accumulator, file, `unlink-failed:${errorCode(error) ?? "unknown"}`);
1326
+ return "failed";
1327
+ }
1328
+ markDeleted(accumulator, file, file.size);
1329
+ return "deleted";
1330
+ }
1331
+
1332
+ /** rmdir only; never recursive. Returns true when this call removed the dir. */
1333
+ async function removeEmptyDirectory(dir: string): Promise<boolean> {
1334
+ try {
1335
+ if ((await readdir(dir)).length > 0) return false;
1336
+ await rmdir(dir);
1337
+ return true;
1338
+ } catch (error) {
1339
+ const code = errorCode(error);
1340
+ if (code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST") return false;
1341
+ return false;
1342
+ }
1343
+ }
1344
+
1345
+ async function pruneManagedParents(file: CleanupFileInventory, store: ReportStore): Promise<void> {
1346
+ const parent = dirname(file.path);
1347
+ const parentName = basename(parent);
1348
+ if (file.kind === "report-entry" || file.kind === "workflow-registration") {
1349
+ if (parentName === "agents" || parentName === "workflows") {
1350
+ await removeEmptyDirectory(parent);
1351
+ }
1352
+ return;
1353
+ }
1354
+ if (
1355
+ file.kind === "report-output" ||
1356
+ file.kind === "workflow-generated" ||
1357
+ file.kind === "legacy-output"
1358
+ ) {
1359
+ if (parentName === "tasks") {
1360
+ await removeEmptyDirectory(parent);
1361
+ const storage = store.storage();
1362
+ const sessionDir = dirname(parent);
1363
+ if (isPathWithin(sessionDir, storage.tempRoot)) {
1364
+ await removeEmptyDirectory(sessionDir);
1365
+ }
1366
+ }
1367
+ }
1368
+ }
1369
+
1370
+ interface ReportGroup {
1371
+ rootSessionId: string;
1372
+ agentId: string;
1373
+ files: CleanupFileInventory[];
1374
+ }
1375
+
1376
+ function reportGroups(files: readonly CleanupFileInventory[]): ReportGroup[] {
1377
+ const groups = new Map<string, ReportGroup>();
1378
+ for (const file of files) {
1379
+ if (
1380
+ (file.kind !== "report-entry" &&
1381
+ file.kind !== "report-output" &&
1382
+ file.kind !== "child-session") ||
1383
+ file.agentId === undefined
1384
+ ) {
1385
+ continue;
1386
+ }
1387
+ const key = `${file.rootSessionId}\u0000${file.agentId}`;
1388
+ const existing = groups.get(key);
1389
+ if (existing) {
1390
+ existing.files.push(file);
1391
+ } else {
1392
+ groups.set(key, {
1393
+ rootSessionId: file.rootSessionId,
1394
+ agentId: file.agentId,
1395
+ files: [file],
1396
+ });
1397
+ }
1398
+ }
1399
+ return [...groups.values()].sort(
1400
+ (a, b) => a.rootSessionId.localeCompare(b.rootSessionId) || a.agentId.localeCompare(b.agentId),
1401
+ );
1402
+ }
1403
+
1404
+ /**
1405
+ * Apply a prior preview. Anything not explicitly confirmed is skipped without a
1406
+ * mutation; all dynamic uncertainty is reported, never forced.
1407
+ */
1408
+ export async function applyCleanup(
1409
+ store: ReportStore,
1410
+ plan: CleanupPlan,
1411
+ options: CleanupApplyOptions,
1412
+ ): Promise<CleanupResult> {
1413
+ const accumulator: ApplyAccumulator = {
1414
+ deleted: [],
1415
+ failed: [],
1416
+ skipped: plan.skipped.map((item) => ({ ...item })),
1417
+ deletedAgentIds: new Set<string>(),
1418
+ bytesDeleted: 0,
1419
+ };
1420
+
1421
+ if (!options.confirmed) {
1422
+ for (const file of plan.files) skipFile(accumulator, file, "not-confirmed");
1423
+ return {
1424
+ scope: plan.scope,
1425
+ deleted: accumulator.deleted,
1426
+ failed: accumulator.failed,
1427
+ skipped: accumulator.skipped,
1428
+ deletedAgentIds: [],
1429
+ bytesDeleted: 0,
1430
+ };
1431
+ }
1432
+
1433
+ let live: NormalizedLiveState;
1434
+ try {
1435
+ live = await readLive(options.liveStateGetter);
1436
+ } catch {
1437
+ for (const file of plan.files) skipFile(accumulator, file, "live-state-unavailable");
1438
+ return {
1439
+ scope: plan.scope,
1440
+ deleted: [],
1441
+ failed: [],
1442
+ skipped: accumulator.skipped,
1443
+ deletedAgentIds: [],
1444
+ bytesDeleted: 0,
1445
+ };
1446
+ }
1447
+
1448
+ const rootFiles = new Map<string, CleanupFileInventory[]>();
1449
+ for (const file of plan.files) {
1450
+ if (file.kind === "diagnostics-log") continue;
1451
+ // Legacy candidates join the same shared lock path once the extra legacy
1452
+ // confirmation authorizes creating their minimal control namespace.
1453
+ if (file.kind === "legacy-output" && !options.confirmedLegacy) continue;
1454
+ const list = rootFiles.get(file.rootSessionId);
1455
+ if (list) list.push(file);
1456
+ else rootFiles.set(file.rootSessionId, [file]);
1457
+ }
1458
+ const planRoots = new Map(
1459
+ plan.roots.map((root) => [root.rootSessionId, root] as const),
1460
+ );
1461
+ const rootSessionFiles = new Set<string>();
1462
+ const identity: RootIdentityInventory = {
1463
+ rootSessionFiles,
1464
+ rootSessionIds: new Set<string>(),
1465
+ };
1466
+ for (const root of plan.roots) {
1467
+ if (root.rootSessionFile) rootSessionFiles.add(normalizeReportPath(root.rootSessionFile));
1468
+ identity.rootSessionIds.add(root.rootSessionId);
1469
+ }
1470
+ const expectedGenerations = new Map<string, number>();
1471
+ for (const root of plan.roots) expectedGenerations.set(root.rootSessionId, root.generation);
1472
+
1473
+ const blockedRoots = new Map<string, string>();
1474
+ // Sticky for this operation: once a root was protected under any snapshot it
1475
+ // stays refused, so skipping its lock may never be undone by a later getter.
1476
+ const protectedRoots = new Set<string>(live.protectedRoots);
1477
+ const locks: CleanupLockHandle[] = [];
1478
+ const heldRoots = new Set<string>();
1479
+ let bodyFailure: { error: unknown } | undefined;
1480
+ let releaseFailed = false;
1481
+ let releaseFailure: unknown;
1482
+ try {
1483
+ for (const rootSessionId of [...rootFiles.keys()].sort()) {
1484
+ // Never acquire a protected root's cleanup lock: that lock blocks every
1485
+ // save/register in the root (writeBlockReason) and would stall live work.
1486
+ if (isProtectedRoot(protectedRoots, rootSessionId)) continue;
1487
+ const rootFilesList = rootFiles.get(rootSessionId) ?? [];
1488
+ const selection = {
1489
+ scope: plan.scope,
1490
+ agentIds: [
1491
+ ...new Set(
1492
+ rootFilesList
1493
+ .map((file) => file.agentId)
1494
+ .filter((id): id is string => id !== undefined),
1495
+ ),
1496
+ ],
1497
+ sessionFiles: [
1498
+ ...new Set(
1499
+ rootFilesList
1500
+ .filter((file) => file.kind === "child-session" && file.sessionFile !== undefined)
1501
+ .map((file) => file.sessionFile as string),
1502
+ ),
1503
+ ],
1504
+ };
1505
+ const legacyOnlyRoot =
1506
+ rootFilesList.some((file) => file.kind === "legacy-output") &&
1507
+ !planRoots.has(rootSessionId);
1508
+ const acquired = await store.acquireCleanupLock(
1509
+ rootSessionId,
1510
+ selection,
1511
+ legacyOnlyRoot ? { createRoot: true } : {},
1512
+ );
1513
+ if (!acquired.ok) {
1514
+ blockedRoots.set(rootSessionId, acquired.reason);
1515
+ continue;
1516
+ }
1517
+ locks.push(acquired.handle);
1518
+ heldRoots.add(rootSessionId);
1519
+ const planned = planRoots.get(rootSessionId);
1520
+ if (planned) {
1521
+ const current = (await store.getRootGeneration(rootSessionId)) ?? 0;
1522
+ if (current !== planned.generation) {
1523
+ blockedRoots.set(rootSessionId, "root-generation-changed");
1524
+ }
1525
+ }
1526
+ }
1527
+
1528
+ let preparation: PreparationView = preparationView(undefined);
1529
+ let preparationFailed: string | undefined;
1530
+ if (options.prepare) {
1531
+ try {
1532
+ const prepared = await options.prepare({
1533
+ scope: plan.scope,
1534
+ agentIds: plan.agentIds,
1535
+ sessionFiles: plan.sessionFiles,
1536
+ rootSessionIds: [...rootFiles.keys()],
1537
+ });
1538
+ preparation = preparationView(prepared);
1539
+ for (const [rootSessionId, reason] of preparation.blockedRoots) {
1540
+ blockedRoots.set(rootSessionId, `preparation-blocked:${reason}`);
1541
+ }
1542
+ if (prepared.readyRootSessionIds !== undefined) {
1543
+ const ready = new Set(prepared.readyRootSessionIds);
1544
+ for (const rootSessionId of rootFiles.keys()) {
1545
+ if (!ready.has(rootSessionId) && !blockedRoots.has(rootSessionId)) {
1546
+ blockedRoots.set(rootSessionId, "preparation-root-not-ready");
1547
+ }
1548
+ }
1549
+ }
1550
+ } catch (error) {
1551
+ preparationFailed = `preparation-failed:${errorCode(error) ?? "unknown"}`;
1552
+ }
1553
+ }
1554
+
1555
+ // The getter is intentionally read again: teardown may have changed what is
1556
+ // active, and a captured Set would certify work that started meanwhile.
1557
+ try {
1558
+ live = await readLive(options.liveStateGetter);
1559
+ } catch {
1560
+ preparationFailed = "live-state-unavailable-after-preparation";
1561
+ }
1562
+ for (const rootSessionId of live.protectedRoots) protectedRoots.add(rootSessionId);
1563
+
1564
+ // Recheck global root identities after preview, including lease-only binds:
1565
+ // a child history selected before someone opened it as their main session
1566
+ // must become undeletable before any unlink. A partial inventory is refusal.
1567
+ let identityUncertainty = plan.identityUncertainty;
1568
+ try {
1569
+ const refreshed = await collectGlobalIdentities(store);
1570
+ for (const protectedPath of refreshed.rootSessionFiles) {
1571
+ rootSessionFiles.add(protectedPath);
1572
+ }
1573
+ for (const rootSessionId of refreshed.rootSessionIds) {
1574
+ identity.rootSessionIds.add(rootSessionId);
1575
+ }
1576
+ identityUncertainty ??= refreshed.uncertainty;
1577
+ if (plan.files.some((file) => file.kind === "child-session" || file.kind === "legacy-output")) {
1578
+ for (const legacy of await store.inspectLegacyOutputs()) {
1579
+ const rootSessionFile = legacy.snapshot?.rootSessionFile;
1580
+ if (rootSessionFile) rootSessionFiles.add(normalizeReportPath(rootSessionFile));
1581
+ }
1582
+ }
1583
+ } catch (error) {
1584
+ identityUncertainty ??= `refresh-failed:${errorCode(error) ?? "unknown"}`;
1585
+ }
1586
+
1587
+ const validation: ValidationContext = {
1588
+ store,
1589
+ liveStateGetter: options.liveStateGetter,
1590
+ expectedGenerations,
1591
+ rootSessionFiles,
1592
+ protectedRoots,
1593
+ };
1594
+ // A root may have been locked before it became protected. These gates and
1595
+ // the per-file validation below still refuse it; the lock is only released.
1596
+ const rootBlockReason = (rootSessionId: string): string | undefined =>
1597
+ isProtectedRoot(protectedRoots, rootSessionId)
1598
+ ? PROTECTED_ROOT_REASON
1599
+ : blockedRoots.get(rootSessionId);
1600
+ const rootSkipReason = (reason: string): string =>
1601
+ reason === PROTECTED_ROOT_REASON ? reason : `root-blocked:${reason}`;
1602
+
1603
+ for (const group of reportGroups(plan.files)) {
1604
+ const rootBlock = rootBlockReason(group.rootSessionId);
1605
+ if (rootBlock) {
1606
+ for (const file of group.files) skipFile(accumulator, file, rootSkipReason(rootBlock));
1607
+ continue;
1608
+ }
1609
+ if (preparationFailed) {
1610
+ for (const file of group.files) skipFile(accumulator, file, preparationFailed);
1611
+ continue;
1612
+ }
1613
+ if (isActiveAgent(live, group.agentId)) {
1614
+ for (const file of group.files) skipFile(accumulator, file, "active-agent");
1615
+ continue;
1616
+ }
1617
+ const entry = await store.readEntry(group.rootSessionId, group.agentId);
1618
+ if (!entry) {
1619
+ for (const file of group.files) skipFile(accumulator, file, "report-entry-missing");
1620
+ continue;
1621
+ }
1622
+ if (hasActiveOwner(entry, live)) {
1623
+ for (const file of group.files) skipFile(accumulator, file, "active-owner");
1624
+ continue;
1625
+ }
1626
+ const ownershipLost = group.files.find((file) => {
1627
+ if (file.kind === "report-output") {
1628
+ return (
1629
+ entry.outputFile === undefined ||
1630
+ normalizeReportPath(file.path) !== normalizeReportPath(entry.outputFile) ||
1631
+ !isRegisteredOutputPath(file.path, entry)
1632
+ );
1633
+ }
1634
+ if (file.kind === "child-session") {
1635
+ return (
1636
+ entry.sessionFile === undefined ||
1637
+ normalizeReportPath(file.path) !== normalizeReportPath(entry.sessionFile)
1638
+ );
1639
+ }
1640
+ return false;
1641
+ });
1642
+ if (ownershipLost) {
1643
+ for (const file of group.files) skipFile(accumulator, file, "ownership-proof-lost");
1644
+ continue;
1645
+ }
1646
+ const childCandidate = group.files.find((file) => file.kind === "child-session");
1647
+ const preparationReason = options.prepare
1648
+ ? failureReason(preparation, group.rootSessionId, group.agentId, childCandidate?.path)
1649
+ : undefined;
1650
+ if (preparationReason) {
1651
+ for (const file of group.files) skipFile(accumulator, file, preparationReason);
1652
+ continue;
1653
+ }
1654
+ if (childCandidate) {
1655
+ if (identityUncertainty !== undefined) {
1656
+ for (const file of group.files) {
1657
+ skipFile(accumulator, file, `root-identity-uncertain:${identityUncertainty}`);
1658
+ }
1659
+ continue;
1660
+ }
1661
+ if (!options.prepare) {
1662
+ for (const file of group.files) skipFile(accumulator, file, "teardown-not-prepared");
1663
+ continue;
1664
+ }
1665
+ const check = await verifyChildSession(store, entry, identity);
1666
+ if (!check.ok) {
1667
+ for (const file of group.files) skipFile(accumulator, file, check.reason ?? "child-session-unverified");
1668
+ continue;
1669
+ }
1670
+ }
1671
+
1672
+ const reportCandidate = group.files.find((file) => file.kind === "report-entry");
1673
+ if (reportCandidate) {
1674
+ const changed = await validateFile(validation, reportCandidate);
1675
+ if (changed) {
1676
+ for (const file of group.files) skipFile(accumulator, file, changed);
1677
+ continue;
1678
+ }
1679
+ if (
1680
+ reportCandidate.entryGeneration !== undefined &&
1681
+ entry.entryGeneration !== reportCandidate.entryGeneration
1682
+ ) {
1683
+ for (const file of group.files) skipFile(accumulator, file, "entry-generation-changed");
1684
+ continue;
1685
+ }
1686
+ try {
1687
+ const receipt = await store.writeDeletionReceipt(group.rootSessionId, entry, {
1688
+ expectedEntryGeneration: reportCandidate.entryGeneration,
1689
+ reason: `cleanup:${plan.scope}`,
1690
+ beforeCommit: () => assertRemovable(validation, reportCandidate, entry),
1691
+ });
1692
+ expectedGenerations.set(group.rootSessionId, receipt.rootGeneration);
1693
+ const durableReceipt = await store.readEntry(group.rootSessionId, group.agentId);
1694
+ if (durableReceipt?.state !== "deleted") {
1695
+ throw new Error("receipt-not-durable");
1696
+ }
1697
+ markDeleted(
1698
+ accumulator,
1699
+ reportCandidate,
1700
+ await freedReportBytes(store, reportCandidate),
1701
+ );
1702
+ } catch (error) {
1703
+ if (error instanceof CleanupRefusal) {
1704
+ for (const file of group.files) skipFile(accumulator, file, error.reason);
1705
+ continue;
1706
+ }
1707
+ // Receipt publication is a durable mutation. Carry the exact partial
1708
+ // result to the caller instead of pretending the body still exists or
1709
+ // unlinking artifacts on an unproven receipt.
1710
+ const failure = await receiptFailure(
1711
+ store,
1712
+ plan,
1713
+ accumulator,
1714
+ heldRoots,
1715
+ reportCandidate,
1716
+ group.agentId,
1717
+ error,
1718
+ );
1719
+ throw failure;
1720
+ }
1721
+ }
1722
+
1723
+ for (const file of group.files) {
1724
+ if (file === reportCandidate) continue;
1725
+ const changed = await validateFile(validation, file);
1726
+ if (changed) {
1727
+ skipFile(accumulator, file, changed);
1728
+ continue;
1729
+ }
1730
+ const outcome = await unlinkFile(accumulator, file, validation, entry);
1731
+ if (outcome === "deleted") await pruneManagedParents(file, store);
1732
+ }
1733
+ }
1734
+
1735
+ const workflowGroups = new Map<string, CleanupFileInventory[]>();
1736
+ for (const file of plan.files) {
1737
+ if (file.kind !== "workflow-generated" && file.kind !== "workflow-registration") continue;
1738
+ if (file.workflowId === undefined) continue;
1739
+ const key = `${file.rootSessionId}\u0000${file.workflowId}`;
1740
+ const list = workflowGroups.get(key);
1741
+ if (list) list.push(file);
1742
+ else workflowGroups.set(key, [file]);
1743
+ }
1744
+ for (const key of [...workflowGroups.keys()].sort()) {
1745
+ const files = workflowGroups.get(key) ?? [];
1746
+ const workflowId = files[0].workflowId;
1747
+ const rootSessionId = files[0].rootSessionId;
1748
+ if (workflowId === undefined) continue;
1749
+ const rootBlock = rootBlockReason(rootSessionId);
1750
+ if (rootBlock || preparationFailed) {
1751
+ const reason = rootBlock ?? preparationFailed ?? "root-blocked";
1752
+ for (const file of files) skipFile(accumulator, file, rootSkipReason(reason));
1753
+ continue;
1754
+ }
1755
+ if (isActiveWorkflow(live, workflowId)) {
1756
+ for (const file of files) skipFile(accumulator, file, "active-workflow");
1757
+ continue;
1758
+ }
1759
+ const registration = files.find((file) => file.kind === "workflow-registration");
1760
+ let blocked = false;
1761
+ for (const file of files.filter((candidate) => candidate.kind === "workflow-generated")) {
1762
+ if (!isRegisteredWorkflowPath(file.path, { id: workflowId, rootSessionId })) {
1763
+ skipFile(accumulator, file, "workflow-path-not-registered-to-this-run");
1764
+ blocked = true;
1765
+ continue;
1766
+ }
1767
+ const changed = await validateFile(validation, file);
1768
+ if (changed === "already-missing") continue;
1769
+ if (changed) {
1770
+ skipFile(accumulator, file, changed);
1771
+ blocked = true;
1772
+ continue;
1773
+ }
1774
+ const outcome = await unlinkFile(accumulator, file, validation);
1775
+ if (outcome === "deleted") await pruneManagedParents(file, store);
1776
+ // Failed/refused artifacts keep ownership registered; missing is satisfied.
1777
+ if (outcome === "failed" || outcome === "skipped") blocked = true;
1778
+ }
1779
+ if (blocked) {
1780
+ if (registration) {
1781
+ skipFile(accumulator, registration, "workflow-registration-kept-for-remaining-artifacts");
1782
+ }
1783
+ continue;
1784
+ }
1785
+ if (registration) {
1786
+ const changed = await validateFile(validation, registration);
1787
+ if (changed) {
1788
+ skipFile(accumulator, registration, changed);
1789
+ continue;
1790
+ }
1791
+ try {
1792
+ const removed = await store.removeWorkflowRegistration(
1793
+ rootSessionId,
1794
+ workflowId,
1795
+ registration.workflowUpdatedAt,
1796
+ () => assertRemovable(validation, registration),
1797
+ );
1798
+ if (removed.removed) {
1799
+ if (removed.rootGeneration !== undefined) {
1800
+ expectedGenerations.set(rootSessionId, removed.rootGeneration);
1801
+ }
1802
+ markDeleted(accumulator, registration, registration.size);
1803
+ await pruneManagedParents(registration, store);
1804
+ } else {
1805
+ failFile(accumulator, registration, removed.reason ?? "registration-remove-failed");
1806
+ }
1807
+ } catch (error) {
1808
+ if (error instanceof CleanupRefusal) {
1809
+ skipFile(accumulator, registration, error.reason);
1810
+ continue;
1811
+ }
1812
+ // Unlink-then-generation-write: a verified missing registration is a
1813
+ // real deletion, so record it and hand the exact partial result on.
1814
+ const failure = await workflowRegistrationFailure(
1815
+ store,
1816
+ plan,
1817
+ accumulator,
1818
+ heldRoots,
1819
+ registration,
1820
+ error,
1821
+ );
1822
+ throw failure;
1823
+ }
1824
+ }
1825
+ }
1826
+
1827
+ for (const file of plan.files) {
1828
+ if (file.kind === "root-metadata") {
1829
+ if (basename(file.path) !== "root.json") {
1830
+ skipFile(accumulator, file, "root-metadata-path-mismatch");
1831
+ continue;
1832
+ }
1833
+ const rootBlock = rootBlockReason(file.rootSessionId);
1834
+ if (rootBlock || preparationFailed) {
1835
+ const reason = rootBlock ?? preparationFailed ?? "root-blocked";
1836
+ skipFile(accumulator, file, rootSkipReason(reason));
1837
+ continue;
1838
+ }
1839
+ const changed = await validateFile(validation, file);
1840
+ if (changed) {
1841
+ skipFile(accumulator, file, changed);
1842
+ continue;
1843
+ }
1844
+ try {
1845
+ const removed = await store.removeRootMetadata(
1846
+ file.rootSessionId,
1847
+ expectedGenerations.get(file.rootSessionId) ?? 0,
1848
+ () => assertRemovable(validation, file),
1849
+ );
1850
+ if (removed.removed) {
1851
+ markDeleted(accumulator, file, file.size);
1852
+ } else {
1853
+ skipFile(accumulator, file, removed.reason ?? "root-metadata-not-removed");
1854
+ }
1855
+ } catch (error) {
1856
+ if (!(error instanceof CleanupRefusal)) throw error;
1857
+ skipFile(accumulator, file, error.reason);
1858
+ }
1859
+ continue;
1860
+ }
1861
+ if (file.kind === "legacy-output") {
1862
+ if (!options.confirmedLegacy) {
1863
+ skipFile(accumulator, file, "legacy-confirmation-required");
1864
+ continue;
1865
+ }
1866
+ const rootBlock = rootBlockReason(file.rootSessionId);
1867
+ if (rootBlock || preparationFailed) {
1868
+ const reason = rootBlock ?? preparationFailed ?? "root-blocked";
1869
+ skipFile(accumulator, file, rootSkipReason(reason));
1870
+ continue;
1871
+ }
1872
+ const preparationReason = failureReason(
1873
+ preparation,
1874
+ file.rootSessionId,
1875
+ file.agentId,
1876
+ undefined,
1877
+ );
1878
+ if (preparationReason) {
1879
+ skipFile(accumulator, file, preparationReason);
1880
+ continue;
1881
+ }
1882
+ const changed = await validateFile(validation, file);
1883
+ if (changed) {
1884
+ skipFile(accumulator, file, changed);
1885
+ continue;
1886
+ }
1887
+ const verified = await store.inspectLegacyOutputs();
1888
+ const proven = verified.find(
1889
+ (item) =>
1890
+ item.verified &&
1891
+ item.snapshot !== undefined &&
1892
+ normalizeReportPath(item.path) === normalizeReportPath(file.path),
1893
+ );
1894
+ if (!proven || proven.snapshot === undefined) {
1895
+ skipFile(accumulator, file, "legacy-ownership-unproven");
1896
+ continue;
1897
+ }
1898
+ // Durable receipt before the unlink: the parent record remains untouched,
1899
+ // but a same-parent lookup/reload must report deliberate deletion.
1900
+ try {
1901
+ const receipt = await store.writeLegacyDeletionReceipt(proven.snapshot, {
1902
+ reason: `cleanup:${plan.scope}:legacy`,
1903
+ beforeCommit: () => assertRemovable(validation, file, proven.snapshot),
1904
+ });
1905
+ expectedGenerations.set(file.rootSessionId, receipt.rootGeneration);
1906
+ } catch (error) {
1907
+ if (error instanceof CleanupRefusal) {
1908
+ skipFile(accumulator, file, error.reason);
1909
+ continue;
1910
+ }
1911
+ failFile(
1912
+ accumulator,
1913
+ file,
1914
+ `legacy-receipt-failed:${errorCode(error) ?? "unknown"}`,
1915
+ );
1916
+ continue;
1917
+ }
1918
+ const outcome = await unlinkFile(accumulator, file, validation, proven.snapshot);
1919
+ if (outcome === "deleted") await pruneManagedParents(file, store);
1920
+ if ((outcome === "deleted" || outcome === "missing") && file.agentId !== undefined) {
1921
+ accumulator.deletedAgentIds.add(file.agentId);
1922
+ }
1923
+ continue;
1924
+ }
1925
+ if (file.kind === "diagnostics-log") {
1926
+ if (plan.scope !== "global") {
1927
+ skipFile(accumulator, file, "diagnostics-only-in-global-scope");
1928
+ continue;
1929
+ }
1930
+ const expectedLog = join(store.storage().agentDir, "pi-subagents", "agent-errors.jsonl");
1931
+ if (normalizeReportPath(file.path) !== normalizeReportPath(expectedLog)) {
1932
+ skipFile(accumulator, file, "diagnostics-path-mismatch");
1933
+ continue;
1934
+ }
1935
+ if (preparationFailed) {
1936
+ skipFile(accumulator, file, preparationFailed);
1937
+ continue;
1938
+ }
1939
+ if (live.diagnosticsBusy) {
1940
+ skipFile(accumulator, file, "shared-diagnostics-writer-active");
1941
+ continue;
1942
+ }
1943
+ const changed = await validateFile(validation, file);
1944
+ if (changed) {
1945
+ skipFile(accumulator, file, changed);
1946
+ continue;
1947
+ }
1948
+ try {
1949
+ await flushIssueLog();
1950
+ } catch {
1951
+ skipFile(accumulator, file, "diagnostics-drain-failed");
1952
+ continue;
1953
+ }
1954
+ const afterDrain = await validateFile(validation, file);
1955
+ if (afterDrain) {
1956
+ skipFile(accumulator, file, afterDrain);
1957
+ continue;
1958
+ }
1959
+ await unlinkFile(accumulator, file, validation);
1960
+ }
1961
+ }
1962
+ } catch (error) {
1963
+ // Hand every unexpected apply error to the caller with this partition's
1964
+ // exact partial progress; the finally below still releases the locks.
1965
+ bodyFailure = { error };
1966
+ } finally {
1967
+ for (const lock of locks) {
1968
+ try {
1969
+ await store.releaseCleanupLock(lock);
1970
+ } catch (error) {
1971
+ // A release error must neither discard actual deletions nor skip the
1972
+ // remaining roots' locks; it becomes a failure and a rejected apply.
1973
+ if (!releaseFailed) {
1974
+ releaseFailed = true;
1975
+ releaseFailure = error;
1976
+ }
1977
+ accumulator.failed.push({
1978
+ reason: `cleanup-lock-release-failed:${errorDetail(error)}`,
1979
+ });
1980
+ }
1981
+ heldRoots.delete(lock.rootSessionId);
1982
+ }
1983
+ for (const file of accumulator.deleted) {
1984
+ if (file.kind === "root-metadata" && file.rootSessionId !== undefined && file.rootSessionId.length > 0) {
1985
+ const root = plan.roots.find((item) => item.rootSessionId === file.rootSessionId);
1986
+ if (root) await removeEmptyDirectory(join(store.storage().reportsRoot, root.rootSessionId));
1987
+ }
1988
+ }
1989
+ }
1990
+
1991
+ if (bodyFailure !== undefined) {
1992
+ throw cleanupApplyFailure(plan, accumulator, bodyFailure.error);
1993
+ }
1994
+ if (releaseFailed) throw cleanupApplyFailure(plan, accumulator, releaseFailure);
1995
+
1996
+ return cleanupResult(plan, accumulator);
1997
+ }
1998
+
1999
+ /** Counts for a merged or partitioned preview, using the inventory's same rules. */
2000
+ export function cleanupCounts(files: readonly CleanupFileInventory[]): CleanupPlanCounts {
2001
+ const counts = emptyCounts();
2002
+ for (const file of files) countFile(counts, file);
2003
+ return counts;
2004
+ }
2005
+
2006
+ /** True when a plan contains no mutation candidates at all. */
2007
+ export function isCleanupPlanEmpty(plan: CleanupPlan): boolean {
2008
+ return plan.files.length === 0;
2009
+ }
2010
+
2011
+ /** Read-state labels the UI should show verbatim; archived "unknown" is never "read". */
2012
+ export function cleanupReadStateLabel(state: CleanupReadState): string {
2013
+ switch (state) {
2014
+ case "read":
2015
+ return "read";
2016
+ case "unread":
2017
+ return "unread";
2018
+ default:
2019
+ return "unknown (archived read state was not recorded)";
2020
+ }
2021
+ }
2022
+
2023
+ /** A marker type re-exported for integration code that keys candidate lists. */
2024
+ export type CleanupCandidateIds = {
2025
+ agentIds: readonly string[];
2026
+ sessionFiles: readonly string[];
2027
+ };
2028
+
2029
+ export function cleanupCandidateIds(plan: CleanupPlan): CleanupCandidateIds {
2030
+ return { agentIds: plan.agentIds, sessionFiles: plan.sessionFiles };
2031
+ }
2032
+
2033
+ /** Guard used by callers before treating an exact id as canonical. */
2034
+ export function isCleanupAgentId(value: string): boolean {
2035
+ return isCanonicalAgentId(value) && isSafePathComponent(value);
2036
+ }
2037
+
2038
+ /** Exported only so fixture builders share the same normalization as apply. */
2039
+ export function cleanupPathKey(path: string): string {
2040
+ return normalizeReportPath(resolve(path));
2041
+ }
2042
+
2043
+ /** A report snapshot's provenance labels are part of the cleanup/read contract. */
2044
+ export type CleanupRecoveredReport = ReportSnapshot;