-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorkspaceWorktreeCleanupEngine.php
More file actions
3365 lines (3059 loc) · 131 KB
/
Copy pathWorkspaceWorktreeCleanupEngine.php
File metadata and controls
3365 lines (3059 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Worktree cleanup engine, safety gates, and reporting helpers.
*
* @package DataMachineCode\Workspace
*/
namespace DataMachineCode\Workspace;
use DataMachineCode\Support\GitHubRemote;
defined('ABSPATH') || exit;
trait WorkspaceWorktreeCleanupEngine {
/**
* Cleanup merged worktrees across all primary checkouts.
*
* Scans all worktrees, consults upstream tracking + GitHub PR state,
* and (unless dry-run) removes worktrees whose work is already merged
* to the remote default branch. Also deletes the local branch and
* prunes the git registry afterwards.
*
* A worktree is considered prunable when ALL of:
* - It is not the primary checkout
* - Its branch is not main/master/trunk/develop/HEAD
* - It has no uncommitted changes (unless $force)
* - At least one cleanup signal is present:
* a) `git for-each-ref` reports upstream status "gone" (branch
* was deleted on the remote — typical after GitHub
* "auto-delete head branches" fires on PR merge), OR
* b) GitHub API reports a closed+merged PR whose head
* branch matches this worktree's branch, OR
* c) the clean local worktree has no unpushed commits and is backed
* by an existing remote branch, so removing the local checkout does
* not delete recoverable Git state.
*
* Signals (a) and (c) are local and fast; signal (b) requires a PAT + network
* but catches the case where the remote branch still exists (e.g.
* manual merge without branch deletion).
*
* @param array $opts {
* @type bool $dry_run If true, return the plan without removing anything.
* @type bool $force If true, ignore dirty working-tree safety.
* @type bool $skip_github If true, only use upstream-gone signal (no API calls).
* @type string $older_than Optional duration such as 7d, 24h, or 30m. Candidates newer than this are skipped.
* }
* @return array<string,mixed>|\WP_Error
*/
public function worktree_cleanup_merged( array $opts = array() ): array|\WP_Error {
$dry_run = ! empty($opts['dry_run']);
$force = ! empty($opts['force']);
$discard_unpushed = ! empty($opts['discard_unpushed']);
$skip_github = ! empty($opts['skip_github']);
$direct_apply_plan = ! empty($opts['direct_apply_plan']);
$inventory_only = ! empty($opts['inventory_only']);
$include_repaired_metadata = ! empty($opts['include_repaired_metadata']);
$stale_liveness_only = ! empty($opts['stale_liveness_only']);
$apply_plan = isset($opts['apply_plan']) && is_array($opts['apply_plan']) ? $opts['apply_plan'] : null;
$older_than = isset($opts['older_than']) ? trim( (string) $opts['older_than']) : '';
$sort = isset($opts['sort']) ? trim( (string) $opts['sort']) : '';
$progress = isset($opts['progress_callback']) && is_callable($opts['progress_callback']) ? $opts['progress_callback'] : null;
$started_at = microtime(true);
$limit = array_key_exists('limit', $opts) ? max(1, (int) $opts['limit']) : null;
$offset = array_key_exists('offset', $opts) ? max(0, (int) $opts['offset']) : 0;
$budget_context = null;
$budget_stopped = false;
$remove_timeout_seconds = $this->normalize_worktree_cleanup_remove_timeout($opts['remove_timeout'] ?? null);
if ( is_wp_error($remove_timeout_seconds) ) {
return $remove_timeout_seconds;
}
if ( isset($opts['until_budget']) && '' !== trim( (string) $opts['until_budget']) ) {
if ( ! $dry_run ) {
return new \WP_Error('cleanup_budget_requires_dry_run', 'Budgeted cleanup is review-only. Use --dry-run with --until-budget, then apply a reviewed cleanup path.', array( 'status' => 400 ));
}
$budget_seconds = $this->parse_worktree_metadata_reconciliation_budget(trim( (string) $opts['until_budget']));
if ( is_wp_error($budget_seconds) ) {
return $budget_seconds;
}
$budget_context = $this->build_worktree_loop_budget_context($opts, $started_at);
}
if ( ( null !== $limit || $offset > 0 ) && ! $dry_run ) {
return new \WP_Error('cleanup_pagination_requires_dry_run', 'Paginated cleanup is review-only. Use --dry-run with --limit/--offset, then apply a reviewed cleanup path.', array( 'status' => 400 ));
}
if ( '' !== $sort && ! in_array($sort, array( 'size', 'age' ), true) ) {
return new \WP_Error('invalid_cleanup_sort', 'Invalid cleanup sort. Use size or age.', array( 'status' => 400 ));
}
if ( $inventory_only ) {
if ( ! $dry_run ) {
return new \WP_Error('inventory_cleanup_requires_dry_run', 'Inventory-only cleanup is review-only. Run workspace worktree bounded-cleanup-eligible-apply to apply the same bounded cleanup-eligible class. Broader merge-signal cleanup is a separate, explicit review path.', array( 'status' => 400 ));
}
if ( null !== $apply_plan ) {
return new \WP_Error('inventory_cleanup_apply_plan_unsupported', 'Inventory-only cleanup cannot apply a plan because it intentionally skips full safety revalidation.', array( 'status' => 400 ));
}
return $this->worktree_cleanup_inventory_only($older_than, $sort, $include_repaired_metadata, $limit, $offset);
}
$planned_candidates = null;
if ( null !== $apply_plan ) {
$planned_candidates = $this->extract_worktree_cleanup_plan_candidates($apply_plan);
if ( is_wp_error($planned_candidates) ) {
return $planned_candidates;
}
// Applying a stale plan must never use the dirty override. The current
// workspace state is re-evaluated below and dirty rows stay skipped.
$force = false;
if ( $direct_apply_plan && ! $dry_run ) {
return $this->apply_worktree_cleanup_plan_candidates($planned_candidates, $force, $started_at, $stale_liveness_only, $remove_timeout_seconds, $discard_unpushed);
}
}
$age_filter = null;
if ( '' !== $older_than ) {
$duration_seconds = $this->parse_worktree_cleanup_duration($older_than);
if ( is_wp_error($duration_seconds) ) {
return $duration_seconds;
}
$age_filter = WorktreeAgeFilter::build($older_than, $duration_seconds);
}
$listing = $this->worktree_list(
null,
null,
array(
'include_status' => false,
'include_disk' => false,
)
);
if ( $listing instanceof \WP_Error ) {
return $listing;
}
$protected_branches = array( 'main', 'master', 'trunk', 'develop', 'HEAD' );
$candidates = array();
$skipped = array();
/** @var array<string,mixed> $github_cache */
$github_cache = array();
$all_worktrees = $this->dedupe_worktree_cleanup_scan_rows(
array_merge(
array_values(array_filter( (array) $listing['worktrees'], fn( $wt ) => empty($wt['is_primary']))),
$this->discover_broken_orphan_worktree_markers( (array) $listing['worktrees'])
)
);
$total_worktrees = count($all_worktrees);
$worktrees = array_slice($all_worktrees, $offset, $limit);
$checked = 0;
$processed = 0;
$removed_count = 0;
$this->emit_worktree_cleanup_progress($progress, 'start', '', $checked, $total_worktrees, $candidates, $skipped, $removed_count, $started_at);
// Fetch + prune each primary once per repo, but keep status/disk probes inside
// the row loop so budgeted dry-runs can return partial evidence promptly.
/** @var array<string,bool> $fetched */
$fetched = array();
/** @var array<string,\WP_Error> $fetch_timeouts */
$fetch_timeouts = array();
foreach ( $worktrees as $wt ) {
if ( null !== $budget_context && $this->is_worktree_loop_budget_exhausted($budget_context) ) {
$budget_stopped = true;
break;
}
++$processed;
$handle = $wt['handle'] ?? '?';
$repo = $wt['repo'] ?? '';
$branch = $wt['branch'] ?? '';
$wt_path = $wt['path'] ?? '';
$metadata = $wt['metadata'] ?? null;
$created_at = $wt['created_at'] ?? null;
$liveness = (string) ( $wt['liveness'] ?? '' );
$disk_fields = $this->extract_worktree_disk_fields($wt);
$identity = $this->recover_worktree_identity_from_metadata($wt);
$repo = (string) $identity['repo'];
$branch = (string) $identity['branch'];
$wt_path = (string) $identity['path'];
$primary_path = '' !== $repo ? $this->get_primary_path($repo) : '';
if ( ! empty($wt['broken_orphan_marker']) ) {
$candidates[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => '',
'path' => $wt_path,
'dirty' => null,
'signal' => 'broken_orphan_worktree_marker',
'reason_code' => 'broken_orphan_worktree_marker',
'reason' => 'managed worktree directory has a .git pointer to missing Git worktree metadata',
'broken_target_path' => (string) ( $wt['broken_target_path'] ?? '' ),
'hint' => 'Cleanup apply will remove this orphan directory only after revalidating that the .git pointer still targets missing worktree metadata.',
'created_at' => $created_at,
'liveness' => $liveness,
'metadata' => $metadata,
),
$disk_fields
);
continue;
}
if ( ! empty($wt['external']) ) {
$skipped[] = array_merge(
array(
'handle' => $handle,
'reason_code' => 'external_worktree',
'reason' => 'external worktree (outside workspace)',
'hint' => 'External worktree outside the DMC workspace; remove with the owning tool or inspect with git worktree list from the primary repo.',
'repo' => $repo,
'owning_repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'primary_path' => $primary_path,
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields
);
continue;
}
++$checked;
$this->emit_worktree_cleanup_progress($progress, 'checking', (string) $handle, $checked, $total_worktrees, $candidates, $skipped, $removed_count, $started_at);
if ( $stale_liveness_only && 'stale' !== $liveness ) {
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'active_or_recent_worktree',
'reason' => sprintf('worktree liveness is %s; stale-worktrees mode only removes stale/inactive worktrees', '' !== $liveness ? $liveness : 'unknown'),
'liveness' => $liveness,
'created_at' => $created_at,
'metadata' => $metadata,
),
$disk_fields
);
continue;
}
if ( '' === $repo || '' === $branch || '' === $wt_path ) {
$missing_fields = array();
foreach (
array(
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
) as $field => $value
) {
if ( '' === $value ) {
$missing_fields[] = $field;
}
}
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'missing_metadata',
'reason' => 'missing repo/branch/path',
'missing_fields' => $missing_fields,
'hydrated_fields' => $identity['hydrated_fields'],
'identity_conflicts' => $identity['conflicts'],
'stored_identity' => $identity['stored_identity'],
'hint' => 'Run workspace worktree prune if this is a stale registry entry; inspect manually if the path still exists.',
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields
);
continue;
}
if ( ! empty($identity['detached_branch']) ) {
$detached_reason = in_array($branch, $protected_branches, true) ? 'detached_protected_branch' : 'detached_worktree';
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => $detached_reason,
'reason' => sprintf('git reports detached HEAD; stored metadata identifies branch %s', $branch),
'actual_branch' => '',
'hydrated_fields' => $identity['hydrated_fields'],
'stored_identity' => $identity['stored_identity'],
'hint' => 'Inspect the detached worktree and either reattach it to the stored branch, finalize lifecycle metadata, or remove it manually after review.',
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields
);
continue;
}
if ( in_array($branch, $protected_branches, true) ) {
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'protected_base_branch_worktree',
'reason' => sprintf('worktree has protected/base branch %s checked out', $branch),
'hint' => 'Protected/base branches should live in primary checkouts. Inspect this worktree, move any needed changes, then remove it explicitly if safe.',
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields
);
continue;
}
$dirty_probe = $this->probe_worktree_dirty_count($wt_path, self::CLEANUP_GIT_PROBE_TIMEOUT);
if ( is_wp_error($dirty_probe) ) {
$skipped[] = $this->build_worktree_probe_failure_skip($handle, $repo, $branch, $wt_path, $created_at, $metadata, $disk_fields, $dirty_probe);
continue;
}
$dirty_count = (int) $dirty_probe;
if ( $dirty_count > 0 && ! $force ) {
$artifact_dirty = $this->classify_artifact_only_dirty_worktree($repo, $wt_path);
if ( is_array($artifact_dirty) ) {
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'artifact_only_dirty_worktree',
'reason' => sprintf('working tree dirty only from declared/generated artifact paths (%d files) - run artifact cleanup instead of force-removing the worktree', $dirty_count),
'dirty' => $dirty_count,
'hint' => 'Run studio wp datamachine-code workspace worktree cleanup-artifacts --dry-run to review reconstructable artifact cleanup; source edits are still protected by dirty_worktree.',
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields, array(
'artifact_dirty_paths' => $artifact_dirty['paths'],
'artifacts' => $artifact_dirty['artifacts'],
'artifact_size_bytes' => $artifact_dirty['artifact_size_bytes'],
'size_bytes' => max( (int) ( $disk_fields['size_bytes'] ?? 0 ), (int) $artifact_dirty['artifact_size_bytes'] ),
'estimated_size_bytes' => max( (int) ( $disk_fields['estimated_size_bytes'] ?? 0 ), (int) $artifact_dirty['artifact_size_bytes'] ),
)
);
continue;
}
// Before falling through to the generic dirty_worktree skip, try to
// classify whether this is the "merged PR + obsolete dirty edits"
// shape. That bucket is still skipped (force=false stays safe), but
// the distinct reason_code lets reviewers spot it as a safe
// force-cleanup candidate without manual archaeology.
$obsolete_dirty = $this->classify_dirty_obsolete_on_default_branch(
$repo,
$branch,
$wt_path,
$skip_github,
$github_cache,
$fetched,
$fetch_timeouts,
$metadata,
$include_repaired_metadata
);
if ( is_array($obsolete_dirty) ) {
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'merged_pr_with_only_obsolete_dirty_changes',
'reason' => sprintf(
'merged branch with %d dirty file(s); all dirty paths already absent on default branch — safe force-cleanup candidate (review then rerun with force=true)',
$dirty_count
),
'dirty' => $dirty_count,
'dirty_obsolete_paths' => $obsolete_dirty['paths'],
'merge_signal' => $obsolete_dirty['merge_signal'],
'pr_url' => $obsolete_dirty['pr_url'] ?? null,
'default_ref' => $obsolete_dirty['default_ref'],
'hint' => 'Dirty edits only touch paths the default branch no longer has. After review, rerun cleanup with force=true to remove this worktree.',
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields
);
continue;
}
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'dirty_worktree',
'reason' => sprintf('working tree dirty (%d files) — pass force=true to override', $dirty_count),
'dirty' => $dirty_count,
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields
);
continue;
}
// Hard stop: worktrees with local commits the remote hasn't seen.
// Upstream may be "gone" because a human manually deleted the
// remote branch without merging — nuking the worktree would lose
// those commits. `force` does NOT override this: data loss is a
// harder problem than dirty-file loss, and this guard is cheap.
$unpushed = $this->count_unpushed_commits($wt_path, self::CLEANUP_GIT_PROBE_TIMEOUT);
if ( is_wp_error($unpushed) ) {
$skipped[] = $this->build_worktree_probe_failure_skip($handle, $repo, $branch, $wt_path, $created_at, $metadata, $disk_fields, $unpushed);
continue;
}
if ( $unpushed > 0 ) {
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'unpushed_commits',
'reason' => sprintf('%d unpushed commit(s) — refusing to delete even with force (push or reset explicitly)', $unpushed),
'unpushed' => $unpushed,
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields
);
continue;
}
$primary_path = $this->get_primary_path($repo);
if ( ! is_dir($primary_path . '/.git') ) {
$skipped[] = array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'missing_metadata',
'reason' => 'primary checkout missing',
'hint' => 'Run workspace worktree prune if this is a stale registry entry; inspect manually if the path still exists.',
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields
);
continue;
}
if ( isset($fetch_timeouts[ $repo ]) ) {
$skipped[] = $this->build_worktree_probe_failure_skip($handle, $repo, $branch, $wt_path, $created_at, $metadata, $disk_fields, $fetch_timeouts[ $repo ]);
continue;
}
if ( empty($fetched[ $repo ]) ) {
$fetch = $this->run_git($primary_path, 'fetch --prune --quiet origin', self::CLEANUP_GIT_PROBE_TIMEOUT);
if ( is_wp_error($fetch) && $this->is_git_timeout_error($fetch) ) {
$fetch_timeouts[ $repo ] = $fetch;
$skipped[] = $this->build_worktree_probe_failure_skip($handle, $repo, $branch, $wt_path, $created_at, $metadata, $disk_fields, $fetch);
continue;
}
$fetched[ $repo ] = true;
}
$signal = is_array($metadata) ? WorktreeCleanupSignal::from_metadata($metadata, $include_repaired_metadata) : null;
if ( null === $signal ) {
$signal = $this->detect_merge_signal($primary_path, $repo, $branch, $skip_github, $github_cache);
}
$classification = WorktreeCleanupCandidateClassifier::classify_merge_signal_path(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'dirty_count' => $dirty_count,
'created_at' => $created_at,
'liveness' => $liveness,
'metadata' => $metadata,
'disk_fields' => $disk_fields,
),
$signal,
$age_filter,
fn() => $this->build_no_merge_signal_evidence($primary_path, $branch, $skip_github),
$this->build_active_no_signal_next_commands(25, 0)
);
if ( 'candidate' === $classification['type'] ) {
$candidates[] = $classification['row'];
continue;
}
$skipped[] = $classification['row'];
}
$candidates = $this->dedupe_worktree_cleanup_rows($candidates);
$skipped = $this->dedupe_worktree_cleanup_rows($skipped);
$candidates = $this->sort_worktree_cleanup_rows($candidates, $sort);
if ( null !== $planned_candidates ) {
$scoped = $this->scope_worktree_cleanup_to_plan($planned_candidates, $candidates, $skipped);
$candidates = $scoped['candidates'];
$skipped = $scoped['skipped'];
}
$summary = $this->build_worktree_cleanup_summary($candidates, array(), $skipped, $age_filter);
$pagination = $this->build_worktree_cleanup_pagination($offset, $limit, $processed, $total_worktrees, $budget_stopped, $budget_context);
if ( null !== $pagination ) {
$summary['pagination'] = $pagination;
}
if ( $dry_run ) {
$this->emit_worktree_cleanup_progress($progress, 'done', '', $checked, $total_worktrees, $candidates, $skipped, $removed_count, $started_at);
$result = array(
'success' => true,
'dry_run' => true,
'candidates' => $candidates,
'removed' => array(),
'skipped' => $skipped,
'summary' => $summary,
);
if ( null !== $pagination ) {
$result['pagination'] = $pagination;
}
if ( null !== $budget_context ) {
$result['evidence'] = array(
'elapsed_ms' => (int) round(( microtime(true) - $started_at ) * 1000),
'budget' => $this->summarize_worktree_loop_budget_context($budget_context, $budget_stopped),
);
}
return $result;
}
$removed = array();
foreach ( $candidates as $cand ) {
$this->emit_worktree_cleanup_progress($progress, 'removing', (string) ( $cand['handle'] ?? '' ), $checked, count($worktrees), $candidates, $skipped, $removed_count, $started_at);
$remove = WorkspaceMutationLock::with_repo(
$this->workspace_path,
$cand['repo'],
function () use ( $cand, $force, $remove_timeout_seconds ) {
$remove = $this->remove_worktree_by_path($cand['repo'], $cand['branch'], $cand['path'], $force, $remove_timeout_seconds);
if ( is_wp_error($remove) ) {
return $remove;
}
// Delete the now-detached local branch while the repo lock still covers
// shared git metadata.
$primary_path = $this->get_primary_path($cand['repo']);
if ( '' === (string) ( $cand['branch'] ?? '' ) ) {
return $remove;
}
$branch = $this->run_git($primary_path, sprintf('branch -D %s', escapeshellarg($cand['branch'])), self::CLEANUP_GIT_PROBE_TIMEOUT);
return is_wp_error($branch) ? $branch : $remove;
}
);
if ( is_wp_error($remove) ) {
$skipped[] = $this->build_worktree_remove_failure_skip($cand, $remove, $remove_timeout_seconds);
continue;
}
$removed[] = array_merge(
$cand,
array(
'removed_path' => (string) ( $cand['path'] ?? '' ),
'path_exists_after' => is_dir( (string) ( $cand['path'] ?? '' ) ),
)
);
++$removed_count;
}
// Final sweep to drop any remaining registry entries.
$this->worktree_prune();
$this->emit_worktree_cleanup_progress($progress, 'done', '', $checked, $total_worktrees, $candidates, $skipped, $removed_count, $started_at);
return array(
'success' => true,
'dry_run' => false,
'candidates' => $candidates,
'removed' => $removed,
'skipped' => $skipped,
'summary' => $this->build_worktree_cleanup_summary($candidates, $removed, $skipped, $age_filter),
);
}
/**
* Build pagination evidence for bounded full cleanup dry-runs.
*
* @param int $offset Inventory offset for this page.
* @param int|null $limit Optional page size.
* @param int $processed Rows consumed from this page.
* @param int $total Total non-primary worktrees.
* @param bool $budget_stopped Whether the budget stopped the scan early.
* @param array|null $budget_context Optional budget context.
* @return array<string,mixed>|null
*/
private function build_worktree_cleanup_pagination( int $offset, ?int $limit, int $processed, int $total, bool $budget_stopped, ?array $budget_context ): ?array {
if ( 0 === $offset && null === $limit && null === $budget_context ) {
return null;
}
$next_offset = ( $offset + $processed ) < $total ? $offset + $processed : null;
$command = null;
if ( null !== $next_offset ) {
$parts = array(
'studio wp datamachine-code workspace worktree cleanup --dry-run',
null === $limit ? null : '--limit=' . $limit,
'--offset=' . $next_offset,
null === $budget_context ? null : '--until-budget=' . (string) ( $budget_context['label'] ?? '' ),
'--format=json',
);
$command = implode(' ', array_values(array_filter($parts, fn( $part ) => null !== $part)));
}
return array(
'total' => $total,
'offset' => $offset,
'limit' => $limit,
'scanned' => $processed,
'partial' => null !== $next_offset,
'complete' => null === $next_offset,
'next_offset' => $next_offset,
'next_command' => $command,
'budget_stopped' => $budget_stopped,
);
}
/**
* Collapse duplicate cleanup rows emitted by overlapping inventory/git sources.
*
* @param array<int,array<string,mixed>> $rows Cleanup rows.
* @return array<int,array<string,mixed>>
*/
private function dedupe_worktree_cleanup_rows( array $rows ): array {
$seen = array();
$result = array();
foreach ( $rows as $row ) {
$key = implode('|', array(
(string) ( $row['handle'] ?? '' ),
(string) ( $row['path'] ?? '' ),
(string) ( $row['reason_code'] ?? $row['signal'] ?? '' ),
));
if ( isset($seen[ $key ]) ) {
continue;
}
$seen[ $key ] = true;
$result[] = $row;
}
return $result;
}
/**
* Find workspace-local managed directories whose .git file points at missing worktree metadata.
*
* @param array<int,array<string,mixed>> $listed_worktrees Rows already returned by git worktree list.
* @return array<int,array<string,mixed>>
*/
private function discover_broken_orphan_worktree_markers( array $listed_worktrees ): array {
$known = array();
foreach ( $listed_worktrees as $row ) {
$handle = (string) ( $row['handle'] ?? '' );
$path = (string) ( $row['path'] ?? '' );
if ( '' !== $handle ) {
$known[ $handle ] = true;
}
if ( '' !== $path ) {
$known[ rtrim($path, '/') ] = true;
}
}
if ( ! is_dir($this->workspace_path) ) {
return array();
}
$entries = scandir($this->workspace_path);
if ( false === $entries ) {
return array();
}
$rows = array();
foreach ( $entries as $entry ) {
if ( '.' === $entry || '..' === $entry || ! str_contains($entry, '@') || isset($known[ $entry ]) ) {
continue;
}
$parsed = $this->parse_handle($entry);
if ( empty($parsed['is_worktree']) || '' === (string) $parsed['repo'] ) {
continue;
}
$path = rtrim($this->workspace_path, '/') . '/' . $entry;
if ( isset($known[ $path ]) || ! is_dir($path) ) {
continue;
}
$broken = $this->classify_broken_orphan_worktree_marker($path);
if ( null === $broken ) {
continue;
}
$repo = (string) $parsed['repo'];
$metadata = WorktreeContextInjector::get_metadata($entry);
$created_at = is_array($metadata) ? ( $metadata['created_at'] ?? null ) : null;
$liveness = WorktreeContextInjector::classify_liveness(is_array($metadata) ? $metadata : null);
$disk = array(
'size_bytes' => null,
'estimated_size_bytes' => null,
'last_touched_at' => $this->detect_worktree_last_touched_at($path, is_array($metadata) ? $metadata : null, is_string($created_at) ? $created_at : null),
'age_days' => $this->calculate_age_days(is_string($created_at) ? $created_at : null),
'artifacts' => array(),
'artifact_size_bytes' => 0,
);
$rows[] = array_merge(
array(
'handle' => $entry,
'repo' => $repo,
'is_worktree' => true,
'is_primary' => false,
'external' => false,
'branch_slug' => $parsed['branch_slug'] ?? null,
'branch' => '',
'head' => '',
'path' => $path,
'dirty' => null,
'created_at' => $created_at,
'lifecycle_state' => is_array($metadata) ? ( $metadata['lifecycle_state'] ?? null ) : null,
'liveness' => $liveness['liveness'],
'liveness_reason' => $liveness['reason'],
'metadata' => $metadata,
'broken_orphan_marker' => true,
'broken_target_path' => $broken['gitdir'],
),
$disk
);
}
return $rows;
}
/**
* Return broken gitdir evidence when a worktree marker targets missing metadata.
*
* @return array{gitdir:string}|null
*/
private function classify_broken_orphan_worktree_marker( string $path ): ?array {
$marker = rtrim($path, '/') . '/.git';
if ( ! is_file($marker) ) {
return null;
}
$contents = file_get_contents($marker); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reads a local .git marker.
if ( false === $contents || ! preg_match('/^gitdir:\s*(.+)$/mi', $contents, $matches) ) {
return null;
}
$gitdir = trim($matches[1]);
if ( '' === $gitdir ) {
return null;
}
if ( ! str_starts_with($gitdir, '/') ) {
$gitdir = rtrim($path, '/') . '/' . $gitdir;
}
$normalized = str_replace('\\', '/', $gitdir);
if ( ! str_contains($normalized, '/.git/worktrees/') || file_exists($gitdir) ) {
return null;
}
return array( 'gitdir' => $gitdir );
}
/**
* Emit a bounded cleanup progress event for human CLI callers.
*
* @param callable|null $callback Progress callback.
* @param string $event Event name.
* @param string $handle Current worktree handle.
* @param int $checked Checked worktree count.
* @param int $total Total worktree count.
* @param array $candidates Candidate rows.
* @param array $skipped Skipped rows.
* @param int $removed_count Removed count.
* @param float $started_at Start timestamp from microtime(true).
* @return void
*/
private function emit_worktree_cleanup_progress( ?callable $callback, string $event, string $handle, int $checked, int $total, array $candidates, array $skipped, int $removed_count, float $started_at ): void {
if ( null === $callback ) {
return;
}
$callback(
array(
'event' => $event,
'handle' => $handle,
'checked' => $checked,
'total' => $total,
'candidates' => count($candidates),
'skipped' => count($skipped),
'removed' => $removed_count,
'elapsed' => round(max(0, microtime(true) - $started_at), 1),
)
);
}
/**
* Build a standard cleanup skip row for failed safety probes.
*
* @param string $handle Worktree handle.
* @param string $repo Repo name.
* @param string $branch Branch name.
* @param string $path Worktree path.
* @param mixed $created_at Created timestamp.
* @param mixed $metadata Worktree metadata.
* @param array $disk_fields Disk summary fields.
* @param \WP_Error $error Probe error.
* @return array<string,mixed>
*/
private function build_worktree_probe_failure_skip( string $handle, string $repo, string $branch, string $path, mixed $created_at, mixed $metadata, array $disk_fields, \WP_Error $error ): array {
$diagnostic = $this->classify_worktree_git_probe_failure($handle, $repo, $path, $error, 'cleanup safety probe', 'leaving in place');
return array_merge(
array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $path,
'created_at' => $created_at,
'metadata' => $metadata,
),
$diagnostic,
$disk_fields
);
}
/**
* Classify a failed git safety probe without weakening cleanup safety.
*
* @param string $handle Worktree handle.
* @param string $repo Repo name from the inventory row.
* @param string $path Worktree path.
* @param \WP_Error $error Probe error.
* @param string $probe_label Human-readable probe label.
* @param string $safety_outcome Human-readable safety outcome.
* @return array<string,mixed>
*/
private function classify_worktree_git_probe_failure( string $handle, string $repo, string $path, \WP_Error $error, string $probe_label, string $safety_outcome ): array {
$message = $error->get_error_message();
$error_code = $this->get_wp_error_code($error);
$error_data = $this->get_wp_error_data($error);
$output = is_array($error_data) ? (string) ( $error_data['output'] ?? '' ) : '';
$haystack = strtolower($message . "\n" . $output);
if ( $this->is_git_timeout_error($error) ) {
return array(
'reason_code' => 'probe_timeout',
'reason' => sprintf('%s timed out - %s: %s', $probe_label, $safety_outcome, $message),
'hint' => 'Retry after reducing cleanup scope or increasing the git probe timeout budget.',
'git_error_code' => $error_code,
);
}
$parsed = $this->parse_handle($handle);
if ( ! empty($parsed['is_worktree']) && '' !== $repo && $parsed['repo'] !== $repo ) {
return array(
'reason_code' => 'owner_repo_mismatch',
'reason' => sprintf('worktree handle repo (%s) does not match inventory repo (%s) - %s: %s', $parsed['repo'], $repo, $safety_outcome, $message),
'hint' => 'Run workspace worktree reconcile-metadata --dry-run --limit=25 --offset=0 --until-budget=30s --format=json to review stale registry ownership, then prune or repair the mismatched row.',
'handle_repo' => $parsed['repo'],
'inventory_repo' => $repo,
'git_error_code' => $error_code,
);
}
if ( str_contains($haystack, '/.git/worktrees/') || str_contains($haystack, '\\.git\\worktrees\\') ) {
return array(
'reason_code' => 'stale_worktree_marker',
'reason' => sprintf('git worktree metadata marker is stale or missing - %s: %s', $safety_outcome, $message),
'hint' => 'Inspect the worktree gitfile/common-dir and run git worktree prune or workspace worktree prune after confirming the row is stale.',
'git_error_code' => $error_code,
);
}
if (
str_contains($haystack, 'not a git repository')
|| str_contains($haystack, 'not a git worktree')
|| str_contains($haystack, 'invalid gitfile format')
|| str_contains($haystack, 'unable to read')
|| ( str_contains($haystack, 'no such file or directory') && str_contains($haystack, '.git') )
) {
return array(
'reason_code' => 'broken_worktree_metadata',
'reason' => sprintf('git worktree metadata is broken - %s: %s', $safety_outcome, $message),
'hint' => 'Inspect the worktree path and git metadata, then repair metadata or prune the stale registry entry before rerunning cleanup.',
'git_error_code' => $error_code,
);
}
return array(
'reason_code' => 'git_probe_failed',
'reason' => sprintf('%s failed - %s: %s', $probe_label, $safety_outcome, $message),
'hint' => 'Inspect the git probe error before rerunning cleanup; this was not an execution timeout.',
'git_error_code' => $error_code,
);
}
/**
* Get a WP_Error code across real WordPress and smoke-test stubs.
*
* @param \WP_Error $error Error object.
* @return string
*/
private function get_wp_error_code( \WP_Error $error ): string {
// @phpstan-ignore-next-line Smoke tests provide a minimal WP_Error stub.
return method_exists($error, 'get_error_code') ? (string) $error->get_error_code() : (string) ( $error->code ?? '' );
}
/**
* Get WP_Error data across real WordPress and smoke-test stubs.
*
* @param \WP_Error $error Error object.
* @return mixed
*/
private function get_wp_error_data( \WP_Error $error ): mixed {
// @phpstan-ignore-next-line Smoke tests provide a minimal WP_Error stub.
return method_exists($error, 'get_error_data') ? $error->get_error_data() : ( $error->data ?? null );
}
/**
* Operator-safe bounded cleanup apply restricted to explicit cleanup-eligible worktrees.
*
* Skips the slow paths (full git worktree discovery, GitHub lookups, full
* status/upstream sweep) and works only off cheap workspace inventory rows
* with explicit `cleanup_eligible` lifecycle metadata. Each candidate is
* revalidated at apply time — dirty/unpushed/missing-metadata/external/
* primary rows stay skipped even when the inventory said they were eligible.
*
* Bounds:
* - `limit` caps how many candidates this batch will attempt (default 25).
* - `older_than` optionally filters by lifecycle `created_at` age.
* - `via_jobs` schedules each candidate as its own `worktree_cleanup_chunk`
* job (single-row chunks) for resumable, async apply. Synchronous mode
* is the default so operators can apply now without an Action Scheduler
* run between batch and result.
*
* Evidence:
* - `processed`, `removed`, `skipped`, `bytes_reclaimed`.
* - `continuation` reports remaining cleanup-eligible handles not in this
* batch so the operator can keep going (next call without changes
* re-derives the same list cheaply).
*
* @param array $opts Options: dry_run, limit, older_than, sort, force, discard_unpushed, via_jobs, source.
* @return array<string,mixed>|\WP_Error
*/
public function worktree_bounded_cleanup_eligible_apply( array $opts = array() ): array|\WP_Error {
$started_at = microtime(true);
$dry_run = ! empty($opts['dry_run']);
$force = ! empty($opts['force']);
$discard_unpushed = ! empty($opts['discard_unpushed']);
$via_jobs = ! empty($opts['via_jobs']);
$include_repaired_metadata = ! empty($opts['include_repaired_metadata']);
$older_than = isset($opts['older_than']) ? trim( (string) $opts['older_than']) : '';
$sort = isset($opts['sort']) ? trim( (string) $opts['sort']) : 'age';
$source = isset($opts['source']) ? trim( (string) $opts['source']) : 'workspace_bounded_cleanup_eligible_apply';
$remove_timeout_seconds = $this->normalize_worktree_cleanup_remove_timeout($opts['remove_timeout'] ?? null);
if ( is_wp_error($remove_timeout_seconds) ) {
return $remove_timeout_seconds;
}
$limit = isset($opts['limit']) ? (int) $opts['limit'] : 25;
if ( $limit < 1 ) {
return new \WP_Error('invalid_bounded_cleanup_eligible_limit', 'Bounded cleanup-eligible apply limit must be a positive integer.', array( 'status' => 400 ));
}
// Hard ceiling keeps a single bounded batch genuinely bounded — operators
// who want more should run multiple batches or fall through to the full
// retention/job-backed path.
$limit = min($limit, 200);
if ( '' !== $sort && ! in_array($sort, array( 'size', 'age' ), true) ) {
return new \WP_Error('invalid_cleanup_sort', 'Invalid bounded cleanup-eligible apply sort. Use size or age.', array( 'status' => 400 ));
}
if ( $via_jobs && $dry_run ) {
return new \WP_Error('bounded_cleanup_eligible_apply_via_jobs_no_dry_run', 'Job-backed bounded cleanup-eligible apply cannot run as dry-run; use the synchronous dry-run path to review candidates first.', array( 'status' => 400 ));
}
// Reuse the cheap inventory_only review path for candidate discovery so