taskplane 0.26.1 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,26 @@
1
1
  /**
2
2
  * Artifact cleanup and log rotation for orchestrator runtime files.
3
3
  *
4
- * Three cleanup layers prevent unbounded disk growth:
4
+ * Five cleanup layers prevent unbounded disk growth:
5
5
  *
6
6
  * 1. **Post-Integrate Cleanup** — Deletes batch-specific telemetry and merge
7
7
  * result files after successful /orch-integrate. Scoped by batchId.
8
8
  *
9
- * 2. **Age-Based Preflight Sweep** — On /orch start, removes telemetry and
10
- * merge artifacts older than 7 days. Catches files missed by Layer 1
11
- * (e.g., aborted batches, manual branch deletions).
9
+ * 2. **Age-Based Preflight Sweep** — On /orch start, removes telemetry,
10
+ * verification, conversation, lane-state, and merge artifacts older than
11
+ * 3 days. Catches files missed by Layer 1 (e.g., aborted batches,
12
+ * manual branch deletions).
12
13
  *
13
14
  * 3. **Size-Capped Log Rotation** — Rotates append-only supervisor logs
14
15
  * (events.jsonl, actions.jsonl) at a 5MB threshold during preflight.
15
16
  * Keeps one .old generation.
16
17
  *
18
+ * 4. **Telemetry Size Cap** — Enforces a 500MB cap on `.pi/telemetry/`
19
+ * by evicting oldest files first when the directory exceeds the cap.
20
+ *
21
+ * 5. **Batch-Start Cleanup** — Removes artifacts from prior completed
22
+ * batches when a new batch starts, protecting the current batch.
23
+ *
17
24
  * All cleanup is **non-fatal** — failures warn but never block execution.
18
25
  *
19
26
  * @module orch/cleanup
@@ -177,8 +184,8 @@ export function formatPostIntegrateCleanup(result: PostIntegrateCleanupResult):
177
184
 
178
185
  // ── Layer 2: Age-Based Preflight Sweep ──────────────────────────────
179
186
 
180
- /** Default max age for stale artifacts (7 days in milliseconds). */
181
- export const STALE_ARTIFACT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
187
+ /** Default max age for stale artifacts (3 days in milliseconds). */
188
+ export const STALE_ARTIFACT_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
182
189
 
183
190
  /**
184
191
  * Result of a preflight age-based sweep.
@@ -215,13 +222,16 @@ export interface SweepDeps {
215
222
  * - `.pi/telemetry/lane-prompt-*.txt` — temporary prompt files
216
223
  * - `.pi/merge-result-*.json` — merge result files
217
224
  * - `.pi/merge-request-*.txt` — merge request files
225
+ * - `.pi/verification/*` — verification snapshots
226
+ * - `.pi/worker-conversation-*.jsonl` — worker conversation logs
227
+ * - `.pi/lane-state-*.json` — lane state files
218
228
  *
219
229
  * Uses file mtime for age detection. Skips files modified within maxAgeMs.
220
230
  * If a batch is currently active (executing/merging), skips ALL cleanup.
221
231
  *
222
232
  * @param stateRoot - Root directory containing .pi/
223
233
  * @param deps - Injectable dependencies for testability
224
- * @param maxAgeMs - Maximum file age in milliseconds (default: 7 days)
234
+ * @param maxAgeMs - Maximum file age in milliseconds (default: 3 days)
225
235
  * @returns Sweep result with count and warnings
226
236
  */
227
237
  export function sweepStaleArtifacts(
@@ -289,7 +299,17 @@ export function sweepStaleArtifacts(
289
299
  (name.startsWith("merge-request-") && name.endsWith(".txt")),
290
300
  );
291
301
 
292
- // Sweep stale batch directories under a parent (mailbox, context-snapshots)
302
+ // Sweep stale worker conversation logs (.pi/worker-conversation-*.jsonl)
303
+ sweepDir(join(stateRoot, ".pi"), (name) =>
304
+ name.startsWith("worker-conversation-") && name.endsWith(".jsonl"),
305
+ );
306
+
307
+ // Sweep stale lane state files (.pi/lane-state-*.json)
308
+ sweepDir(join(stateRoot, ".pi"), (name) =>
309
+ name.startsWith("lane-state-") && name.endsWith(".json"),
310
+ );
311
+
312
+ // Sweep stale batch directories under a parent (mailbox, context-snapshots, verification)
293
313
  const sweepBatchDirs = (parentDir: string, label: string): void => {
294
314
  if (!existsSync(parentDir)) return;
295
315
  try {
@@ -318,6 +338,9 @@ export function sweepStaleArtifacts(
318
338
  // Sweep stale context-snapshot batch directories (.pi/context-snapshots/{batchId}/)
319
339
  sweepBatchDirs(join(stateRoot, ".pi", "context-snapshots"), "context-snapshots");
320
340
 
341
+ // Sweep stale verification snapshot directories (.pi/verification/{opId}/)
342
+ sweepBatchDirs(join(stateRoot, ".pi", "verification"), "verification");
343
+
321
344
  return result;
322
345
  }
323
346
 
@@ -336,7 +359,7 @@ export function formatPreflightSweep(result: PreflightSweepResult): string {
336
359
  const segments: string[] = [];
337
360
  if (result.staleFilesDeleted > 0) segments.push(`${result.staleFilesDeleted} stale artifact(s)`);
338
361
  if (result.staleDirsDeleted > 0) segments.push(`${result.staleDirsDeleted} stale mailbox dir(s)`);
339
- parts.push(`🧹 Preflight cleanup: removed ${segments.join(" and ")} (>7 days old)`);
362
+ parts.push(`🧹 Preflight cleanup: removed ${segments.join(" and ")} (>3 days old)`);
340
363
  }
341
364
  for (const warning of result.warnings) {
342
365
  parts.push(` ⚠️ ${warning}`);
@@ -424,6 +447,245 @@ export function formatLogRotation(result: LogRotationResult): string {
424
447
  return parts.join("\n");
425
448
  }
426
449
 
450
+ // ── Layer 4: Telemetry Directory Size Cap ─────────────────────────────
451
+
452
+ /** Default telemetry directory size cap: 500 MB. */
453
+ export const TELEMETRY_SIZE_CAP_BYTES = 500 * 1024 * 1024;
454
+
455
+ /**
456
+ * Result of telemetry size cap enforcement.
457
+ */
458
+ export interface SizeCapResult {
459
+ /** Number of files deleted to bring directory under cap */
460
+ filesDeleted: number;
461
+ /** Total bytes freed */
462
+ bytesFreed: number;
463
+ /** Warnings from non-fatal failures */
464
+ warnings: string[];
465
+ }
466
+
467
+ /**
468
+ * Enforce a size cap on the telemetry directory by evicting oldest files first.
469
+ *
470
+ * Scans `.pi/telemetry/` and sums file sizes. If the total exceeds `capBytes`,
471
+ * deletes the oldest files (by mtime) until the total is under the cap.
472
+ *
473
+ * @param stateRoot - Root directory containing .pi/
474
+ * @param capBytes - Maximum allowed total size in bytes (default: 500MB)
475
+ * @returns Size cap enforcement result
476
+ */
477
+ export function enforceTelemetrySizeCap(
478
+ stateRoot: string,
479
+ capBytes: number = TELEMETRY_SIZE_CAP_BYTES,
480
+ ): SizeCapResult {
481
+ const result: SizeCapResult = {
482
+ filesDeleted: 0,
483
+ bytesFreed: 0,
484
+ warnings: [],
485
+ };
486
+
487
+ const telemetryDir = join(stateRoot, ".pi", "telemetry");
488
+ if (!existsSync(telemetryDir)) return result;
489
+
490
+ // Collect all files with size and mtime
491
+ interface FileEntry {
492
+ name: string;
493
+ path: string;
494
+ size: number;
495
+ mtimeMs: number;
496
+ }
497
+
498
+ const files: FileEntry[] = [];
499
+ let totalSize = 0;
500
+
501
+ try {
502
+ const entries = readdirSync(telemetryDir);
503
+ for (const entry of entries) {
504
+ const filePath = join(telemetryDir, entry);
505
+ try {
506
+ const stat = statSync(filePath);
507
+ if (!stat.isFile()) continue;
508
+ files.push({ name: entry, path: filePath, size: stat.size, mtimeMs: stat.mtimeMs });
509
+ totalSize += stat.size;
510
+ } catch (err: unknown) {
511
+ result.warnings.push(`Failed to stat ${entry}: ${(err as Error).message}`);
512
+ }
513
+ }
514
+ } catch (err: unknown) {
515
+ result.warnings.push(`Failed to read telemetry directory: ${(err as Error).message}`);
516
+ return result;
517
+ }
518
+
519
+ if (totalSize <= capBytes) return result;
520
+
521
+ // Sort oldest first (lowest mtime first)
522
+ files.sort((a, b) => a.mtimeMs - b.mtimeMs);
523
+
524
+ // Delete oldest files until under cap
525
+ for (const file of files) {
526
+ if (totalSize <= capBytes) break;
527
+ try {
528
+ unlinkSync(file.path);
529
+ totalSize -= file.size;
530
+ result.filesDeleted++;
531
+ result.bytesFreed += file.size;
532
+ } catch (err: unknown) {
533
+ result.warnings.push(`Failed to delete ${file.name}: ${(err as Error).message}`);
534
+ }
535
+ }
536
+
537
+ return result;
538
+ }
539
+
540
+ /**
541
+ * Format size cap result for logging.
542
+ */
543
+ export function formatSizeCap(result: SizeCapResult): string {
544
+ if (result.filesDeleted === 0 && result.warnings.length === 0) return "";
545
+ const parts: string[] = [];
546
+ if (result.filesDeleted > 0) {
547
+ const mbFreed = (result.bytesFreed / (1024 * 1024)).toFixed(1);
548
+ parts.push(`🧹 Telemetry size cap: deleted ${result.filesDeleted} file(s), freed ${mbFreed} MB`);
549
+ }
550
+ for (const warning of result.warnings) {
551
+ parts.push(` ⚠️ ${warning}`);
552
+ }
553
+ return parts.join("\n");
554
+ }
555
+
556
+ // ── Layer 5: Batch-Start Cleanup of Prior Batch Artifacts ─────────────
557
+
558
+ /**
559
+ * Result of prior-batch artifact cleanup.
560
+ */
561
+ export interface PriorBatchCleanupResult {
562
+ /** Number of files/dirs deleted */
563
+ itemsDeleted: number;
564
+ /** Warnings from non-fatal failures */
565
+ warnings: string[];
566
+ }
567
+
568
+ /**
569
+ * Clean up artifacts from prior completed batches when a new batch starts.
570
+ *
571
+ * Removes batch-scoped files that may have been left behind by prior runs
572
+ * that were not integrated (e.g., aborted, crashed). Only cleans artifacts
573
+ * from batches that are NOT the currently active batch.
574
+ *
575
+ * Targets the same file patterns as `cleanupPostIntegrate` plus stale
576
+ * batch-state files.
577
+ *
578
+ * @param stateRoot - Root directory containing .pi/
579
+ * @param currentBatchId - The batch ID that is currently starting (will NOT be deleted)
580
+ * @returns Cleanup result
581
+ */
582
+ export function cleanupPriorBatchArtifacts(
583
+ stateRoot: string,
584
+ currentBatchId: string,
585
+ ): PriorBatchCleanupResult {
586
+ const result: PriorBatchCleanupResult = {
587
+ itemsDeleted: 0,
588
+ warnings: [],
589
+ };
590
+
591
+ if (!currentBatchId) {
592
+ result.warnings.push("No currentBatchId provided — skipping prior batch cleanup");
593
+ return result;
594
+ }
595
+
596
+ const piDir = join(stateRoot, ".pi");
597
+ if (!existsSync(piDir)) return result;
598
+
599
+ // Helper: delete files in a directory matching a filter, skipping current batch
600
+ const cleanDir = (dir: string, filter: (name: string) => boolean): void => {
601
+ if (!existsSync(dir)) return;
602
+ try {
603
+ const entries = readdirSync(dir);
604
+ for (const entry of entries) {
605
+ if (!filter(entry)) continue;
606
+ if (entry.includes(currentBatchId)) continue; // Protect current batch
607
+ const filePath = join(dir, entry);
608
+ try {
609
+ const stat = statSync(filePath);
610
+ if (stat.isFile()) {
611
+ unlinkSync(filePath);
612
+ result.itemsDeleted++;
613
+ }
614
+ } catch (err: unknown) {
615
+ result.warnings.push(`Failed to delete ${entry}: ${(err as Error).message}`);
616
+ }
617
+ }
618
+ } catch (err: unknown) {
619
+ result.warnings.push(`Failed to read directory ${dir}: ${(err as Error).message}`);
620
+ }
621
+ };
622
+
623
+ // Clean telemetry files from prior batches
624
+ cleanDir(join(piDir, "telemetry"), (name) =>
625
+ name.endsWith(".jsonl") ||
626
+ name.endsWith("-exit.json") ||
627
+ (name.startsWith("lane-prompt-") && name.endsWith(".txt")),
628
+ );
629
+
630
+ // Clean merge result/request files from prior batches
631
+ cleanDir(piDir, (name) =>
632
+ (name.startsWith("merge-result-") && name.endsWith(".json")) ||
633
+ (name.startsWith("merge-request-") && name.endsWith(".txt")),
634
+ );
635
+
636
+ // Clean worker conversation logs from prior batches
637
+ cleanDir(piDir, (name) =>
638
+ name.startsWith("worker-conversation-") && name.endsWith(".jsonl"),
639
+ );
640
+
641
+ // Clean lane state files from prior batches
642
+ cleanDir(piDir, (name) =>
643
+ name.startsWith("lane-state-") && name.endsWith(".json"),
644
+ );
645
+
646
+ // Clean batch-scoped directories (mailbox, context-snapshots)
647
+ const cleanBatchDirs = (parentDir: string): void => {
648
+ if (!existsSync(parentDir)) return;
649
+ try {
650
+ const entries = readdirSync(parentDir);
651
+ for (const entry of entries) {
652
+ if (entry === currentBatchId) continue; // Protect current batch
653
+ const entryPath = join(parentDir, entry);
654
+ try {
655
+ const stat = statSync(entryPath);
656
+ if (!stat.isDirectory()) continue;
657
+ rmSync(entryPath, { recursive: true, force: true });
658
+ result.itemsDeleted++;
659
+ } catch (err: unknown) {
660
+ result.warnings.push(`Failed to delete batch dir ${entry}: ${(err as Error).message}`);
661
+ }
662
+ }
663
+ } catch (err: unknown) {
664
+ result.warnings.push(`Failed to read directory ${parentDir}: ${(err as Error).message}`);
665
+ }
666
+ };
667
+
668
+ cleanBatchDirs(join(piDir, MAILBOX_DIR_NAME));
669
+ cleanBatchDirs(join(piDir, "context-snapshots"));
670
+
671
+ return result;
672
+ }
673
+
674
+ /**
675
+ * Format prior batch cleanup result for logging.
676
+ */
677
+ export function formatPriorBatchCleanup(result: PriorBatchCleanupResult): string {
678
+ if (result.itemsDeleted === 0 && result.warnings.length === 0) return "";
679
+ const parts: string[] = [];
680
+ if (result.itemsDeleted > 0) {
681
+ parts.push(`🧹 Prior batch cleanup: removed ${result.itemsDeleted} artifact(s) from previous batch(es)`);
682
+ }
683
+ for (const warning of result.warnings) {
684
+ parts.push(` ⚠️ ${warning}`);
685
+ }
686
+ return parts.join("\n");
687
+ }
688
+
427
689
  // ── Combined Preflight Cleanup ──────────────────────────────────────
428
690
 
429
691
  /**
@@ -466,7 +728,7 @@ export function formatPreflightCleanup(result: PreflightCleanupResult): string {
466
728
  const segments: string[] = [];
467
729
  if (result.sweep.staleFilesDeleted > 0) segments.push(`${result.sweep.staleFilesDeleted} stale artifact(s)`);
468
730
  if (result.sweep.staleDirsDeleted > 0) segments.push(`${result.sweep.staleDirsDeleted} stale mailbox dir(s)`);
469
- parts.push(`removed ${segments.join(" and ")} (>7 days old)`);
731
+ parts.push(`removed ${segments.join(" and ")} (>3 days old)`);
470
732
  }
471
733
 
472
734
  // Layer 3: log rotation