@cleocode/core 2026.11.1-canary.9 → 2026.11.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.
Files changed (128) hide show
  1. package/dist/.source-stamp.json +1 -1
  2. package/dist/build-provenance.json +2 -2
  3. package/dist/config.js +2 -0
  4. package/dist/config.js.map +1 -1
  5. package/dist/doctor/db-substrate.js +14 -6
  6. package/dist/doctor/db-substrate.js.map +1 -1
  7. package/dist/doctor/migrations.d.ts +16 -0
  8. package/dist/doctor/migrations.js +85 -1
  9. package/dist/doctor/migrations.js.map +1 -1
  10. package/dist/doctor/system-health.d.ts +77 -1
  11. package/dist/doctor/system-health.js +145 -0
  12. package/dist/doctor/system-health.js.map +1 -1
  13. package/dist/errors-to-engine.d.ts +8 -4
  14. package/dist/errors-to-engine.js +9 -5
  15. package/dist/errors-to-engine.js.map +1 -1
  16. package/dist/errors.d.ts +14 -0
  17. package/dist/errors.js +10 -0
  18. package/dist/errors.js.map +1 -1
  19. package/dist/git/work-tree.js +1 -1
  20. package/dist/git/work-tree.js.map +1 -1
  21. package/dist/hygiene/census.d.ts +181 -12
  22. package/dist/hygiene/census.js +564 -86
  23. package/dist/hygiene/census.js.map +1 -1
  24. package/dist/hygiene/prune-plan-worker.d.ts +17 -0
  25. package/dist/hygiene/prune-plan-worker.js +42 -0
  26. package/dist/hygiene/prune-plan-worker.js.map +1 -0
  27. package/dist/hygiene/task-status.d.ts +20 -0
  28. package/dist/hygiene/task-status.js +71 -0
  29. package/dist/hygiene/task-status.js.map +1 -0
  30. package/dist/memory/pipeline-manifest-sqlite.d.ts +2 -1
  31. package/dist/memory/pipeline-manifest-sqlite.js +3 -2
  32. package/dist/memory/pipeline-manifest-sqlite.js.map +1 -1
  33. package/dist/orchestrate/agentmbx.d.ts +5 -2
  34. package/dist/orchestrate/agentmbx.js +7 -4
  35. package/dist/orchestrate/agentmbx.js.map +1 -1
  36. package/dist/orchestrate/dispatch-workers.d.ts +10 -3
  37. package/dist/orchestrate/dispatch-workers.js +26 -14
  38. package/dist/orchestrate/dispatch-workers.js.map +1 -1
  39. package/dist/orchestrate/lead.d.ts +3 -0
  40. package/dist/orchestrate/lead.js +1 -0
  41. package/dist/orchestrate/lead.js.map +1 -1
  42. package/dist/orchestrate/orca-execution.d.ts +151 -0
  43. package/dist/orchestrate/orca-execution.js +571 -0
  44. package/dist/orchestrate/orca-execution.js.map +1 -0
  45. package/dist/orchestrate/orca-routing.d.ts +13 -0
  46. package/dist/orchestrate/orca-routing.js +142 -0
  47. package/dist/orchestrate/orca-routing.js.map +1 -0
  48. package/dist/orchestrate/spawn-ops.d.ts +50 -20
  49. package/dist/orchestrate/spawn-ops.js +332 -86
  50. package/dist/orchestrate/spawn-ops.js.map +1 -1
  51. package/dist/orchestrate/worker-records.d.ts +97 -5
  52. package/dist/orchestrate/worker-records.js +503 -11
  53. package/dist/orchestrate/worker-records.js.map +1 -1
  54. package/dist/orchestrate/worker-report.js +1 -0
  55. package/dist/orchestrate/worker-report.js.map +1 -1
  56. package/dist/orchestration/index.d.ts +8 -2
  57. package/dist/orchestration/index.js +70 -17
  58. package/dist/orchestration/index.js.map +1 -1
  59. package/dist/orchestration/spawn-prompt.d.ts +9 -2
  60. package/dist/orchestration/spawn-prompt.js +47 -18
  61. package/dist/orchestration/spawn-prompt.js.map +1 -1
  62. package/dist/orchestration/spawn.d.ts +20 -6
  63. package/dist/orchestration/spawn.js +14 -6
  64. package/dist/orchestration/spawn.js.map +1 -1
  65. package/dist/release/ci-evidence.d.ts +55 -2
  66. package/dist/release/ci-evidence.js +161 -51
  67. package/dist/release/ci-evidence.js.map +1 -1
  68. package/dist/resources/admission-ledger.d.ts +6 -0
  69. package/dist/resources/admission-ledger.js +100 -10
  70. package/dist/resources/admission-ledger.js.map +1 -1
  71. package/dist/resources/agent-lease.d.ts +7 -0
  72. package/dist/resources/agent-lease.js +37 -4
  73. package/dist/resources/agent-lease.js.map +1 -1
  74. package/dist/resources/hook-footprint.d.ts +22 -0
  75. package/dist/resources/hook-footprint.js +49 -2
  76. package/dist/resources/hook-footprint.js.map +1 -1
  77. package/dist/resources/run-class.d.ts +9 -1
  78. package/dist/resources/run-class.js +87 -6
  79. package/dist/resources/run-class.js.map +1 -1
  80. package/dist/spawn/adapter-registry.js +5 -0
  81. package/dist/spawn/adapter-registry.js.map +1 -1
  82. package/dist/spawn/branch-integration.d.ts +4 -0
  83. package/dist/spawn/branch-integration.js +10 -1
  84. package/dist/spawn/branch-integration.js.map +1 -1
  85. package/dist/store/open-cleo-db.d.ts +17 -0
  86. package/dist/store/open-cleo-db.js +39 -0
  87. package/dist/store/open-cleo-db.js.map +1 -1
  88. package/dist/store/restore-marker.js +4 -0
  89. package/dist/store/restore-marker.js.map +1 -1
  90. package/dist/store/sqlite.d.ts +21 -0
  91. package/dist/store/sqlite.js +33 -0
  92. package/dist/store/sqlite.js.map +1 -1
  93. package/dist/store/worktree-build-guard.js +3 -0
  94. package/dist/store/worktree-build-guard.js.map +1 -1
  95. package/dist/tasks/add.js +8 -0
  96. package/dist/tasks/add.js.map +1 -1
  97. package/dist/tasks/complete.d.ts +7 -3
  98. package/dist/tasks/complete.js +5 -0
  99. package/dist/tasks/complete.js.map +1 -1
  100. package/dist/tasks/engine-wrap.d.ts +3 -1
  101. package/dist/tasks/engine-wrap.js +6 -18
  102. package/dist/tasks/engine-wrap.js.map +1 -1
  103. package/dist/tasks/merge-close.d.ts +5 -3
  104. package/dist/tasks/merge-close.js +30 -10
  105. package/dist/tasks/merge-close.js.map +1 -1
  106. package/dist/tasks/pipeline-stage.d.ts +7 -1
  107. package/dist/tasks/pipeline-stage.js +44 -0
  108. package/dist/tasks/pipeline-stage.js.map +1 -1
  109. package/dist/tasks/update.js +8 -0
  110. package/dist/tasks/update.js.map +1 -1
  111. package/dist/upgrade.d.ts +4 -0
  112. package/dist/upgrade.js +32 -0
  113. package/dist/upgrade.js.map +1 -1
  114. package/dist/worktree/in-use-probe.d.ts +19 -0
  115. package/dist/worktree/in-use-probe.js +87 -0
  116. package/dist/worktree/in-use-probe.js.map +1 -1
  117. package/dist/worktree/list.d.ts +6 -6
  118. package/dist/worktree/list.js +42 -30
  119. package/dist/worktree/list.js.map +1 -1
  120. package/dist/worktree/own-project.d.ts +32 -0
  121. package/dist/worktree/own-project.js +68 -0
  122. package/dist/worktree/own-project.js.map +1 -0
  123. package/dist/worktree/prune.d.ts +11 -1
  124. package/dist/worktree/prune.js +83 -2
  125. package/dist/worktree/prune.js.map +1 -1
  126. package/package.json +12 -12
  127. package/templates/CLEO-INJECTION.md +1 -1
  128. package/templates/CLEO-REFERENCE.md +2 -2
@@ -7,7 +7,8 @@
7
7
  * deleted ones, scratch clones) were never swept: 484 had accumulated. The
8
8
  * CI cleanup workflow ran where no worktree exists and swallowed every error.
9
9
  *
10
- * The census walks every project hash directory under the root:
10
+ * The census walks every project hash directory and every registered project's
11
+ * git worktree registry (including unadopted external worktrees):
11
12
  *
12
13
  * - a directory whose hash matches a registered project (the nexus registry)
13
14
  * is classified by that project's {@link listWorktrees}: the disposal proof
@@ -16,26 +17,39 @@
16
17
  * - a directory no registered project owns, and any directory git does not
17
18
  * list as a worktree, is reported `unknown`, report only.
18
19
  *
19
- * `--apply` removes only `redundant` worktrees of the projects it is allowed
20
- * to act on (by default the project it runs in; other projects stay report
21
- * only until the owner's plan question C is answered), each re-proved by
20
+ * The CLI reports by default. `--apply` removes only `redundant` terminal
21
+ * worktrees of the current project; foreign projects remain report-only;
22
+ * automatic completion and scheduled cleanup opt in explicitly, each re-proved by
22
23
  * `disposeWorktree` with the task's evidence. Every run writes one census
23
24
  * record (counts, apparent bytes, bytes reclaimed, the free-space delta and
24
25
  * every kept worktree with its reason) under `<cleoHome>/hygiene/census/`.
25
26
  *
26
27
  * One census runs at a time per machine (a heartbeat lock), and the lazy spawn
27
- * claims at most one run per 24 h; it never starts in CI, under vitest, or in
28
+ * claims at most one run per project per 24 h; it never starts in CI, under vitest, or in
28
29
  * a process git started (T14189).
29
30
  *
31
+ * Every row also carries the visibility fields the machine-hygiene epic needs
32
+ * (T14440): the owning task's status, last activity and creation time, git and
33
+ * task locks, the dirty-entry count, and the `node_modules` kind and size.
34
+ * Per project the record rolls up worktree counts, bytes and merged local and
35
+ * remote branches, and names why each project's store was or was not read;
36
+ * machine-wide it names the orphan hash directories and the global pnpm
37
+ * store's size.
38
+ *
30
39
  * @task T14275
40
+ * @task T14440
31
41
  */
32
- import { spawn } from 'node:child_process';
42
+ import { execFileSync, spawn } from 'node:child_process';
33
43
  import { appendFileSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statfsSync, statSync, writeFileSync, } from 'node:fs';
34
- import { setPriority } from 'node:os';
35
- import { join, resolve } from 'node:path';
44
+ import { homedir, setPriority } from 'node:os';
45
+ import { dirname, join, resolve } from 'node:path';
46
+ import { fileURLToPath } from 'node:url';
47
+ import { Worker } from 'node:worker_threads';
36
48
  import { computeProjectHash, getCleoHome, getCleoWorktreesRoot } from '@cleocode/paths';
49
+ import { gitDefaultBranchRefs } from '../git/work-tree.js';
37
50
  import { acquireHeartbeatLock, claimAtMostEvery } from '../tasks/merge-close.js';
38
- /** The lazy census runs at most this often per machine. */
51
+ import { appendWorktreeAuditEntry, resolveWorktreeAuditActor } from '../worktree/audit.js';
52
+ /** The lazy census runs at most this often per project. */
39
53
  export const CENSUS_INTERVAL_MS = 24 * 60 * 60 * 1000;
40
54
  /** A census lock whose heartbeat is older than this is stale. */
41
55
  const CENSUS_LOCK_STALE_MS = 10 * 60 * 1000;
@@ -90,15 +104,17 @@ function canonical(path) {
90
104
  * Registered project roots from the nexus registry; `[]` when it cannot be read.
91
105
  *
92
106
  * @param load - The registry listing (default: `nexusList`; tests stub it).
107
+ * @param onError - Capture missing registry coverage in the census receipt.
93
108
  * @returns Each registered project's path.
94
109
  * @internal Exported for tests.
95
110
  */
96
- export async function registeredProjects(load) {
111
+ export async function registeredProjects(load, onError) {
97
112
  try {
98
113
  const list = load ?? (await import('../nexus/registry.js')).nexusList;
99
114
  return (await list()).map((p) => p.path);
100
115
  }
101
- catch {
116
+ catch (err) {
117
+ onError?.(err instanceof Error ? err.message : String(err));
102
118
  return [];
103
119
  }
104
120
  }
@@ -110,6 +126,12 @@ export async function registeredProjects(load) {
110
126
  * @task T14275
111
127
  */
112
128
  export async function runWorktreeCensus(opts = {}) {
129
+ for (const value of [opts.ttlDays, opts.maxBytes]) {
130
+ if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
131
+ // @sync-invariant none:input-shape invalid local retention limits cannot select worktrees
132
+ throw new RangeError('Worktree TTL and size budget must be finite, non-negative numbers.');
133
+ }
134
+ }
113
135
  const dir = opts.recordDir ?? censusDir();
114
136
  mkdirSync(dir, { recursive: true });
115
137
  const release = acquireHeartbeatLock(join(dir, 'census.lock'), CENSUS_LOCK_STALE_MS);
@@ -139,27 +161,146 @@ function writeRecord(dir, record) {
139
161
  /** The census proper: classify, optionally apply, and build the record. */
140
162
  async function census(opts) {
141
163
  // Lazy: the CLI imports this module on read commands to claim the daily run.
142
- const { listWorktrees } = await import('../worktree/list.js');
143
- const { worktreeInUseProbe } = await import('../worktree/in-use-probe.js');
164
+ const { classifyStatus, isPrimaryWorktree, listWorktrees, loadOwningTaskStatuses, resolvePrimaryWorktreePath, } = await import('../worktree/list.js');
165
+ const { worktreeReaperInUseProbe } = await import('../worktree/in-use-probe.js');
144
166
  const { loadTaskEvidence } = await import('../worktree/prune.js');
167
+ const { disposeWorktree, readWorktreeTaskLock } = await import('@cleocode/worktree');
168
+ const { isOwnProjectStore } = await import('../worktree/own-project.js');
169
+ const { loadCensusTaskStatuses } = await import('./task-status.js');
145
170
  const startedAt = new Date().toISOString();
146
171
  const machineRoot = opts.machineRoot ?? getCleoWorktreesRoot();
147
172
  const apply = opts.apply === true;
148
173
  const applyProjects = new Set((opts.applyProjects ?? []).map(canonical));
174
+ const ttlDays = opts.ttlDays ?? 0;
175
+ const maxBytes = opts.maxBytes ?? 0;
149
176
  const deadline = opts.deadline ?? Number.POSITIVE_INFINITY;
150
177
  let partial = false;
178
+ const projectErrors = [];
151
179
  const outOfTime = () => {
152
- if (Date.now() > deadline)
180
+ const expired = Date.now() > deadline;
181
+ if (expired)
153
182
  partial = true;
154
- return partial;
183
+ return expired;
155
184
  };
156
- const projects = opts.projects ?? (await registeredProjects());
185
+ const projects = [
186
+ ...new Set((opts.projects ??
187
+ (await registeredProjects(undefined, (error) => {
188
+ partial = true;
189
+ projectErrors.push({ project: 'registry', error });
190
+ }))).map(canonical)),
191
+ ];
192
+ if (opts.allProjects === true)
193
+ for (const project of projects)
194
+ applyProjects.add(project);
157
195
  const projectByHash = new Map();
158
196
  for (const p of projects)
159
197
  if (existsSync(p))
160
198
  projectByHash.set(computeProjectHash(p), canonical(p));
161
199
  const rows = [];
162
200
  const meta = new Map();
201
+ const statusReadByProject = new Map();
202
+ const seen = new Set();
203
+ // Git's registry covers adopted AND unadopted external worktrees, including
204
+ // projects that have never had a canonical hash directory on this machine.
205
+ for (const project of projects) {
206
+ if (outOfTime())
207
+ break;
208
+ if (!existsSync(project)) {
209
+ partial = true;
210
+ projectErrors.push({ project, error: 'registered project path is unavailable' });
211
+ continue;
212
+ }
213
+ const own = isOwnProjectStore(project);
214
+ const result = await listWorktrees({
215
+ projectRoot: project,
216
+ exemptRegenerable: opts.exemptRegenerable === true,
217
+ }, own);
218
+ if (!result.success) {
219
+ partial = true;
220
+ projectErrors.push({ project, error: result.error.message });
221
+ continue;
222
+ }
223
+ const taskIds = [
224
+ ...new Set(result.data.worktrees.flatMap((w) => (w.taskId === null ? [] : [w.taskId]))),
225
+ ];
226
+ const statuses = await loadCensusTaskStatuses(taskIds, project, own);
227
+ statusReadByProject.set(project, statuses.success
228
+ ? own
229
+ ? 'read'
230
+ : 'snapshot: may lag uncommitted writes'
231
+ : `status unknown: ${statuses.error.message}`);
232
+ const primary = resolvePrimaryWorktreePath(project);
233
+ for (const worktree of result.data.worktrees) {
234
+ if (outOfTime())
235
+ break;
236
+ const path = canonical(worktree.path);
237
+ if (isPrimaryWorktree(path, primary) || path === project || seen.has(path))
238
+ continue;
239
+ seen.add(path);
240
+ // T14440 (round 7): a FOREIGN project's row never reaches the reaper's
241
+ // probe, disposal or any store-opening liveness code — its liveness is
242
+ // 'unknown (foreign project)' and it is never a removal candidate. Own
243
+ // rows keep main's behaviour exactly.
244
+ worktree.owningTaskStatus = statuses.success
245
+ ? (statuses.data.get(worktree.taskId ?? '') ?? null)
246
+ : null;
247
+ const terminal = own &&
248
+ worktree.taskId !== null &&
249
+ (worktree.owningTaskStatus === 'done' || worktree.owningTaskStatus === 'cancelled');
250
+ const classified = !own
251
+ ? { statusCategory: 'unknown', keepReason: 'unknown (foreign project)' }
252
+ : terminal && worktree.taskId !== null
253
+ ? classifyStatus(disposeWorktree({
254
+ worktreePath: path,
255
+ projectRoot: project,
256
+ taskId: worktree.taskId,
257
+ reason: 'census',
258
+ dryRun: true,
259
+ evidence: await loadTaskEvidence(project, worktree.taskId),
260
+ exemptRegenerable: opts.exemptRegenerable === true && worktree.isMerged,
261
+ inUse: await worktreeReaperInUseProbe(project, worktree.taskId, path),
262
+ }))
263
+ : { statusCategory: worktree.statusCategory, keepReason: worktree.keepReason };
264
+ const rowProjectHash = computeProjectHash(project);
265
+ const nm = classifyNodeModules(path);
266
+ const row = {
267
+ project,
268
+ projectHash: rowProjectHash,
269
+ path,
270
+ taskId: worktree.taskId,
271
+ category: classified.statusCategory,
272
+ ...(classified.keepReason !== undefined ? { keepReason: classified.keepReason } : {}),
273
+ apparentBytes: apparentBytes(path, deadline),
274
+ branch: worktree.branch,
275
+ lastActivity: worktree.lastActivity,
276
+ taskStatus: worktree.owningTaskStatus,
277
+ // T14440 visibility fields, off the classifier and the filesystem.
278
+ createdAt: worktree.createdAt ?? null,
279
+ gitLocked: worktree.lockState === 'locked',
280
+ taskLocked: readTaskLockSafe(readWorktreeTaskLock, rowProjectHash, worktree.taskId),
281
+ dirtyFiles: dirtyFileCount(path, deadline),
282
+ nodeModules: nm,
283
+ nodeModulesBytes: nm === 'real' ? apparentBytes(join(path, 'node_modules'), deadline) : 0,
284
+ };
285
+ // A known task id without readable task state is not a taskless orphan.
286
+ if (row.taskStatus === null && (row.taskId !== null || row.category === 'redundant')) {
287
+ row.category = 'unknown';
288
+ row.keepReason =
289
+ row.taskId === null
290
+ ? 'task ownership unavailable (report only)'
291
+ : 'owning task state unavailable (report only)';
292
+ }
293
+ // Round 7: the foreign liveness label wins over the null-status
294
+ // relabel above — the snapshot could not see the WAL, which is exactly
295
+ // why the row is not a candidate.
296
+ if (!own) {
297
+ row.category = 'unknown';
298
+ row.keepReason = 'unknown (foreign project)';
299
+ }
300
+ rows.push(row);
301
+ meta.set(row, worktree);
302
+ }
303
+ }
163
304
  let hashes = [];
164
305
  try {
165
306
  hashes = readdirSync(machineRoot).filter((h) => lstatSync(join(machineRoot, h)).isDirectory());
@@ -172,20 +313,6 @@ async function census(opts) {
172
313
  break;
173
314
  const hashDir = join(machineRoot, projectHash);
174
315
  const project = projectByHash.get(projectHash) ?? null;
175
- const listed = new Map();
176
- if (project !== null) {
177
- const result = await listWorktrees({ projectRoot: project });
178
- if (result.success) {
179
- for (const w of result.data.worktrees) {
180
- listed.set(canonical(w.path), {
181
- category: w.statusCategory,
182
- ...(w.keepReason !== undefined ? { keepReason: w.keepReason } : {}),
183
- taskId: w.taskId,
184
- isMerged: w.isMerged,
185
- });
186
- }
187
- }
188
- }
189
316
  let children = [];
190
317
  try {
191
318
  children = readdirSync(hashDir).filter((n) => lstatSync(join(hashDir, n)).isDirectory());
@@ -197,62 +324,89 @@ async function census(opts) {
197
324
  if (outOfTime())
198
325
  break;
199
326
  const path = join(hashDir, name);
200
- const hit = listed.get(canonical(path));
201
- const row = hit
202
- ? {
203
- project,
204
- projectHash,
205
- path,
206
- taskId: hit.taskId,
207
- category: hit.category,
208
- ...(hit.keepReason !== undefined ? { keepReason: hit.keepReason } : {}),
209
- apparentBytes: apparentBytes(path, deadline),
210
- }
211
- : {
212
- project,
213
- projectHash,
214
- path,
215
- taskId: null,
216
- category: 'unknown',
217
- keepReason: project === null
218
- ? 'no registered project owns this hash directory (report only)'
219
- : 'git does not list this directory as a worktree of its project (report only)',
220
- apparentBytes: apparentBytes(path, deadline),
221
- };
327
+ if (seen.has(canonical(path)))
328
+ continue;
329
+ const nm = classifyNodeModules(path);
330
+ const row = {
331
+ project,
332
+ projectHash,
333
+ path,
334
+ taskId: null,
335
+ category: 'unknown',
336
+ keepReason: project === null
337
+ ? 'no registered project owns this hash directory (report only)'
338
+ : 'git does not list this directory as a worktree of its project (report only)',
339
+ apparentBytes: apparentBytes(path, deadline),
340
+ createdAt: null,
341
+ gitLocked: false,
342
+ taskLocked: false,
343
+ dirtyFiles: null,
344
+ nodeModules: nm,
345
+ nodeModulesBytes: nm === 'real' ? apparentBytes(join(path, 'node_modules'), deadline) : 0,
346
+ };
222
347
  rows.push(row);
223
- meta.set(row, { isMerged: hit?.isMerged ?? false });
224
348
  }
225
349
  }
226
350
  const dfFreeBefore = apply ? freeBytes(machineRoot) : null;
227
351
  let reclaimed = 0;
228
- if (apply) {
229
- const { disposeWorktree, readWorktreeTaskLock } = await import('@cleocode/worktree');
230
- for (const row of rows) {
231
- if (outOfTime())
232
- break;
233
- if (row.category !== 'redundant' || row.project === null)
234
- continue;
235
- if (!applyProjects.has(row.project))
352
+ let retainedBytes = rows.reduce((total, row) => total + row.apparentBytes, 0);
353
+ const oldestFirst = [...rows].sort((a, b) => (a.lastActivity ?? '').localeCompare(b.lastActivity ?? '') || a.path.localeCompare(b.path));
354
+ for (const row of oldestFirst) {
355
+ if (outOfTime())
356
+ break;
357
+ if (row.category !== 'redundant' || row.project === null)
358
+ continue;
359
+ if (row.taskId === null || (row.taskStatus !== 'done' && row.taskStatus !== 'cancelled'))
360
+ continue;
361
+ if (!applyProjects.has(row.project))
362
+ continue;
363
+ const age = Date.now() - Date.parse(row.lastActivity ?? '');
364
+ if (!Number.isFinite(age) || age < ttlDays * 86_400_000 || retainedBytes <= maxBytes)
365
+ continue;
366
+ row.selected = true;
367
+ if (!apply) {
368
+ retainedBytes -= row.apparentBytes;
369
+ continue;
370
+ }
371
+ // An active/reopened task or a store failure after listing cancels removal.
372
+ if (row.taskId !== null) {
373
+ const lookup = await loadOwningTaskStatuses([row.taskId], row.project);
374
+ const status = lookup.success ? lookup.data.get(row.taskId) : undefined;
375
+ if (status === undefined || status !== row.taskStatus) {
376
+ row.category = 'unknown';
377
+ row.keepReason = 'owning task changed or could not be re-read; nothing removed';
236
378
  continue;
237
- // Re-proved here, with the task's evidence: the listing was a dry run.
238
- const disposal = disposeWorktree({
239
- worktreePath: row.path,
240
- projectRoot: row.project,
241
- taskId: row.taskId,
242
- reason: 'census',
243
- evidence: await loadTaskEvidence(row.project, row.taskId),
244
- exemptRegenerable: meta.get(row)?.isMerged ?? false,
245
- inUse: worktreeInUseProbe(readWorktreeTaskLock, row.project, row.taskId),
246
- });
247
- if (disposal.removed) {
248
- row.removed = true;
249
- reclaimed += row.apparentBytes;
250
- }
251
- else {
252
- row.category = disposal.indeterminate === true ? 'unknown' : 'keep';
253
- row.keepReason = disposal.keptReason ?? 'kept';
254
379
  }
255
380
  }
381
+ // Re-proved here, with the task's evidence: the listing was a dry run.
382
+ const disposal = disposeWorktree({
383
+ worktreePath: row.path,
384
+ projectRoot: row.project,
385
+ taskId: row.taskId,
386
+ reason: 'census',
387
+ evidence: await loadTaskEvidence(row.project, row.taskId),
388
+ exemptRegenerable: opts.exemptRegenerable === true && meta.get(row)?.isMerged === true,
389
+ inUse: await worktreeReaperInUseProbe(row.project, row.taskId, row.path),
390
+ });
391
+ if (disposal.removed) {
392
+ row.removed = true;
393
+ reclaimed += row.apparentBytes;
394
+ retainedBytes -= row.apparentBytes;
395
+ }
396
+ else {
397
+ row.category = disposal.indeterminate === true ? 'unknown' : 'keep';
398
+ row.keepReason = disposal.keptReason ?? 'kept';
399
+ }
400
+ appendWorktreeAuditEntry(row.project, {
401
+ actor: resolveWorktreeAuditActor(),
402
+ action: 'prune',
403
+ target: row.path,
404
+ ...(row.taskId !== null ? { taskId: row.taskId } : {}),
405
+ ...(row.branch !== undefined ? { branch: row.branch } : {}),
406
+ reason: 'census',
407
+ success: disposal.removed,
408
+ ...(row.keepReason !== undefined ? { error: row.keepReason } : {}),
409
+ });
256
410
  }
257
411
  const dfFreeAfter = apply ? freeBytes(machineRoot) : null;
258
412
  const counts = {
@@ -265,8 +419,18 @@ async function census(opts) {
265
419
  if (!row.removed)
266
420
  counts[row.category] += 1;
267
421
  outOfTime();
422
+ // T14440: one overall deadline — every measurement below shares the walk's,
423
+ // so a truncation is always visible in `partial`.
424
+ const registeredRollups = [...projectByHash.entries()].map(([hash, root]) => ({
425
+ project: root,
426
+ projectHash: hash,
427
+ }));
428
+ const branchesOf = opts.branchesOf ?? ((projectRoot) => mergedBranchCounts(projectRoot, deadline));
429
+ const rollups = await projectRollups(rows, registeredRollups, branchesOf, async (projectRoot) => statusReadByProject.get(projectRoot) ?? 'status unknown');
430
+ const store = opts.pnpmStore === undefined ? pnpmStoreCensus(deadline) : null;
431
+ outOfTime();
268
432
  return {
269
- schemaVersion: 1,
433
+ schemaVersion: 2,
270
434
  mode: apply ? 'apply' : 'report',
271
435
  startedAt,
272
436
  finishedAt: new Date().toISOString(),
@@ -283,7 +447,309 @@ async function census(opts) {
283
447
  .map((r) => ({ path: r.path, category: r.category, keepReason: r.keepReason ?? '' })),
284
448
  rows,
285
449
  partial,
450
+ ttlDays,
451
+ maxBytes,
452
+ projectErrors,
453
+ projects: rollups.rollups,
454
+ orphanFolders: rollups.orphans,
455
+ pnpmStore: opts.pnpmStore === undefined ? store : opts.pnpmStore,
456
+ };
457
+ }
458
+ /** Wall-clock budget note: the merged-branch and pnpm measurements share the walk deadline. */
459
+ /**
460
+ * Per-project rollups over the census rows, seeded with every registered
461
+ * project (a project with zero worktrees keeps its branch counts, T14440
462
+ * review P2e), plus the orphan hash directories.
463
+ *
464
+ * Merged-branch probes run once per registered project (never for orphans);
465
+ * a probe failure records `null`, never a zero. `storeRead` is the census's
466
+ * own status-read label ('read' / display snapshot / 'status unknown').
467
+ *
468
+ * @param rows - The census rows.
469
+ * @param registered - Every registered project root and its hash.
470
+ * @param branchesOf - Merged-branch counter (tests stub it).
471
+ * @param verdictOf - The foreign-store read verdict (tests stub it).
472
+ * @returns Rollups keyed by hash dir and the orphan directories among them.
473
+ */
474
+ async function projectRollups(rows, registered, branchesOf, verdictOf) {
475
+ const byHash = new Map();
476
+ const seed = async (project, projectHash) => {
477
+ const existing = byHash.get(projectHash);
478
+ if (existing)
479
+ return existing;
480
+ const rollup = {
481
+ project,
482
+ projectHash,
483
+ worktrees: 0,
484
+ apparentBytes: 0,
485
+ mergedLocalBranches: null,
486
+ mergedRemoteBranches: null,
487
+ orphan: project === null,
488
+ storeRead: project === null ? 'not read: orphan directory' : await verdictOf(project),
489
+ };
490
+ byHash.set(projectHash, rollup);
491
+ return rollup;
286
492
  };
493
+ for (const entry of registered)
494
+ await seed(entry.project, entry.projectHash);
495
+ for (const row of rows) {
496
+ const rollup = await seed(row.project, row.projectHash);
497
+ if (!row.removed) {
498
+ rollup.worktrees += 1;
499
+ rollup.apparentBytes += row.apparentBytes;
500
+ }
501
+ }
502
+ const orphans = [];
503
+ for (const rollup of byHash.values()) {
504
+ if (rollup.orphan) {
505
+ orphans.push({
506
+ projectHash: rollup.projectHash,
507
+ worktrees: rollup.worktrees,
508
+ apparentBytes: rollup.apparentBytes,
509
+ });
510
+ }
511
+ else if (rollup.project !== null) {
512
+ const counts = await branchesOf(rollup.project);
513
+ rollup.mergedLocalBranches = counts.mergedLocal;
514
+ rollup.mergedRemoteBranches = counts.mergedRemote;
515
+ }
516
+ }
517
+ return { rollups: [...byHash.values()], orphans };
518
+ }
519
+ /** Where the compiled worker file lives, or `null` (resolveWorkerPath pattern). */
520
+ function resolvePrunePlanWorkerPath() {
521
+ try {
522
+ const currentDir = dirname(fileURLToPath(import.meta.url));
523
+ // dist build: the compiled .js next to census.js; vitest/source: the .ts
524
+ // sibling (Node 24 type stripping runs it, and it exists in the checkout).
525
+ for (const name of ['prune-plan-worker.js', 'prune-plan-worker.ts']) {
526
+ const candidate = join(currentDir, name);
527
+ if (existsSync(candidate))
528
+ return candidate;
529
+ }
530
+ return null;
531
+ }
532
+ catch {
533
+ return null;
534
+ }
535
+ }
536
+ /**
537
+ * The SDK integration probe, run in a Worker built from a REAL module file
538
+ * (never eval — an eval worker inherits the parent's `--input-type=module`
539
+ * and cannot bootstrap) that the shared deadline TERMINATES (T14440, round 5).
540
+ * The napi `pruneWorktrees` walk over a large repository is synchronous and
541
+ * uninterruptible in-process, so it runs off-thread and a deadline overrun
542
+ * kills it before the census releases its lock. Any failure yields `null` —
543
+ * a failed probe is never a zero.
544
+ *
545
+ * @param repoRoot - The repository root to probe.
546
+ * @param integrationTarget - The branch "merged" is tested against.
547
+ * @param deadline - Wall-clock ms epoch; past it the worker is terminated.
548
+ * @returns The prune plan, or `null`.
549
+ */
550
+ export async function prunePlanBounded(repoRoot, integrationTarget, deadline,
551
+ /** Test hook: the worker writes this file markerDelayMs after the walk. */
552
+ markerPath,
553
+ /** Test hook: the marker delay (ms) after the walk completes. */
554
+ markerDelayMs,
555
+ /** Test hook: invoked when the worker has fully exited (round 7, item 5). */
556
+ onWorkerExit) {
557
+ const remainingMs = deadline - Date.now();
558
+ if (remainingMs <= 0)
559
+ return null;
560
+ const workerPath = resolvePrunePlanWorkerPath();
561
+ if (workerPath === null) {
562
+ // No worker file (unexpected — the build emits it next to this module):
563
+ // fall back in-process. Not interruptible; the census re-checks the
564
+ // deadline afterwards and marks the record partial.
565
+ const { buildGitAwarePrunePlan } = await import('@cleocode/worktree');
566
+ return buildGitAwarePrunePlan(repoRoot, integrationTarget);
567
+ }
568
+ const worker = new Worker(workerPath, {
569
+ // Round 7 (item 4): execArgv literally [] — the parent may run with
570
+ // --input-type=module (the lazy census child spawns that way), and an
571
+ // inherited --input-type makes the Worker throw ERR_INPUT_TYPE_NOT_ALLOWED.
572
+ execArgv: [],
573
+ workerData: {
574
+ requireFrom: fileURLToPath(import.meta.url),
575
+ repoRoot,
576
+ integrationTarget,
577
+ markerPath,
578
+ markerDelayMs,
579
+ },
580
+ });
581
+ let received = null;
582
+ return new Promise((resolvePromise) => {
583
+ let settled = false;
584
+ const settle = (value) => {
585
+ if (settled)
586
+ return;
587
+ settled = true;
588
+ if (timer !== null)
589
+ clearTimeout(timer);
590
+ resolvePromise(value);
591
+ };
592
+ // AC1 (round 4): no deadline means no timer — `Infinity` clamps to 1 ms
593
+ // and would kill every probe while it still runs.
594
+ const timer = Number.isFinite(remainingMs)
595
+ ? setTimeout(() => {
596
+ void worker.terminate();
597
+ }, remainingMs)
598
+ : null;
599
+ worker.once('message', (message) => {
600
+ received = message;
601
+ });
602
+ worker.once('error', (error) => {
603
+ received = { error: error.message };
604
+ });
605
+ worker.once('exit', () => {
606
+ onWorkerExit?.();
607
+ const plan = received?.plan;
608
+ settle(plan && Array.isArray(plan.candidates) ? { candidates: plan.candidates } : null);
609
+ });
610
+ });
611
+ }
612
+ /**
613
+ * Merged-branch counts for one project: local via the worker-bounded SDK
614
+ * integration probe (primary checkout and target excluded), remote via
615
+ * `git for-each-ref --merged` with HEAD refs excluded, all under the shared
616
+ * walk deadline. `null` per side when its probe fails or the deadline ends -
617
+ * a failed probe is never a zero (T14440).
618
+ *
619
+ * @param projectRoot - The registered project's repository root.
620
+ * @param deadline - Wall-clock ms epoch past which probes stop.
621
+ * @param planOf - The SDK probe (tests stub it; default {@link prunePlanBounded}).
622
+ * @returns Merged local and remote branch counts.
623
+ */
624
+ export async function mergedBranchCounts(projectRoot, deadline = Number.POSITIVE_INFINITY, planOf = prunePlanBounded) {
625
+ if (Date.now() > deadline)
626
+ return { mergedLocal: null, mergedRemote: null };
627
+ const defaultRefs = gitDefaultBranchRefs(projectRoot);
628
+ const integrationTarget = defaultRefs.find((ref) => !ref.startsWith('origin/')) ?? defaultRefs[0];
629
+ if (integrationTarget === undefined)
630
+ return { mergedLocal: null, mergedRemote: null };
631
+ let mergedLocal = null;
632
+ let mergedRemote = null;
633
+ try {
634
+ const plan = await planOf(projectRoot, integrationTarget, deadline);
635
+ if (plan !== null) {
636
+ mergedLocal = new Set(plan.candidates
637
+ .filter((c) => c.kind === 'worktree' || c.kind === 'branch_only')
638
+ .map((c) => c.branch)
639
+ .filter((b) => b !== undefined)).size;
640
+ }
641
+ }
642
+ catch {
643
+ mergedLocal = null;
644
+ }
645
+ if (Date.now() > deadline)
646
+ return { mergedLocal, mergedRemote };
647
+ try {
648
+ const out = execFileSync('git', [
649
+ '--no-optional-locks',
650
+ 'for-each-ref',
651
+ '--merged',
652
+ integrationTarget,
653
+ '--format=%(refname:short)',
654
+ 'refs/remotes',
655
+ ], { cwd: projectRoot, timeout: 10_000, stdio: ['pipe', 'pipe', 'pipe'], encoding: 'utf-8' });
656
+ mergedRemote = out
657
+ .split('\n')
658
+ .map((line) => line.trim())
659
+ // A remote branch is `<remote>/<name>`; the bare remote line and HEAD
660
+ // aliases are not branches, and the target's own remote ref is trivially
661
+ // merged.
662
+ .filter((ref) => ref.includes('/') &&
663
+ !ref.endsWith('/HEAD') &&
664
+ !ref.endsWith(`/${integrationTarget.replace(/^origin\//, '')}`)).length;
665
+ }
666
+ catch {
667
+ mergedRemote = null;
668
+ }
669
+ return { mergedLocal, mergedRemote };
670
+ }
671
+ /**
672
+ * The `node_modules` classification for one worktree (T14440).
673
+ *
674
+ * @param worktreePath - The worktree directory.
675
+ * @returns `absent`, `symlink` or `real`.
676
+ */
677
+ function classifyNodeModules(worktreePath) {
678
+ try {
679
+ const st = lstatSync(join(worktreePath, 'node_modules'));
680
+ if (st.isSymbolicLink())
681
+ return 'symlink';
682
+ if (st.isDirectory())
683
+ return 'real';
684
+ return 'absent';
685
+ }
686
+ catch {
687
+ return 'absent';
688
+ }
689
+ }
690
+ /**
691
+ * Changed + untracked entry count without optional Git index writes (T14440).
692
+ *
693
+ * @param worktreePath - The worktree directory.
694
+ * @param deadline - Past it, `null` (an undercount is never a zero).
695
+ * @returns The dirty entry count, or `null`.
696
+ */
697
+ function dirtyFileCount(worktreePath, deadline) {
698
+ if (Date.now() > deadline)
699
+ return null;
700
+ try {
701
+ const out = execFileSync('git', ['--no-optional-locks', 'status', '--porcelain'], {
702
+ cwd: worktreePath,
703
+ timeout: 10_000,
704
+ stdio: ['pipe', 'pipe', 'pipe'],
705
+ encoding: 'utf-8',
706
+ });
707
+ return out.split('\n').filter((line) => line.trim() !== '').length;
708
+ }
709
+ catch {
710
+ return null;
711
+ }
712
+ }
713
+ /**
714
+ * CLEO task-lock state for one worktree's task (T14440).
715
+ *
716
+ * @param read - The lock reader (`readWorktreeTaskLock`).
717
+ * @param projectHash - The project hash directory.
718
+ * @param taskId - The owning task, or `null`.
719
+ * @returns True when a live task lock record exists.
720
+ */
721
+ function readTaskLockSafe(read, projectHash, taskId) {
722
+ if (taskId === null)
723
+ return false;
724
+ return read(projectHash, taskId) !== null;
725
+ }
726
+ /**
727
+ * The global pnpm content-addressable store and its apparent size (T14440).
728
+ * `pnpm store path` resolves the location from the home dir (an inherited
729
+ * per-worktree cwd would honour that worktree's `.npmrc` store-dir); any
730
+ * failure yields `null`, never a zero-sized store.
731
+ *
732
+ * @param deadline - Past it, `null`.
733
+ * @returns The store census, or `null`.
734
+ */
735
+ export function pnpmStoreCensus(deadline = Number.POSITIVE_INFINITY) {
736
+ if (Date.now() > deadline)
737
+ return null;
738
+ let storePath;
739
+ try {
740
+ storePath = execFileSync('pnpm', ['store', 'path'], {
741
+ cwd: homedir(),
742
+ timeout: 10_000,
743
+ stdio: ['pipe', 'pipe', 'pipe'],
744
+ encoding: 'utf-8',
745
+ }).trim();
746
+ }
747
+ catch {
748
+ return null;
749
+ }
750
+ if (storePath === '' || !existsSync(storePath))
751
+ return null;
752
+ return { path: storePath, apparentBytes: apparentBytes(storePath, deadline) };
287
753
  }
288
754
  /** The lazy census child's wall-clock budget: past it, a partial record and exit. */
289
755
  export const LAZY_CENSUS_BUDGET_MS = 3 * 60 * 1000;
@@ -337,10 +803,10 @@ export function startLazyCensus(env, deps = {}) {
337
803
  mkdirSync(dir, { recursive: true });
338
804
  if (censusLockHeld(dir, now))
339
805
  return 'another census holds the lock';
340
- if (!claimCensus(now, dir))
806
+ if (!claimCensus(now, dir, deps.projectRoot))
341
807
  return 'already claimed in the last 24 h';
342
808
  const entry = import.meta.url;
343
- const script = `import(${JSON.stringify(entry)}).then((m) => m.runLazyCensus(${JSON.stringify(dir)}))`;
809
+ const script = `import(${JSON.stringify(entry)}).then((m) => m.runLazyCensus(${JSON.stringify(dir)}, ${JSON.stringify(deps.projectRoot)}))`;
344
810
  const log = openSync(join(dir, 'census.log'), 'a');
345
811
  try {
346
812
  const [cmd, ...pre] = [...lowPriorityPrefix(), process.execPath];
@@ -363,9 +829,10 @@ export function startLazyCensus(env, deps = {}) {
363
829
  * process alive. The lock is released on every exit path.
364
830
  *
365
831
  * @param dir - The census directory.
832
+ * @param projectRoot - The project captured by the scheduling caller.
366
833
  * @task T14275
367
834
  */
368
- export async function runLazyCensus(dir = censusDir()) {
835
+ export async function runLazyCensus(dir = censusDir(), projectRoot) {
369
836
  try {
370
837
  setPriority(19);
371
838
  }
@@ -373,7 +840,16 @@ export async function runLazyCensus(dir = censusDir()) {
373
840
  // Not permitted here: the budget still bounds the run.
374
841
  }
375
842
  setTimeout(() => process.exit(2), LAZY_CENSUS_BUDGET_MS + 60_000).unref();
843
+ const { getProjectRoot } = await import('../paths.js');
844
+ try {
845
+ projectRoot ??= getProjectRoot();
846
+ }
847
+ catch {
848
+ /* no project: report only */
849
+ }
376
850
  const result = await runWorktreeCensus({
851
+ apply: projectRoot !== undefined,
852
+ applyProjects: projectRoot !== undefined ? [projectRoot] : [],
377
853
  recordDir: dir,
378
854
  deadline: Date.now() + LAZY_CENSUS_BUDGET_MS,
379
855
  });
@@ -397,17 +873,19 @@ export function censusSpawnAllowed(env) {
397
873
  return !(env['GIT_EXEC_PATH'] || env['GIT_INDEX_FILE'] || env['GIT_DIR']);
398
874
  }
399
875
  /**
400
- * Claim today's lazy census, atomically: true for exactly one caller per
401
- * {@link CENSUS_INTERVAL_MS} on this machine.
876
+ * Claim today's lazy census, atomically: one caller per project per interval,
877
+ * or one machine-wide report when no project is supplied.
402
878
  *
403
879
  * @param now - Current time (ms).
404
880
  * @param dir - The census directory (tests).
881
+ * @param projectRoot - The canonical project root whose daily run is claimed.
405
882
  * @returns True when this caller should start the census.
406
883
  * @task T14275
407
884
  */
408
- export function claimCensus(now = Date.now(), dir = censusDir()) {
885
+ export function claimCensus(now = Date.now(), dir = censusDir(), projectRoot) {
409
886
  mkdirSync(dir, { recursive: true });
410
- return claimAtMostEvery(join(dir, 'census.claim'), CENSUS_INTERVAL_MS, now);
887
+ const name = projectRoot === undefined ? 'census' : `census-${computeProjectHash(projectRoot)}`;
888
+ return claimAtMostEvery(join(dir, `${name}.claim`), CENSUS_INTERVAL_MS, now);
411
889
  }
412
890
  /**
413
891
  * The newest census record, or `null` when none was written.