dsh-taskbridge 1.9.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,715 +1,715 @@
1
- import { buildTaskTree } from './task-tree.js';
2
- import { HISTORY_CODES, HISTORY_DELETE_MAX_TASKS } from './history.js';
3
- import { sessionPathKey } from '../runtime/session-placement.js';
4
-
5
- export const MAX_CLEANUP_CHAINS = 100;
6
- const FINISHED = new Set(['awaiting-host-review', 'failed', 'cancelled', 'interrupted']);
7
- const ALLOWED_CLEANUP_KEYS = new Set(['chains', 'confirm', 'archiveSessions', 'removeWorktrees', 'cleanPlans']);
8
- const ALLOWED_ORPHAN_KEYS = new Set(['confirm', 'archiveSessions', 'removeWorktrees']);
9
-
10
- export const CLEANUP_CODES = Object.freeze({
11
- invalid: 'CLEANUP_INVALID',
12
- notFound: 'CLEANUP_CHAIN_NOT_FOUND',
13
- stale: 'CLEANUP_STALE',
14
- live: 'CLEANUP_CHAIN_LIVE',
15
- notDurable: 'CLEANUP_NOT_DURABLE',
16
- nextRound: 'CLEANUP_NEXT_ROUND',
17
- planChildren: 'CLEANUP_PLAN_CHILDREN',
18
- hierarchyChildren: 'CLEANUP_HIERARCHY_CHILDREN',
19
- reviewWrite: 'CLEANUP_REVIEW_WRITE',
20
- unavailable: 'CLEANUP_UNAVAILABLE',
21
- failed: 'CLEANUP_FAILED',
22
- });
23
-
24
- class CleanupError extends Error {
25
- constructor(code, message, details = {}) {
26
- super(message);
27
- this.name = 'CleanupError';
28
- this.code = code;
29
- this.details = details;
30
- }
31
- }
32
-
33
- function invalid(message, details) {
34
- throw new CleanupError(CLEANUP_CODES.invalid, message, details);
35
- }
36
-
37
- function isObject(value) {
38
- return value !== null && typeof value === 'object' && !Array.isArray(value);
39
- }
40
-
41
- function isId(value) {
42
- return typeof value === 'string' && value.length > 0 && value.length <= 256 && value.trim() === value;
43
- }
44
-
45
- export function validateCleanupRequest(body) {
46
- if (!isObject(body) || Object.keys(body).some((key) => !ALLOWED_CLEANUP_KEYS.has(key))) {
47
- invalid('expected only chains and explicit confirmation');
48
- }
49
- if (body.confirm !== true) invalid('cleanup requires explicit confirmation', { field: 'confirm' });
50
- for (const flag of ['archiveSessions', 'removeWorktrees', 'cleanPlans']) {
51
- if (body[flag] !== undefined && typeof body[flag] !== 'boolean') {
52
- invalid(`${flag} must be a boolean`, { field: flag });
53
- }
54
- }
55
- if (!Array.isArray(body.chains) || body.chains.length === 0 || body.chains.length > MAX_CLEANUP_CHAINS) {
56
- invalid('select a bounded list of execution chains', { field: 'chains', limit: MAX_CLEANUP_CHAINS });
57
- }
58
- const chainIds = new Set();
59
- const taskIds = new Set();
60
- const chains = body.chains.map((chain, index) => {
61
- if (!isObject(chain) || Object.keys(chain).some((key) => key !== 'chainId' && key !== 'taskIds') || !isId(chain.chainId)) {
62
- invalid('expected a chain id and its exact rounds', { index });
63
- }
64
- if (chainIds.has(chain.chainId)) invalid('duplicate chain id', { index });
65
- chainIds.add(chain.chainId);
66
- if (!Array.isArray(chain.taskIds) || chain.taskIds.length === 0) invalid('select the complete chain', { index });
67
- for (const id of chain.taskIds) {
68
- if (!isId(id) || taskIds.has(id)) invalid('expected unique task ids', { index });
69
- taskIds.add(id);
70
- if (taskIds.size > HISTORY_DELETE_MAX_TASKS) invalid('too many rounds for one batch', { limit: HISTORY_DELETE_MAX_TASKS });
71
- }
72
- return { chainId: chain.chainId, taskIds: [...chain.taskIds] };
73
- });
74
- return {
75
- chains,
76
- options: {
77
- archiveSessions: body.archiveSessions === true,
78
- removeWorktrees: body.removeWorktrees === true,
79
- cleanPlans: body.cleanPlans === true,
80
- },
81
- };
82
- }
83
-
84
- function planStore(deps) {
85
- return deps.plans ?? deps.engine?.plans ?? null;
86
- }
87
-
88
- function collectChains(node, byChain) {
89
- for (const chain of node.chain ? [node.chain] : node.executions ?? []) byChain.set(chain.chainId, chain);
90
- for (const child of node.children) collectChains(child, byChain);
91
- }
92
-
93
- function cleanupContext(engine, archived, plans) {
94
- const live = engine?.list?.() ?? [];
95
- const liveById = new Map(live.map((row) => [row.taskId, row]));
96
- const archivedById = new Map(archived.map((row) => [row.taskId, row]));
97
- const tasks = new Map([...archivedById, ...liveById]);
98
- const continuations = new Map();
99
- const taskChildren = new Map();
100
- const liveReuseChildren = new Map();
101
- const planParents = new Set(plans.map((node) => node.parentNodeId));
102
- const remember = (map, parent, child) => {
103
- if (typeof parent !== 'string' || parent === '' || parent === child) return;
104
- if (!map.has(parent)) map.set(parent, new Set());
105
- map.get(parent).add(child);
106
- };
107
- for (const row of [...archived, ...live]) {
108
- remember(continuations, row.continueFromTaskId, row.taskId);
109
- remember(taskChildren, row.parentNodeId, row.taskId);
110
- remember(taskChildren, row.planNodeId, row.taskId);
111
- }
112
- for (const row of tasks.values()) {
113
- if (!FINISHED.has(row.state)) {
114
- remember(liveReuseChildren, row.reuseWorktreeFromTaskId, row.taskId);
115
- }
116
- }
117
- const tree = buildTaskTree({ planNodes: plans, tasks: [...tasks.values()] });
118
- const byChain = new Map();
119
- for (const root of tree.roots) collectChains(root, byChain);
120
- return { byChain, liveById, archivedById, continuations, taskChildren, liveReuseChildren, planParents, engine };
121
- }
122
-
123
- function blockersFor(chain, context) {
124
- const blockers = new Set();
125
- const members = new Set(chain.taskIds);
126
- for (const taskId of members) {
127
- const live = context.liveById.get(taskId);
128
- const archived = context.archivedById.get(taskId);
129
- if ((live && !FINISHED.has(live.state)) || (archived && !FINISHED.has(archived.state))) {
130
- blockers.add(CLEANUP_CODES.live);
131
- } else if (!archived || (live && !context.engine.isTaskSettledForCleanup?.(taskId))) {
132
- blockers.add(CLEANUP_CODES.notDurable);
133
- }
134
- if (context.engine?.reviewWriteDone?.(taskId)) blockers.add(CLEANUP_CODES.reviewWrite);
135
- for (const child of context.continuations.get(taskId) ?? []) {
136
- if (!members.has(child)) blockers.add(CLEANUP_CODES.nextRound);
137
- }
138
- for (const child of context.taskChildren.get(taskId) ?? []) {
139
- if (!members.has(child)) blockers.add(CLEANUP_CODES.hierarchyChildren);
140
- }
141
- for (const child of context.liveReuseChildren.get(taskId) ?? []) {
142
- if (!members.has(child)) blockers.add(CLEANUP_CODES.hierarchyChildren);
143
- }
144
- if (context.planParents.has(taskId)) blockers.add(CLEANUP_CODES.planChildren);
145
- }
146
- return [...blockers];
147
- }
148
-
149
- export async function cleanupOverview(deps) {
150
- const archived = await deps.history.load();
151
- const plans = await planStore(deps)?.load() ?? [];
152
- const context = cleanupContext(deps.engine, archived, plans);
153
- const chains = [...context.byChain.values()].map((chain) => {
154
- const blockers = blockersFor(chain, context);
155
- return { chainId: chain.chainId, taskIds: [...chain.taskIds], eligible: blockers.length === 0, blockers };
156
- });
157
- return { chains };
158
- }
159
-
160
- function checkBatch(chains, context) {
161
- const refused = [];
162
- for (const { chainId, taskIds } of chains) {
163
- const chain = context.byChain.get(chainId);
164
- let blockers;
165
- if (!chain) blockers = [CLEANUP_CODES.notFound];
166
- else if (chain.taskIds.length !== taskIds.length || chain.taskIds.some((id, i) => id !== taskIds[i])) {
167
- blockers = [CLEANUP_CODES.stale];
168
- } else blockers = blockersFor(chain, context);
169
- if (blockers.length) refused.push({ chainId, code: blockers[0], blockers });
170
- }
171
- if (refused.length) {
172
- throw new CleanupError(refused[0].code, 'the selected chains cannot be removed as one batch', {
173
- chains: refused, reason: refused[0].code, deleted: 0,
174
- });
175
- }
176
- }
177
-
178
- export async function runCleanup(deps, body) {
179
- const { chains, options } = validateCleanupRequest(body);
180
- const store = deps.history;
181
- const plans = planStore(deps);
182
- const engine = deps.engine;
183
- if (typeof store?.deleteMany !== 'function' || (plans && typeof plans.withStableNodes !== 'function')) {
184
- throw new CleanupError(CLEANUP_CODES.unavailable, 'task record cleanup is unavailable');
185
- }
186
- const ids = chains.flatMap((chain) => chain.taskIds);
187
- const idsSet = new Set(ids);
188
- let deletedRowsSnapshot = [];
189
- let remainingRowsSnapshot = [];
190
- const deleteRecords = async (planNodes) => {
191
- let release;
192
- try {
193
- return await store.deleteMany(ids, {
194
- beforeWrite(archived) {
195
- // Read the latest engine state inside the history queue. No asynchronous
196
- // work may run between checking relationships and reserving these ids.
197
- const context = cleanupContext(engine, archived, planNodes);
198
- checkBatch(chains, context);
199
- const allTasks = new Map([...context.archivedById, ...context.liveById]);
200
- deletedRowsSnapshot = ids.map((id) => allTasks.get(id)).filter(Boolean);
201
- remainingRowsSnapshot = [...allTasks.values()].filter((row) => !idsSet.has(row.taskId));
202
- release = engine?.reserveCleanupIds(ids);
203
- },
204
- afterWrite(deletedIds) {
205
- engine?.forgetCleanedRecords(deletedIds);
206
- },
207
- });
208
- } finally {
209
- release?.();
210
- }
211
- };
212
- let result;
213
- try {
214
- result = plans ? await plans.withStableNodes(deleteRecords) : await deleteRecords([]);
215
- } catch (error) {
216
- if (error instanceof CleanupError) throw error;
217
- const code = error?.code === HISTORY_CODES.deleteInvalid ? CLEANUP_CODES.stale
218
- : error?.code === HISTORY_CODES.writeFailed ? CLEANUP_CODES.failed : CLEANUP_CODES.unavailable;
219
- throw new CleanupError(code, 'the task records could not be removed', { deleted: 0 });
220
- }
221
-
222
- const hasLinkedCleanup = options.archiveSessions || options.removeWorktrees || options.cleanPlans;
223
- if (!hasLinkedCleanup) {
224
- return {
225
- chains: chains.length,
226
- tasks: result.deletedTaskIds.length,
227
- ...result,
228
- retained: { sessions: true, workspaces: true, worktrees: true, sourceFiles: true, plans: true },
229
- };
230
- }
231
-
232
- const linked = await performLinkedCleanup(deps, {
233
- options,
234
- deletedTaskIds: result.deletedTaskIds,
235
- deletedRows: deletedRowsSnapshot,
236
- remainingRows: remainingRowsSnapshot,
237
- plans,
238
- });
239
-
240
- return {
241
- chains: chains.length,
242
- tasks: result.deletedTaskIds.length,
243
- ...result,
244
- retained: {
245
- sessions: !options.archiveSessions,
246
- workspaces: !options.removeWorktrees,
247
- worktrees: !options.removeWorktrees,
248
- sourceFiles: true,
249
- plans: !options.cleanPlans,
250
- },
251
- cleaned: linked,
252
- };
253
- }
254
-
255
- function firstNonEmpty(...values) {
256
- for (const val of values) {
257
- if (typeof val === 'string' && val.trim() !== '') return val.trim();
258
- }
259
- return null;
260
- }
261
-
262
- function extractTaskFacts(row, sessionRow = null) {
263
- const isolation = firstNonEmpty(
264
- row?.isolation,
265
- row?.effective?.worker?.isolation,
266
- sessionRow?.isolation,
267
- );
268
- const sourcePath = firstNonEmpty(
269
- sessionRow?.sourcePath,
270
- row?.sourcePath,
271
- row?.execution?.sourcePath,
272
- row?.conversation?.sourcePath,
273
- );
274
- const executionPath = firstNonEmpty(
275
- sessionRow?.executionPath,
276
- row?.executionWorkspacePath,
277
- row?.worktree?.workspacePath,
278
- row?.execution?.workspacePath,
279
- row?.workspacePath,
280
- );
281
- const workspaceId = firstNonEmpty(
282
- sessionRow?.workspaceId,
283
- row?.workspaceId,
284
- row?.execution?.workspaceId,
285
- row?.execution?.conversation?.workspaceId,
286
- row?.conversation?.workspaceId,
287
- );
288
- const sessionId = firstNonEmpty(
289
- sessionRow?.sessionId,
290
- row?.sessionId,
291
- row?.execution?.sessionId,
292
- row?.execution?.conversation?.sessionId,
293
- row?.conversation?.sessionId,
294
- );
295
- return {
296
- taskId: firstNonEmpty(row?.taskId, sessionRow?.taskId),
297
- isolation,
298
- sourcePath,
299
- executionPath,
300
- workspaceId,
301
- sessionId,
302
- planNodeId: firstNonEmpty(row?.planNodeId),
303
- parentNodeId: firstNonEmpty(row?.parentNodeId),
304
- };
305
- }
306
-
307
- function resolveController(serviceOrAccessor) {
308
- if (serviceOrAccessor === null || serviceOrAccessor === undefined) return null;
309
- if (typeof serviceOrAccessor === 'object' && 'current' in serviceOrAccessor) {
310
- return serviceOrAccessor.current ?? null;
311
- }
312
- return serviceOrAccessor;
313
- }
314
-
315
- async function tryArchiveHostSession(deps, sessionId) {
316
- const ws = resolveController(deps?.workspaces);
317
- if (typeof ws?.archiveSession === 'function') {
318
- try {
319
- await ws.archiveSession(sessionId);
320
- return true;
321
- } catch {
322
- try {
323
- await ws.archiveSession({ sessionId });
324
- return true;
325
- } catch {
326
- // Ignore host controller error; browser client also reconciles via client workspaces service.
327
- }
328
- }
329
- }
330
- const sc = resolveController(deps?.sessionController);
331
- if (typeof sc?.archiveSession === 'function') {
332
- try {
333
- await sc.archiveSession(sessionId);
334
- return true;
335
- } catch {
336
- // Ignore
337
- }
338
- }
339
- return false;
340
- }
341
-
342
- async function tryDeleteHostWorkspace(deps, workspaceId) {
343
- const ws = resolveController(deps?.workspaces);
344
- if (typeof ws?.delete === 'function') {
345
- try {
346
- await ws.delete(workspaceId);
347
- return true;
348
- } catch {
349
- try {
350
- await ws.delete({ workspaceId });
351
- return true;
352
- } catch {
353
- // Ignore
354
- }
355
- }
356
- }
357
- return false;
358
- }
359
-
360
- function collectReservedReuseRefs(rows, knownRowsById, sessionByTask, engine) {
361
- const paths = [];
362
- const sessionIds = [];
363
- const workspaceIds = [];
364
- const upstreamTaskIds = new Set();
365
- if (typeof engine?.reservedWorktreePathsForCleanup === 'function') {
366
- for (const candidate of engine.reservedWorktreePathsForCleanup()) {
367
- if (typeof candidate === 'string' && candidate.trim() !== '') paths.push(candidate.trim());
368
- }
369
- }
370
- if (typeof engine?.reservedContinuationRefsForCleanup === 'function') {
371
- const refs = engine.reservedContinuationRefsForCleanup();
372
- for (const id of Array.isArray(refs?.sessionIds) ? refs.sessionIds : []) {
373
- if (typeof id === 'string' && id.trim() !== '') sessionIds.push(id.trim());
374
- }
375
- for (const id of Array.isArray(refs?.workspaceIds) ? refs.workspaceIds : []) {
376
- if (typeof id === 'string' && id.trim() !== '') workspaceIds.push(id.trim());
377
- }
378
- }
379
- for (const row of rows) {
380
- if (FINISHED.has(row?.state)) continue;
381
- const reuseId = firstNonEmpty(row?.reuseWorktreeFromTaskId);
382
- const contId = firstNonEmpty(row?.continueFromTaskId);
383
- const upstreamId = firstNonEmpty(reuseId, contId);
384
- if (upstreamId === null) continue;
385
- upstreamTaskIds.add(upstreamId);
386
- const upstreamFacts = extractTaskFacts(knownRowsById.get(upstreamId) ?? null, sessionByTask.get(upstreamId) ?? null);
387
- if (upstreamFacts.executionPath !== null) {
388
- const execKey = sessionPathKey(upstreamFacts.executionPath);
389
- const sourceKey = sessionPathKey(upstreamFacts.sourcePath);
390
- if (execKey !== null && execKey !== sourceKey) paths.push(upstreamFacts.executionPath);
391
- }
392
- if (upstreamFacts.workspaceId !== null) workspaceIds.push(upstreamFacts.workspaceId);
393
- if (contId !== null && upstreamFacts.sessionId !== null) sessionIds.push(upstreamFacts.sessionId);
394
- }
395
- return { paths, sessionIds, workspaceIds, upstreamTaskIds };
396
- }
397
-
398
- async function performLinkedCleanup(deps, { options, deletedTaskIds, deletedRows, remainingRows, plans }) {
399
- const deletedSet = new Set(deletedTaskIds);
400
- let sessionRows = [];
401
- if (typeof deps?.sessionStore?.list === 'function') {
402
- try {
403
- sessionRows = await deps.sessionStore.list();
404
- } catch {
405
- sessionRows = [];
406
- }
407
- }
408
- const sessionByTask = new Map(sessionRows.map((row) => [row.taskId, row]));
409
- const knownRowsById = new Map(
410
- [...deletedRows, ...remainingRows]
411
- .filter((row) => typeof row?.taskId === 'string' && row.taskId !== '')
412
- .map((row) => [row.taskId, row]),
413
- );
414
-
415
- const activeSessionIds = new Set();
416
- const activeWorkspaceIds = new Set();
417
- const activeExecKeys = new Set();
418
- for (const row of remainingRows) {
419
- const facts = extractTaskFacts(row, sessionByTask.get(row.taskId));
420
- if (facts.sessionId !== null) activeSessionIds.add(facts.sessionId);
421
- if (facts.workspaceId !== null) activeWorkspaceIds.add(facts.workspaceId);
422
- const execKey = sessionPathKey(facts.executionPath);
423
- if (execKey !== null) activeExecKeys.add(execKey);
424
- }
425
- const reservedLinked = collectReservedReuseRefs(remainingRows, knownRowsById, sessionByTask, deps?.engine);
426
- for (const sid of reservedLinked.sessionIds) activeSessionIds.add(sid);
427
- for (const wid of reservedLinked.workspaceIds) activeWorkspaceIds.add(wid);
428
- for (const reservedPath of reservedLinked.paths) {
429
- const reservedKey = sessionPathKey(reservedPath);
430
- if (reservedKey !== null) activeExecKeys.add(reservedKey);
431
- }
432
-
433
- const deletedFacts = deletedTaskIds.map((taskId) => {
434
- const row = deletedRows.find((item) => item?.taskId === taskId) ?? { taskId };
435
- return extractTaskFacts(row, sessionByTask.get(taskId));
436
- });
437
-
438
- const archivedSessionIds = [];
439
- const archivedSet = new Set();
440
- if (options.archiveSessions) {
441
- for (const facts of deletedFacts) {
442
- if (facts.sessionId !== null && !activeSessionIds.has(facts.sessionId) && !archivedSet.has(facts.sessionId)) {
443
- archivedSet.add(facts.sessionId);
444
- archivedSessionIds.push(facts.sessionId);
445
- await tryArchiveHostSession(deps, facts.sessionId);
446
- }
447
- }
448
- if (typeof deps?.sessionStore?.forgetMany === 'function') {
449
- await deps.sessionStore.forgetMany(deletedSet).catch(() => []);
450
- } else if (typeof deps?.sessionStore?.forget === 'function') {
451
- for (const id of deletedSet) {
452
- await deps.sessionStore.forget(id).catch(() => false);
453
- }
454
- }
455
- }
456
-
457
- const removedWorktreePaths = [];
458
- const removedWorktreeSet = new Set();
459
- const removedWorkspaceIds = [];
460
- const removedWorkspaceSet = new Set();
461
-
462
- if (options.removeWorktrees) {
463
- for (const facts of deletedFacts) {
464
- // Strictly operate ONLY on worktree-isolated tasks; never touch shared directories or shared workspaces.
465
- if (facts.isolation !== 'worktree') continue;
466
- const execKey = sessionPathKey(facts.executionPath);
467
- const sourceKey = sessionPathKey(facts.sourcePath);
468
- if (execKey === null || execKey === sourceKey || activeExecKeys.has(execKey)) continue;
469
-
470
- let worktreeEligibleForWorkspaceRemoval = false;
471
- if (typeof deps?.worktrees?.removeManagedTree === 'function') {
472
- if (!removedWorktreeSet.has(execKey)) {
473
- const outcome = await deps.worktrees.removeManagedTree({
474
- taskId: facts.taskId,
475
- sourcePath: facts.sourcePath,
476
- workspacePath: facts.executionPath,
477
- });
478
- if (outcome.removed && outcome.workspacePath) {
479
- removedWorktreeSet.add(execKey);
480
- removedWorktreePaths.push(outcome.workspacePath);
481
- worktreeEligibleForWorkspaceRemoval = true;
482
- } else if (outcome.reason === 'already-absent') {
483
- removedWorktreeSet.add(execKey);
484
- worktreeEligibleForWorkspaceRemoval = true;
485
- }
486
- } else {
487
- worktreeEligibleForWorkspaceRemoval = true;
488
- }
489
- }
490
-
491
- if (
492
- worktreeEligibleForWorkspaceRemoval
493
- && facts.workspaceId !== null
494
- && !activeWorkspaceIds.has(facts.workspaceId)
495
- && !removedWorkspaceSet.has(facts.workspaceId)
496
- ) {
497
- removedWorkspaceSet.add(facts.workspaceId);
498
- removedWorkspaceIds.push(facts.workspaceId);
499
- await tryDeleteHostWorkspace(deps, facts.workspaceId);
500
- }
501
- }
502
- }
503
-
504
- let removedPlanNodeIds = [];
505
- if (options.cleanPlans && typeof plans?.deleteEmptyAncestors === 'function') {
506
- const seedPlanIds = new Set();
507
- for (const facts of deletedFacts) {
508
- if (facts.planNodeId !== null) seedPlanIds.add(facts.planNodeId);
509
- if (facts.parentNodeId !== null && facts.parentNodeId.startsWith('plan-')) {
510
- seedPlanIds.add(facts.parentNodeId);
511
- }
512
- }
513
- if (seedPlanIds.size > 0) {
514
- try {
515
- removedPlanNodeIds = await plans.deleteEmptyAncestors(seedPlanIds, remainingRows);
516
- } catch {
517
- removedPlanNodeIds = [];
518
- }
519
- }
520
- }
521
-
522
- return {
523
- archivedSessionIds,
524
- removedWorktreePaths,
525
- removedWorkspaceIds,
526
- removedPlanNodeIds,
527
- };
528
- }
529
-
530
- export function validateOrphanCleanupRequest(body) {
531
- if (!isObject(body) || Object.keys(body).some((key) => !ALLOWED_ORPHAN_KEYS.has(key))) {
532
- invalid('expected explicit confirmation for orphan cleanup');
533
- }
534
- if (body.confirm !== true) invalid('orphan cleanup requires explicit confirmation', { field: 'confirm' });
535
- for (const flag of ['archiveSessions', 'removeWorktrees']) {
536
- if (body[flag] !== undefined && typeof body[flag] !== 'boolean') {
537
- invalid(`${flag} must be a boolean`, { field: flag });
538
- }
539
- }
540
- return {
541
- archiveSessions: body.archiveSessions !== false,
542
- removeWorktrees: body.removeWorktrees !== false,
543
- };
544
- }
545
-
546
- /**
547
- * Sweep residual worktrees and dispatched session identities whose task records
548
- * were already deleted or rotated out of `history.json`.
549
- *
550
- * Strictly preserves any session, workspace or directory still referenced by a live
551
- * or retained historical task, and never touches a shared checkout or shared project
552
- * Workspace.
553
- * @param {object} deps - runtime dependencies.
554
- * @param {object} body - `{ confirm: true, archiveSessions?: boolean, removeWorktrees?: boolean }`.
555
- * @returns {Promise<object>} sweep outcome.
556
- */
557
- export async function runOrphanCleanup(deps, body) {
558
- const options = validateOrphanCleanupRequest(body);
559
- const store = deps?.history;
560
- if (typeof store?.load !== 'function') {
561
- throw new CleanupError(CLEANUP_CODES.unavailable, 'task history is unavailable');
562
- }
563
- let archived = [];
564
- try {
565
- archived = await store.load();
566
- } catch {
567
- throw new CleanupError(CLEANUP_CODES.unavailable, 'task history could not be read');
568
- }
569
- const live = deps?.engine?.list?.() ?? [];
570
- const allExisting = [...archived, ...live];
571
- const existingTaskIds = new Set(allExisting.map((row) => row?.taskId).filter(Boolean));
572
-
573
- let sessionRows = [];
574
- if (typeof deps?.sessionStore?.list === 'function') {
575
- try {
576
- sessionRows = await deps.sessionStore.list();
577
- } catch {
578
- sessionRows = [];
579
- }
580
- }
581
- const sessionByTask = new Map(sessionRows.map((row) => [row.taskId, row]));
582
-
583
- const activeSessionIds = new Set();
584
- const activeWorkspaceIds = new Set();
585
- const activeExecKeys = new Set();
586
- const activeExecPaths = [];
587
- const knownSourcePaths = new Set();
588
-
589
- const knownRowsById = new Map(
590
- allExisting
591
- .filter((row) => typeof row?.taskId === 'string' && row.taskId !== '')
592
- .map((row) => [row.taskId, row]),
593
- );
594
- for (const row of allExisting) {
595
- const facts = extractTaskFacts(row, sessionByTask.get(row.taskId));
596
- if (facts.sessionId !== null) activeSessionIds.add(facts.sessionId);
597
- if (facts.workspaceId !== null) activeWorkspaceIds.add(facts.workspaceId);
598
- if (facts.sourcePath !== null) knownSourcePaths.add(facts.sourcePath);
599
- if (facts.executionPath !== null) {
600
- activeExecPaths.push(facts.executionPath);
601
- const key = sessionPathKey(facts.executionPath);
602
- if (key !== null) activeExecKeys.add(key);
603
- }
604
- }
605
- const reservedOrphan = collectReservedReuseRefs(allExisting, knownRowsById, sessionByTask, deps?.engine);
606
- for (const sid of reservedOrphan.sessionIds) activeSessionIds.add(sid);
607
- for (const wid of reservedOrphan.workspaceIds) activeWorkspaceIds.add(wid);
608
- for (const reservedPath of reservedOrphan.paths) {
609
- activeExecPaths.push(reservedPath);
610
- const key = sessionPathKey(reservedPath);
611
- if (key !== null) activeExecKeys.add(key);
612
- }
613
-
614
- const orphanRows = sessionRows.filter(
615
- (row) => typeof row?.taskId === 'string' && !existingTaskIds.has(row.taskId) && !reservedOrphan.upstreamTaskIds.has(row.taskId),
616
- );
617
- const orphanTaskIds = orphanRows.map((row) => row.taskId);
618
-
619
- const archivedSessionIds = [];
620
- const archivedSet = new Set();
621
- const removedWorktreePaths = [];
622
- const removedWorktreeSet = new Set();
623
- const removedWorkspaceIds = [];
624
- const removedWorkspaceSet = new Set();
625
-
626
- for (const row of orphanRows) {
627
- const facts = extractTaskFacts(null, row);
628
- if (facts.sourcePath !== null) knownSourcePaths.add(facts.sourcePath);
629
-
630
- if (options.archiveSessions && facts.sessionId !== null) {
631
- if (!activeSessionIds.has(facts.sessionId) && !archivedSet.has(facts.sessionId)) {
632
- archivedSet.add(facts.sessionId);
633
- archivedSessionIds.push(facts.sessionId);
634
- await tryArchiveHostSession(deps, facts.sessionId);
635
- }
636
- }
637
-
638
- if (options.removeWorktrees && facts.isolation === 'worktree') {
639
- const execKey = sessionPathKey(facts.executionPath);
640
- const sourceKey = sessionPathKey(facts.sourcePath);
641
- if (execKey !== null && execKey !== sourceKey && !activeExecKeys.has(execKey)) {
642
- let canRemoveWs = false;
643
- if (typeof deps?.worktrees?.removeManagedTree === 'function') {
644
- if (!removedWorktreeSet.has(execKey)) {
645
- const wt = await deps.worktrees.removeManagedTree({
646
- taskId: facts.taskId,
647
- sourcePath: facts.sourcePath,
648
- workspacePath: facts.executionPath,
649
- });
650
- if (wt.removed && wt.workspacePath) {
651
- removedWorktreeSet.add(execKey);
652
- removedWorktreePaths.push(wt.workspacePath);
653
- canRemoveWs = true;
654
- } else if (wt.reason === 'already-absent') {
655
- removedWorktreeSet.add(execKey);
656
- canRemoveWs = true;
657
- }
658
- } else {
659
- canRemoveWs = true;
660
- }
661
- }
662
- if (
663
- canRemoveWs
664
- && facts.workspaceId !== null
665
- && !activeWorkspaceIds.has(facts.workspaceId)
666
- && !removedWorkspaceSet.has(facts.workspaceId)
667
- ) {
668
- removedWorkspaceSet.add(facts.workspaceId);
669
- removedWorkspaceIds.push(facts.workspaceId);
670
- await tryDeleteHostWorkspace(deps, facts.workspaceId);
671
- }
672
- }
673
- }
674
- }
675
-
676
- if (options.archiveSessions && orphanTaskIds.length > 0) {
677
- if (typeof deps?.sessionStore?.forgetMany === 'function') {
678
- await deps.sessionStore.forgetMany(orphanTaskIds).catch(() => []);
679
- } else if (typeof deps?.sessionStore?.forget === 'function') {
680
- for (const id of orphanTaskIds) {
681
- await deps.sessionStore.forget(id).catch(() => false);
682
- }
683
- }
684
- }
685
-
686
- if (options.removeWorktrees && typeof deps?.worktrees?.sweepOrphanTrees === 'function') {
687
- try {
688
- const swept = await deps.worktrees.sweepOrphanTrees({
689
- activePaths: activeExecPaths,
690
- sourcePaths: [...knownSourcePaths],
691
- });
692
- for (const wtPath of Array.isArray(swept?.removedWorktreePaths) ? swept.removedWorktreePaths : []) {
693
- const key = sessionPathKey(wtPath);
694
- if (key !== null && !removedWorktreeSet.has(key)) {
695
- removedWorktreeSet.add(key);
696
- removedWorktreePaths.push(wtPath);
697
- }
698
- }
699
- } catch {
700
- // Best-effort disk sweep.
701
- }
702
- }
703
-
704
- return {
705
- orphanSessionsForgotten: options.archiveSessions ? orphanTaskIds.length : 0,
706
- cleaned: {
707
- archivedSessionIds,
708
- removedWorktreePaths,
709
- removedWorkspaceIds,
710
- },
711
- retained: {
712
- sourceFiles: true,
713
- },
714
- };
715
- }
1
+ import { buildTaskTree } from './task-tree.js';
2
+ import { HISTORY_CODES, HISTORY_DELETE_MAX_TASKS } from './history.js';
3
+ import { sessionPathKey } from '../runtime/session-placement.js';
4
+
5
+ export const MAX_CLEANUP_CHAINS = 100;
6
+ const FINISHED = new Set(['awaiting-host-review', 'failed', 'cancelled', 'interrupted']);
7
+ const ALLOWED_CLEANUP_KEYS = new Set(['chains', 'confirm', 'archiveSessions', 'removeWorktrees', 'cleanPlans']);
8
+ const ALLOWED_ORPHAN_KEYS = new Set(['confirm', 'archiveSessions', 'removeWorktrees']);
9
+
10
+ export const CLEANUP_CODES = Object.freeze({
11
+ invalid: 'CLEANUP_INVALID',
12
+ notFound: 'CLEANUP_CHAIN_NOT_FOUND',
13
+ stale: 'CLEANUP_STALE',
14
+ live: 'CLEANUP_CHAIN_LIVE',
15
+ notDurable: 'CLEANUP_NOT_DURABLE',
16
+ nextRound: 'CLEANUP_NEXT_ROUND',
17
+ planChildren: 'CLEANUP_PLAN_CHILDREN',
18
+ hierarchyChildren: 'CLEANUP_HIERARCHY_CHILDREN',
19
+ reviewWrite: 'CLEANUP_REVIEW_WRITE',
20
+ unavailable: 'CLEANUP_UNAVAILABLE',
21
+ failed: 'CLEANUP_FAILED',
22
+ });
23
+
24
+ class CleanupError extends Error {
25
+ constructor(code, message, details = {}) {
26
+ super(message);
27
+ this.name = 'CleanupError';
28
+ this.code = code;
29
+ this.details = details;
30
+ }
31
+ }
32
+
33
+ function invalid(message, details) {
34
+ throw new CleanupError(CLEANUP_CODES.invalid, message, details);
35
+ }
36
+
37
+ function isObject(value) {
38
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
39
+ }
40
+
41
+ function isId(value) {
42
+ return typeof value === 'string' && value.length > 0 && value.length <= 256 && value.trim() === value;
43
+ }
44
+
45
+ export function validateCleanupRequest(body) {
46
+ if (!isObject(body) || Object.keys(body).some((key) => !ALLOWED_CLEANUP_KEYS.has(key))) {
47
+ invalid('expected only chains and explicit confirmation');
48
+ }
49
+ if (body.confirm !== true) invalid('cleanup requires explicit confirmation', { field: 'confirm' });
50
+ for (const flag of ['archiveSessions', 'removeWorktrees', 'cleanPlans']) {
51
+ if (body[flag] !== undefined && typeof body[flag] !== 'boolean') {
52
+ invalid(`${flag} must be a boolean`, { field: flag });
53
+ }
54
+ }
55
+ if (!Array.isArray(body.chains) || body.chains.length === 0 || body.chains.length > MAX_CLEANUP_CHAINS) {
56
+ invalid('select a bounded list of execution chains', { field: 'chains', limit: MAX_CLEANUP_CHAINS });
57
+ }
58
+ const chainIds = new Set();
59
+ const taskIds = new Set();
60
+ const chains = body.chains.map((chain, index) => {
61
+ if (!isObject(chain) || Object.keys(chain).some((key) => key !== 'chainId' && key !== 'taskIds') || !isId(chain.chainId)) {
62
+ invalid('expected a chain id and its exact rounds', { index });
63
+ }
64
+ if (chainIds.has(chain.chainId)) invalid('duplicate chain id', { index });
65
+ chainIds.add(chain.chainId);
66
+ if (!Array.isArray(chain.taskIds) || chain.taskIds.length === 0) invalid('select the complete chain', { index });
67
+ for (const id of chain.taskIds) {
68
+ if (!isId(id) || taskIds.has(id)) invalid('expected unique task ids', { index });
69
+ taskIds.add(id);
70
+ if (taskIds.size > HISTORY_DELETE_MAX_TASKS) invalid('too many rounds for one batch', { limit: HISTORY_DELETE_MAX_TASKS });
71
+ }
72
+ return { chainId: chain.chainId, taskIds: [...chain.taskIds] };
73
+ });
74
+ return {
75
+ chains,
76
+ options: {
77
+ archiveSessions: body.archiveSessions === true,
78
+ removeWorktrees: body.removeWorktrees === true,
79
+ cleanPlans: body.cleanPlans === true,
80
+ },
81
+ };
82
+ }
83
+
84
+ function planStore(deps) {
85
+ return deps.plans ?? deps.engine?.plans ?? null;
86
+ }
87
+
88
+ function collectChains(node, byChain) {
89
+ for (const chain of node.chain ? [node.chain] : node.executions ?? []) byChain.set(chain.chainId, chain);
90
+ for (const child of node.children) collectChains(child, byChain);
91
+ }
92
+
93
+ function cleanupContext(engine, archived, plans) {
94
+ const live = engine?.list?.() ?? [];
95
+ const liveById = new Map(live.map((row) => [row.taskId, row]));
96
+ const archivedById = new Map(archived.map((row) => [row.taskId, row]));
97
+ const tasks = new Map([...archivedById, ...liveById]);
98
+ const continuations = new Map();
99
+ const taskChildren = new Map();
100
+ const liveReuseChildren = new Map();
101
+ const planParents = new Set(plans.map((node) => node.parentNodeId));
102
+ const remember = (map, parent, child) => {
103
+ if (typeof parent !== 'string' || parent === '' || parent === child) return;
104
+ if (!map.has(parent)) map.set(parent, new Set());
105
+ map.get(parent).add(child);
106
+ };
107
+ for (const row of [...archived, ...live]) {
108
+ remember(continuations, row.continueFromTaskId, row.taskId);
109
+ remember(taskChildren, row.parentNodeId, row.taskId);
110
+ remember(taskChildren, row.planNodeId, row.taskId);
111
+ }
112
+ for (const row of tasks.values()) {
113
+ if (!FINISHED.has(row.state)) {
114
+ remember(liveReuseChildren, row.reuseWorktreeFromTaskId, row.taskId);
115
+ }
116
+ }
117
+ const tree = buildTaskTree({ planNodes: plans, tasks: [...tasks.values()] });
118
+ const byChain = new Map();
119
+ for (const root of tree.roots) collectChains(root, byChain);
120
+ return { byChain, liveById, archivedById, continuations, taskChildren, liveReuseChildren, planParents, engine };
121
+ }
122
+
123
+ function blockersFor(chain, context) {
124
+ const blockers = new Set();
125
+ const members = new Set(chain.taskIds);
126
+ for (const taskId of members) {
127
+ const live = context.liveById.get(taskId);
128
+ const archived = context.archivedById.get(taskId);
129
+ if ((live && !FINISHED.has(live.state)) || (archived && !FINISHED.has(archived.state))) {
130
+ blockers.add(CLEANUP_CODES.live);
131
+ } else if (!archived || (live && !context.engine.isTaskSettledForCleanup?.(taskId))) {
132
+ blockers.add(CLEANUP_CODES.notDurable);
133
+ }
134
+ if (context.engine?.reviewWriteDone?.(taskId)) blockers.add(CLEANUP_CODES.reviewWrite);
135
+ for (const child of context.continuations.get(taskId) ?? []) {
136
+ if (!members.has(child)) blockers.add(CLEANUP_CODES.nextRound);
137
+ }
138
+ for (const child of context.taskChildren.get(taskId) ?? []) {
139
+ if (!members.has(child)) blockers.add(CLEANUP_CODES.hierarchyChildren);
140
+ }
141
+ for (const child of context.liveReuseChildren.get(taskId) ?? []) {
142
+ if (!members.has(child)) blockers.add(CLEANUP_CODES.hierarchyChildren);
143
+ }
144
+ if (context.planParents.has(taskId)) blockers.add(CLEANUP_CODES.planChildren);
145
+ }
146
+ return [...blockers];
147
+ }
148
+
149
+ export async function cleanupOverview(deps) {
150
+ const archived = await deps.history.load();
151
+ const plans = await planStore(deps)?.load() ?? [];
152
+ const context = cleanupContext(deps.engine, archived, plans);
153
+ const chains = [...context.byChain.values()].map((chain) => {
154
+ const blockers = blockersFor(chain, context);
155
+ return { chainId: chain.chainId, taskIds: [...chain.taskIds], eligible: blockers.length === 0, blockers };
156
+ });
157
+ return { chains };
158
+ }
159
+
160
+ function checkBatch(chains, context) {
161
+ const refused = [];
162
+ for (const { chainId, taskIds } of chains) {
163
+ const chain = context.byChain.get(chainId);
164
+ let blockers;
165
+ if (!chain) blockers = [CLEANUP_CODES.notFound];
166
+ else if (chain.taskIds.length !== taskIds.length || chain.taskIds.some((id, i) => id !== taskIds[i])) {
167
+ blockers = [CLEANUP_CODES.stale];
168
+ } else blockers = blockersFor(chain, context);
169
+ if (blockers.length) refused.push({ chainId, code: blockers[0], blockers });
170
+ }
171
+ if (refused.length) {
172
+ throw new CleanupError(refused[0].code, 'the selected chains cannot be removed as one batch', {
173
+ chains: refused, reason: refused[0].code, deleted: 0,
174
+ });
175
+ }
176
+ }
177
+
178
+ export async function runCleanup(deps, body) {
179
+ const { chains, options } = validateCleanupRequest(body);
180
+ const store = deps.history;
181
+ const plans = planStore(deps);
182
+ const engine = deps.engine;
183
+ if (typeof store?.deleteMany !== 'function' || (plans && typeof plans.withStableNodes !== 'function')) {
184
+ throw new CleanupError(CLEANUP_CODES.unavailable, 'task record cleanup is unavailable');
185
+ }
186
+ const ids = chains.flatMap((chain) => chain.taskIds);
187
+ const idsSet = new Set(ids);
188
+ let deletedRowsSnapshot = [];
189
+ let remainingRowsSnapshot = [];
190
+ const deleteRecords = async (planNodes) => {
191
+ let release;
192
+ try {
193
+ return await store.deleteMany(ids, {
194
+ beforeWrite(archived) {
195
+ // Read the latest engine state inside the history queue. No asynchronous
196
+ // work may run between checking relationships and reserving these ids.
197
+ const context = cleanupContext(engine, archived, planNodes);
198
+ checkBatch(chains, context);
199
+ const allTasks = new Map([...context.archivedById, ...context.liveById]);
200
+ deletedRowsSnapshot = ids.map((id) => allTasks.get(id)).filter(Boolean);
201
+ remainingRowsSnapshot = [...allTasks.values()].filter((row) => !idsSet.has(row.taskId));
202
+ release = engine?.reserveCleanupIds(ids);
203
+ },
204
+ afterWrite(deletedIds) {
205
+ engine?.forgetCleanedRecords(deletedIds);
206
+ },
207
+ });
208
+ } finally {
209
+ release?.();
210
+ }
211
+ };
212
+ let result;
213
+ try {
214
+ result = plans ? await plans.withStableNodes(deleteRecords) : await deleteRecords([]);
215
+ } catch (error) {
216
+ if (error instanceof CleanupError) throw error;
217
+ const code = error?.code === HISTORY_CODES.deleteInvalid ? CLEANUP_CODES.stale
218
+ : error?.code === HISTORY_CODES.writeFailed ? CLEANUP_CODES.failed : CLEANUP_CODES.unavailable;
219
+ throw new CleanupError(code, 'the task records could not be removed', { deleted: 0 });
220
+ }
221
+
222
+ const hasLinkedCleanup = options.archiveSessions || options.removeWorktrees || options.cleanPlans;
223
+ if (!hasLinkedCleanup) {
224
+ return {
225
+ chains: chains.length,
226
+ tasks: result.deletedTaskIds.length,
227
+ ...result,
228
+ retained: { sessions: true, workspaces: true, worktrees: true, sourceFiles: true, plans: true },
229
+ };
230
+ }
231
+
232
+ const linked = await performLinkedCleanup(deps, {
233
+ options,
234
+ deletedTaskIds: result.deletedTaskIds,
235
+ deletedRows: deletedRowsSnapshot,
236
+ remainingRows: remainingRowsSnapshot,
237
+ plans,
238
+ });
239
+
240
+ return {
241
+ chains: chains.length,
242
+ tasks: result.deletedTaskIds.length,
243
+ ...result,
244
+ retained: {
245
+ sessions: !options.archiveSessions,
246
+ workspaces: !options.removeWorktrees,
247
+ worktrees: !options.removeWorktrees,
248
+ sourceFiles: true,
249
+ plans: !options.cleanPlans,
250
+ },
251
+ cleaned: linked,
252
+ };
253
+ }
254
+
255
+ function firstNonEmpty(...values) {
256
+ for (const val of values) {
257
+ if (typeof val === 'string' && val.trim() !== '') return val.trim();
258
+ }
259
+ return null;
260
+ }
261
+
262
+ function extractTaskFacts(row, sessionRow = null) {
263
+ const isolation = firstNonEmpty(
264
+ row?.isolation,
265
+ row?.effective?.worker?.isolation,
266
+ sessionRow?.isolation,
267
+ );
268
+ const sourcePath = firstNonEmpty(
269
+ sessionRow?.sourcePath,
270
+ row?.sourcePath,
271
+ row?.execution?.sourcePath,
272
+ row?.conversation?.sourcePath,
273
+ );
274
+ const executionPath = firstNonEmpty(
275
+ sessionRow?.executionPath,
276
+ row?.executionWorkspacePath,
277
+ row?.worktree?.workspacePath,
278
+ row?.execution?.workspacePath,
279
+ row?.workspacePath,
280
+ );
281
+ const workspaceId = firstNonEmpty(
282
+ sessionRow?.workspaceId,
283
+ row?.workspaceId,
284
+ row?.execution?.workspaceId,
285
+ row?.execution?.conversation?.workspaceId,
286
+ row?.conversation?.workspaceId,
287
+ );
288
+ const sessionId = firstNonEmpty(
289
+ sessionRow?.sessionId,
290
+ row?.sessionId,
291
+ row?.execution?.sessionId,
292
+ row?.execution?.conversation?.sessionId,
293
+ row?.conversation?.sessionId,
294
+ );
295
+ return {
296
+ taskId: firstNonEmpty(row?.taskId, sessionRow?.taskId),
297
+ isolation,
298
+ sourcePath,
299
+ executionPath,
300
+ workspaceId,
301
+ sessionId,
302
+ planNodeId: firstNonEmpty(row?.planNodeId),
303
+ parentNodeId: firstNonEmpty(row?.parentNodeId),
304
+ };
305
+ }
306
+
307
+ function resolveController(serviceOrAccessor) {
308
+ if (serviceOrAccessor === null || serviceOrAccessor === undefined) return null;
309
+ if (typeof serviceOrAccessor === 'object' && 'current' in serviceOrAccessor) {
310
+ return serviceOrAccessor.current ?? null;
311
+ }
312
+ return serviceOrAccessor;
313
+ }
314
+
315
+ async function tryArchiveHostSession(deps, sessionId) {
316
+ const ws = resolveController(deps?.workspaces);
317
+ if (typeof ws?.archiveSession === 'function') {
318
+ try {
319
+ await ws.archiveSession(sessionId);
320
+ return true;
321
+ } catch {
322
+ try {
323
+ await ws.archiveSession({ sessionId });
324
+ return true;
325
+ } catch {
326
+ // Ignore host controller error; browser client also reconciles via client workspaces service.
327
+ }
328
+ }
329
+ }
330
+ const sc = resolveController(deps?.sessionController);
331
+ if (typeof sc?.archiveSession === 'function') {
332
+ try {
333
+ await sc.archiveSession(sessionId);
334
+ return true;
335
+ } catch {
336
+ // Ignore
337
+ }
338
+ }
339
+ return false;
340
+ }
341
+
342
+ async function tryDeleteHostWorkspace(deps, workspaceId) {
343
+ const ws = resolveController(deps?.workspaces);
344
+ if (typeof ws?.delete === 'function') {
345
+ try {
346
+ await ws.delete(workspaceId);
347
+ return true;
348
+ } catch {
349
+ try {
350
+ await ws.delete({ workspaceId });
351
+ return true;
352
+ } catch {
353
+ // Ignore
354
+ }
355
+ }
356
+ }
357
+ return false;
358
+ }
359
+
360
+ function collectReservedReuseRefs(rows, knownRowsById, sessionByTask, engine) {
361
+ const paths = [];
362
+ const sessionIds = [];
363
+ const workspaceIds = [];
364
+ const upstreamTaskIds = new Set();
365
+ if (typeof engine?.reservedWorktreePathsForCleanup === 'function') {
366
+ for (const candidate of engine.reservedWorktreePathsForCleanup()) {
367
+ if (typeof candidate === 'string' && candidate.trim() !== '') paths.push(candidate.trim());
368
+ }
369
+ }
370
+ if (typeof engine?.reservedContinuationRefsForCleanup === 'function') {
371
+ const refs = engine.reservedContinuationRefsForCleanup();
372
+ for (const id of Array.isArray(refs?.sessionIds) ? refs.sessionIds : []) {
373
+ if (typeof id === 'string' && id.trim() !== '') sessionIds.push(id.trim());
374
+ }
375
+ for (const id of Array.isArray(refs?.workspaceIds) ? refs.workspaceIds : []) {
376
+ if (typeof id === 'string' && id.trim() !== '') workspaceIds.push(id.trim());
377
+ }
378
+ }
379
+ for (const row of rows) {
380
+ if (FINISHED.has(row?.state)) continue;
381
+ const reuseId = firstNonEmpty(row?.reuseWorktreeFromTaskId);
382
+ const contId = firstNonEmpty(row?.continueFromTaskId);
383
+ const upstreamId = firstNonEmpty(reuseId, contId);
384
+ if (upstreamId === null) continue;
385
+ upstreamTaskIds.add(upstreamId);
386
+ const upstreamFacts = extractTaskFacts(knownRowsById.get(upstreamId) ?? null, sessionByTask.get(upstreamId) ?? null);
387
+ if (upstreamFacts.executionPath !== null) {
388
+ const execKey = sessionPathKey(upstreamFacts.executionPath);
389
+ const sourceKey = sessionPathKey(upstreamFacts.sourcePath);
390
+ if (execKey !== null && execKey !== sourceKey) paths.push(upstreamFacts.executionPath);
391
+ }
392
+ if (upstreamFacts.workspaceId !== null) workspaceIds.push(upstreamFacts.workspaceId);
393
+ if (contId !== null && upstreamFacts.sessionId !== null) sessionIds.push(upstreamFacts.sessionId);
394
+ }
395
+ return { paths, sessionIds, workspaceIds, upstreamTaskIds };
396
+ }
397
+
398
+ async function performLinkedCleanup(deps, { options, deletedTaskIds, deletedRows, remainingRows, plans }) {
399
+ const deletedSet = new Set(deletedTaskIds);
400
+ let sessionRows = [];
401
+ if (typeof deps?.sessionStore?.list === 'function') {
402
+ try {
403
+ sessionRows = await deps.sessionStore.list();
404
+ } catch {
405
+ sessionRows = [];
406
+ }
407
+ }
408
+ const sessionByTask = new Map(sessionRows.map((row) => [row.taskId, row]));
409
+ const knownRowsById = new Map(
410
+ [...deletedRows, ...remainingRows]
411
+ .filter((row) => typeof row?.taskId === 'string' && row.taskId !== '')
412
+ .map((row) => [row.taskId, row]),
413
+ );
414
+
415
+ const activeSessionIds = new Set();
416
+ const activeWorkspaceIds = new Set();
417
+ const activeExecKeys = new Set();
418
+ for (const row of remainingRows) {
419
+ const facts = extractTaskFacts(row, sessionByTask.get(row.taskId));
420
+ if (facts.sessionId !== null) activeSessionIds.add(facts.sessionId);
421
+ if (facts.workspaceId !== null) activeWorkspaceIds.add(facts.workspaceId);
422
+ const execKey = sessionPathKey(facts.executionPath);
423
+ if (execKey !== null) activeExecKeys.add(execKey);
424
+ }
425
+ const reservedLinked = collectReservedReuseRefs(remainingRows, knownRowsById, sessionByTask, deps?.engine);
426
+ for (const sid of reservedLinked.sessionIds) activeSessionIds.add(sid);
427
+ for (const wid of reservedLinked.workspaceIds) activeWorkspaceIds.add(wid);
428
+ for (const reservedPath of reservedLinked.paths) {
429
+ const reservedKey = sessionPathKey(reservedPath);
430
+ if (reservedKey !== null) activeExecKeys.add(reservedKey);
431
+ }
432
+
433
+ const deletedFacts = deletedTaskIds.map((taskId) => {
434
+ const row = deletedRows.find((item) => item?.taskId === taskId) ?? { taskId };
435
+ return extractTaskFacts(row, sessionByTask.get(taskId));
436
+ });
437
+
438
+ const archivedSessionIds = [];
439
+ const archivedSet = new Set();
440
+ if (options.archiveSessions) {
441
+ for (const facts of deletedFacts) {
442
+ if (facts.sessionId !== null && !activeSessionIds.has(facts.sessionId) && !archivedSet.has(facts.sessionId)) {
443
+ archivedSet.add(facts.sessionId);
444
+ archivedSessionIds.push(facts.sessionId);
445
+ await tryArchiveHostSession(deps, facts.sessionId);
446
+ }
447
+ }
448
+ if (typeof deps?.sessionStore?.forgetMany === 'function') {
449
+ await deps.sessionStore.forgetMany(deletedSet).catch(() => []);
450
+ } else if (typeof deps?.sessionStore?.forget === 'function') {
451
+ for (const id of deletedSet) {
452
+ await deps.sessionStore.forget(id).catch(() => false);
453
+ }
454
+ }
455
+ }
456
+
457
+ const removedWorktreePaths = [];
458
+ const removedWorktreeSet = new Set();
459
+ const removedWorkspaceIds = [];
460
+ const removedWorkspaceSet = new Set();
461
+
462
+ if (options.removeWorktrees) {
463
+ for (const facts of deletedFacts) {
464
+ // Strictly operate ONLY on worktree-isolated tasks; never touch shared directories or shared workspaces.
465
+ if (facts.isolation !== 'worktree') continue;
466
+ const execKey = sessionPathKey(facts.executionPath);
467
+ const sourceKey = sessionPathKey(facts.sourcePath);
468
+ if (execKey === null || execKey === sourceKey || activeExecKeys.has(execKey)) continue;
469
+
470
+ let worktreeEligibleForWorkspaceRemoval = false;
471
+ if (typeof deps?.worktrees?.removeManagedTree === 'function') {
472
+ if (!removedWorktreeSet.has(execKey)) {
473
+ const outcome = await deps.worktrees.removeManagedTree({
474
+ taskId: facts.taskId,
475
+ sourcePath: facts.sourcePath,
476
+ workspacePath: facts.executionPath,
477
+ });
478
+ if (outcome.removed && outcome.workspacePath) {
479
+ removedWorktreeSet.add(execKey);
480
+ removedWorktreePaths.push(outcome.workspacePath);
481
+ worktreeEligibleForWorkspaceRemoval = true;
482
+ } else if (outcome.reason === 'already-absent') {
483
+ removedWorktreeSet.add(execKey);
484
+ worktreeEligibleForWorkspaceRemoval = true;
485
+ }
486
+ } else {
487
+ worktreeEligibleForWorkspaceRemoval = true;
488
+ }
489
+ }
490
+
491
+ if (
492
+ worktreeEligibleForWorkspaceRemoval
493
+ && facts.workspaceId !== null
494
+ && !activeWorkspaceIds.has(facts.workspaceId)
495
+ && !removedWorkspaceSet.has(facts.workspaceId)
496
+ ) {
497
+ removedWorkspaceSet.add(facts.workspaceId);
498
+ removedWorkspaceIds.push(facts.workspaceId);
499
+ await tryDeleteHostWorkspace(deps, facts.workspaceId);
500
+ }
501
+ }
502
+ }
503
+
504
+ let removedPlanNodeIds = [];
505
+ if (options.cleanPlans && typeof plans?.deleteEmptyAncestors === 'function') {
506
+ const seedPlanIds = new Set();
507
+ for (const facts of deletedFacts) {
508
+ if (facts.planNodeId !== null) seedPlanIds.add(facts.planNodeId);
509
+ if (facts.parentNodeId !== null && facts.parentNodeId.startsWith('plan-')) {
510
+ seedPlanIds.add(facts.parentNodeId);
511
+ }
512
+ }
513
+ if (seedPlanIds.size > 0) {
514
+ try {
515
+ removedPlanNodeIds = await plans.deleteEmptyAncestors(seedPlanIds, remainingRows);
516
+ } catch {
517
+ removedPlanNodeIds = [];
518
+ }
519
+ }
520
+ }
521
+
522
+ return {
523
+ archivedSessionIds,
524
+ removedWorktreePaths,
525
+ removedWorkspaceIds,
526
+ removedPlanNodeIds,
527
+ };
528
+ }
529
+
530
+ export function validateOrphanCleanupRequest(body) {
531
+ if (!isObject(body) || Object.keys(body).some((key) => !ALLOWED_ORPHAN_KEYS.has(key))) {
532
+ invalid('expected explicit confirmation for orphan cleanup');
533
+ }
534
+ if (body.confirm !== true) invalid('orphan cleanup requires explicit confirmation', { field: 'confirm' });
535
+ for (const flag of ['archiveSessions', 'removeWorktrees']) {
536
+ if (body[flag] !== undefined && typeof body[flag] !== 'boolean') {
537
+ invalid(`${flag} must be a boolean`, { field: flag });
538
+ }
539
+ }
540
+ return {
541
+ archiveSessions: body.archiveSessions !== false,
542
+ removeWorktrees: body.removeWorktrees !== false,
543
+ };
544
+ }
545
+
546
+ /**
547
+ * Sweep residual worktrees and dispatched session identities whose task records
548
+ * were already deleted or rotated out of `history.json`.
549
+ *
550
+ * Strictly preserves any session, workspace or directory still referenced by a live
551
+ * or retained historical task, and never touches a shared checkout or shared project
552
+ * Workspace.
553
+ * @param {object} deps - runtime dependencies.
554
+ * @param {object} body - `{ confirm: true, archiveSessions?: boolean, removeWorktrees?: boolean }`.
555
+ * @returns {Promise<object>} sweep outcome.
556
+ */
557
+ export async function runOrphanCleanup(deps, body) {
558
+ const options = validateOrphanCleanupRequest(body);
559
+ const store = deps?.history;
560
+ if (typeof store?.load !== 'function') {
561
+ throw new CleanupError(CLEANUP_CODES.unavailable, 'task history is unavailable');
562
+ }
563
+ let archived = [];
564
+ try {
565
+ archived = await store.load();
566
+ } catch {
567
+ throw new CleanupError(CLEANUP_CODES.unavailable, 'task history could not be read');
568
+ }
569
+ const live = deps?.engine?.list?.() ?? [];
570
+ const allExisting = [...archived, ...live];
571
+ const existingTaskIds = new Set(allExisting.map((row) => row?.taskId).filter(Boolean));
572
+
573
+ let sessionRows = [];
574
+ if (typeof deps?.sessionStore?.list === 'function') {
575
+ try {
576
+ sessionRows = await deps.sessionStore.list();
577
+ } catch {
578
+ sessionRows = [];
579
+ }
580
+ }
581
+ const sessionByTask = new Map(sessionRows.map((row) => [row.taskId, row]));
582
+
583
+ const activeSessionIds = new Set();
584
+ const activeWorkspaceIds = new Set();
585
+ const activeExecKeys = new Set();
586
+ const activeExecPaths = [];
587
+ const knownSourcePaths = new Set();
588
+
589
+ const knownRowsById = new Map(
590
+ allExisting
591
+ .filter((row) => typeof row?.taskId === 'string' && row.taskId !== '')
592
+ .map((row) => [row.taskId, row]),
593
+ );
594
+ for (const row of allExisting) {
595
+ const facts = extractTaskFacts(row, sessionByTask.get(row.taskId));
596
+ if (facts.sessionId !== null) activeSessionIds.add(facts.sessionId);
597
+ if (facts.workspaceId !== null) activeWorkspaceIds.add(facts.workspaceId);
598
+ if (facts.sourcePath !== null) knownSourcePaths.add(facts.sourcePath);
599
+ if (facts.executionPath !== null) {
600
+ activeExecPaths.push(facts.executionPath);
601
+ const key = sessionPathKey(facts.executionPath);
602
+ if (key !== null) activeExecKeys.add(key);
603
+ }
604
+ }
605
+ const reservedOrphan = collectReservedReuseRefs(allExisting, knownRowsById, sessionByTask, deps?.engine);
606
+ for (const sid of reservedOrphan.sessionIds) activeSessionIds.add(sid);
607
+ for (const wid of reservedOrphan.workspaceIds) activeWorkspaceIds.add(wid);
608
+ for (const reservedPath of reservedOrphan.paths) {
609
+ activeExecPaths.push(reservedPath);
610
+ const key = sessionPathKey(reservedPath);
611
+ if (key !== null) activeExecKeys.add(key);
612
+ }
613
+
614
+ const orphanRows = sessionRows.filter(
615
+ (row) => typeof row?.taskId === 'string' && !existingTaskIds.has(row.taskId) && !reservedOrphan.upstreamTaskIds.has(row.taskId),
616
+ );
617
+ const orphanTaskIds = orphanRows.map((row) => row.taskId);
618
+
619
+ const archivedSessionIds = [];
620
+ const archivedSet = new Set();
621
+ const removedWorktreePaths = [];
622
+ const removedWorktreeSet = new Set();
623
+ const removedWorkspaceIds = [];
624
+ const removedWorkspaceSet = new Set();
625
+
626
+ for (const row of orphanRows) {
627
+ const facts = extractTaskFacts(null, row);
628
+ if (facts.sourcePath !== null) knownSourcePaths.add(facts.sourcePath);
629
+
630
+ if (options.archiveSessions && facts.sessionId !== null) {
631
+ if (!activeSessionIds.has(facts.sessionId) && !archivedSet.has(facts.sessionId)) {
632
+ archivedSet.add(facts.sessionId);
633
+ archivedSessionIds.push(facts.sessionId);
634
+ await tryArchiveHostSession(deps, facts.sessionId);
635
+ }
636
+ }
637
+
638
+ if (options.removeWorktrees && facts.isolation === 'worktree') {
639
+ const execKey = sessionPathKey(facts.executionPath);
640
+ const sourceKey = sessionPathKey(facts.sourcePath);
641
+ if (execKey !== null && execKey !== sourceKey && !activeExecKeys.has(execKey)) {
642
+ let canRemoveWs = false;
643
+ if (typeof deps?.worktrees?.removeManagedTree === 'function') {
644
+ if (!removedWorktreeSet.has(execKey)) {
645
+ const wt = await deps.worktrees.removeManagedTree({
646
+ taskId: facts.taskId,
647
+ sourcePath: facts.sourcePath,
648
+ workspacePath: facts.executionPath,
649
+ });
650
+ if (wt.removed && wt.workspacePath) {
651
+ removedWorktreeSet.add(execKey);
652
+ removedWorktreePaths.push(wt.workspacePath);
653
+ canRemoveWs = true;
654
+ } else if (wt.reason === 'already-absent') {
655
+ removedWorktreeSet.add(execKey);
656
+ canRemoveWs = true;
657
+ }
658
+ } else {
659
+ canRemoveWs = true;
660
+ }
661
+ }
662
+ if (
663
+ canRemoveWs
664
+ && facts.workspaceId !== null
665
+ && !activeWorkspaceIds.has(facts.workspaceId)
666
+ && !removedWorkspaceSet.has(facts.workspaceId)
667
+ ) {
668
+ removedWorkspaceSet.add(facts.workspaceId);
669
+ removedWorkspaceIds.push(facts.workspaceId);
670
+ await tryDeleteHostWorkspace(deps, facts.workspaceId);
671
+ }
672
+ }
673
+ }
674
+ }
675
+
676
+ if (options.archiveSessions && orphanTaskIds.length > 0) {
677
+ if (typeof deps?.sessionStore?.forgetMany === 'function') {
678
+ await deps.sessionStore.forgetMany(orphanTaskIds).catch(() => []);
679
+ } else if (typeof deps?.sessionStore?.forget === 'function') {
680
+ for (const id of orphanTaskIds) {
681
+ await deps.sessionStore.forget(id).catch(() => false);
682
+ }
683
+ }
684
+ }
685
+
686
+ if (options.removeWorktrees && typeof deps?.worktrees?.sweepOrphanTrees === 'function') {
687
+ try {
688
+ const swept = await deps.worktrees.sweepOrphanTrees({
689
+ activePaths: activeExecPaths,
690
+ sourcePaths: [...knownSourcePaths],
691
+ });
692
+ for (const wtPath of Array.isArray(swept?.removedWorktreePaths) ? swept.removedWorktreePaths : []) {
693
+ const key = sessionPathKey(wtPath);
694
+ if (key !== null && !removedWorktreeSet.has(key)) {
695
+ removedWorktreeSet.add(key);
696
+ removedWorktreePaths.push(wtPath);
697
+ }
698
+ }
699
+ } catch {
700
+ // Best-effort disk sweep.
701
+ }
702
+ }
703
+
704
+ return {
705
+ orphanSessionsForgotten: options.archiveSessions ? orphanTaskIds.length : 0,
706
+ cleaned: {
707
+ archivedSessionIds,
708
+ removedWorktreePaths,
709
+ removedWorkspaceIds,
710
+ },
711
+ retained: {
712
+ sourceFiles: true,
713
+ },
714
+ };
715
+ }