-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorkspace.php
More file actions
4114 lines (3717 loc) · 154 KB
/
Workspace.php
File metadata and controls
4114 lines (3717 loc) · 154 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
/**
* Agent Workspace
*
* Provides a managed directory for agent file operations — cloning repos,
* storing working files, etc. Lives outside the web root when possible
* for security.
*
* @package DataMachineCode\Workspace
* @since 0.31.0
*/
namespace DataMachineCode\Workspace;
use DataMachine\Core\FilesRepository\FilesystemHelper;
use DataMachineCode\Support\GitHubRemote;
use DataMachineCode\Support\GitRunner;
use DataMachineCode\Support\PathSecurity;
use DataMachineCode\Storage\WorktreeInventoryRepository;
defined( 'ABSPATH' ) || exit;
require_once __DIR__ . '/WorkspaceArtifactCleanup.php';
require_once __DIR__ . '/WorkspaceCleanupPlan.php';
require_once __DIR__ . '/WorkspaceGitOperations.php';
require_once __DIR__ . '/WorkspaceHygieneReport.php';
require_once __DIR__ . '/WorkspaceMetadataReconciliation.php';
require_once __DIR__ . '/WorkspaceRepositoryLifecycle.php';
require_once __DIR__ . '/WorkspaceWorktreeLifecycle.php';
require_once __DIR__ . '/WorkspaceWorktreeInventoryCleanup.php';
require_once __DIR__ . '/WorkspaceWorktreeEmergencyCleanup.php';
class Workspace {
use WorkspaceArtifactCleanup;
use WorkspaceCleanupPlan;
use WorkspaceGitOperations;
use WorkspaceHygieneReport;
use WorkspaceMetadataReconciliation;
use WorkspaceRepositoryLifecycle;
use WorkspaceWorktreeLifecycle;
use WorkspaceWorktreeInventoryCleanup;
use WorkspaceWorktreeEmergencyCleanup;
/**
* Maximum file size for reading (1 MB).
*/
const MAX_READ_SIZE = 1048576;
/**
* Bound GitHub cleanup checks so one slow repo cannot stall cleanup.
*/
private const CLEANUP_GITHUB_TIMEOUT = 5;
/**
* Bound per-worktree git cleanup probes so one wedged checkout cannot stall cleanup.
*/
private const CLEANUP_GIT_PROBE_TIMEOUT = 5;
/**
* Closed PR pages to inspect per repo during cleanup.
*/
private const CLEANUP_GITHUB_MAX_PAGES = 3;
/**
* Number of largest/oldest rows to expose in cleanup summaries.
*/
private const CLEANUP_SUMMARY_TOP_LIMIT = 10;
/**
* Default number of workspace entries to size in hygiene reports.
*/
private const HYGIENE_DEFAULT_SIZE_LIMIT = 1000;
/**
* Default cap on worktrees scanned for an artifact cleanup dry-run when no
* `limit` is provided. Keeps dry-run bounded and fast on huge workspaces.
*/
public const ARTIFACT_CLEANUP_DEFAULT_LIMIT = 100;
/**
* Default metadata reconciliation dry-run page size when pagination is used.
*/
private const METADATA_RECONCILE_DEFAULT_LIMIT = 100;
/**
* @var string Resolved workspace path.
*/
private string $workspace_path;
public function __construct() {
$this->workspace_path = self::resolve_workspace_directory();
}
/**
* Worktree inventory repository factory.
*/
private function worktree_inventory(): WorktreeInventoryRepository {
if ( ! class_exists( WorktreeInventoryRepository::class ) ) {
require_once dirname( __DIR__ ) . '/Storage/WorktreeInventoryRepository.php';
}
return new WorktreeInventoryRepository();
}
/**
* Resolve the workspace directory path.
*
* Priority:
* 1. DATAMACHINE_WORKSPACE_PATH constant (if defined)
* 2. /var/lib/datamachine/workspace (if writable — typical on VPS)
* 3. $HOME/.datamachine/workspace (local/macOS fallback)
* 4. sys_get_temp_dir()/datamachine/workspace (ephemeral CI/Playground fallback)
* 5. Empty string (no workspace available)
*
* @return string Workspace path or empty string if unavailable.
*/
private static function resolve_workspace_directory(): string {
if ( defined( 'DATAMACHINE_WORKSPACE_PATH' ) ) {
return rtrim( DATAMACHINE_WORKSPACE_PATH, '/' );
}
$system_path = '/var/lib/datamachine/workspace';
$system_base = dirname( $system_path );
$fs = FilesystemHelper::get();
$base_writable = $fs
? $fs->is_writable( $system_base )
: is_writable( $system_base ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
$parent_writable = ! $base_writable && ! file_exists( $system_base ) && (
$fs
? $fs->is_writable( dirname( $system_base ) )
: is_writable( dirname( $system_base ) ) // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
);
if ( $base_writable || $parent_writable ) {
return $system_path;
}
// Local/macOS fallback: $HOME/.datamachine/workspace.
// Matches the path setup.sh uses in --local mode.
$home = getenv( 'HOME' );
if ( false !== $home && '' !== $home ) {
$home_path = rtrim( $home, '/' ) . '/.datamachine/workspace';
$home_base = dirname( $home_path );
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
if ( is_dir( $home_base ) && is_writable( $home_base ) ) {
return $home_path;
}
// Base doesn't exist yet — check if $HOME/.datamachine can be created.
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
if ( ! file_exists( $home_base ) && is_writable( dirname( $home_base ) ) ) {
return $home_path;
}
}
$temp_path = rtrim( sys_get_temp_dir(), '/' ) . '/datamachine/workspace';
$temp_base = dirname( $temp_path );
$web_root = defined( 'ABSPATH' ) ? realpath( ABSPATH ) : false;
$temp_root = realpath( sys_get_temp_dir() );
if (
false !== $temp_root &&
( false === $web_root || 0 !== strpos( $temp_root . '/', rtrim( $web_root, '/' ) . '/' ) )
) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
if ( is_dir( $temp_base ) && is_writable( $temp_base ) ) {
return $temp_path;
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
if ( ! file_exists( $temp_base ) && is_writable( dirname( $temp_base ) ) ) {
return $temp_path;
}
}
return '';
}
/**
* Get the workspace base path.
*
* @return string
*/
public function get_path(): string {
return $this->workspace_path;
}
/**
* Inspect whether the configured workspace root is visible to PHP.
*
* @return array{path: string, configured: bool, is_dir: bool, is_readable: bool, scandir: string, readable: bool}
*/
public function inspect_workspace_path(): array {
$path = $this->workspace_path;
$is_dir = '' !== $path && is_dir( $path );
$is_readable = '' !== $path && is_readable( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_readable
$entries = ( $is_dir && $is_readable ) ? scandir( $path ) : false;
return array(
'path' => $path,
'configured' => defined( 'DATAMACHINE_WORKSPACE_PATH' ),
'is_dir' => $is_dir,
'is_readable' => $is_readable,
'scandir' => false === $entries ? 'failed' : 'ok',
'readable' => $is_dir && false !== $entries,
);
}
/**
* Require the configured workspace root to be visible before substrate checks.
*
* @return \WP_Error|null
*/
private function require_workspace_visible(): ?\WP_Error {
$diagnostic = $this->inspect_workspace_path();
if ( '' === $diagnostic['path'] ) {
return new \WP_Error(
'workspace_unavailable',
'Workspace unavailable: no writable path outside the web root. Define DATAMACHINE_WORKSPACE_PATH in wp-config.php, ensure /var/lib/datamachine/ is writable, ensure $HOME is set, or ensure the system temporary directory is writable.',
$this->workspace_visibility_error_data( $diagnostic )
);
}
if ( ! $diagnostic['is_dir'] ) {
if ( empty( $diagnostic['configured'] ) ) {
return null;
}
return new \WP_Error(
'workspace_path_invisible',
$this->format_workspace_visibility_message( $diagnostic ),
$this->workspace_visibility_error_data( $diagnostic )
);
}
if ( ! $diagnostic['readable'] ) {
return new \WP_Error(
'workspace_path_unreadable',
$this->format_workspace_visibility_message( $diagnostic ),
$this->workspace_visibility_error_data( $diagnostic )
);
}
return null;
}
/**
* Build error data for workspace visibility failures.
*
* @param array<string,mixed> $diagnostic Path visibility details.
* @return array{status: int, workspace: array<string,mixed>}
*/
private function workspace_visibility_error_data( array $diagnostic ): array {
return array(
'status' => 500,
'workspace' => $diagnostic,
);
}
/**
* Format a workspace visibility diagnostic for CLI/API callers.
*
* @param array<string,mixed> $diagnostic Path visibility details.
* @return string
*/
private function format_workspace_visibility_message( array $diagnostic ): string {
return sprintf(
'Workspace path is not accessible from PHP: %s (is_dir=%s, is_readable=%s, scandir=%s). If this is a Studio/local host path, ensure the path is mounted into the PHP runtime or update DATAMACHINE_WORKSPACE_PATH to a PHP-visible workspace.',
(string) ( $diagnostic['path'] ?? '' ),
! empty( $diagnostic['is_dir'] ) ? 'true' : 'false',
! empty( $diagnostic['is_readable'] ) ? 'true' : 'false',
(string) ( $diagnostic['scandir'] ?? 'failed' )
);
}
/**
* Get the full path to a workspace handle.
*
* Handles can be either a primary checkout (`<repo>`) or a worktree
* (`<repo>@<branch-slug>`). The directory name on disk equals the handle.
*
* @param string $handle Workspace handle (`<repo>` or `<repo>@<branch-slug>`).
* @return string Full filesystem path.
*/
public function get_repo_path( string $handle ): string {
$parsed = $this->parse_handle( $handle );
return $this->workspace_path . '/' . $parsed['dir_name'];
}
/**
* Parse a workspace handle into its components.
*
* Accepts either:
* - `<repo>` → primary checkout
* - `<repo>@<slug>` → worktree (slug = slugified branch name)
*
* @param string $handle Workspace handle.
* @return array{repo: string, branch_slug: string|null, is_worktree: bool, dir_name: string}
*/
public function parse_handle( string $handle ): array {
$handle = trim( $handle );
if ( str_contains( $handle, '@' ) ) {
$parts = explode( '@', $handle, 2 );
$repo = $this->sanitize_name( $parts[0] );
$slug = $this->sanitize_slug( $parts[1] );
if ( '' !== $repo && '' !== $slug ) {
return array(
'repo' => $repo,
'branch_slug' => $slug,
'is_worktree' => true,
'dir_name' => $repo . '@' . $slug,
);
}
}
$repo = $this->sanitize_name( $handle );
return array(
'repo' => $repo,
'branch_slug' => null,
'is_worktree' => false,
'dir_name' => $repo,
);
}
/**
* Convert a branch name to a filesystem-safe slug.
*
* Slashes become dashes (`fix/foo-bar` → `fix-foo-bar`). Anything else
* outside [A-Za-z0-9._-] is stripped.
*
* @param string $branch Branch name.
* @return string Slug (empty if branch is invalid).
*/
public function slugify_branch( string $branch ): string {
$branch = trim( $branch );
if ( '' === $branch ) {
return '';
}
$slug = str_replace( '/', '-', $branch );
return $this->sanitize_slug( $slug );
}
/**
* Sanitize a branch slug. Allows alphanumerics, dots, dashes, underscores.
*
* @param string $slug Raw slug.
* @return string
*/
private function sanitize_slug( string $slug ): string {
$slug = preg_replace( '/[^a-zA-Z0-9._-]/', '', $slug );
// Collapse runs of dashes for readability.
$slug = preg_replace( '/-{2,}/', '-', (string) $slug );
return trim( (string) $slug, '-.' );
}
/**
* Get the primary checkout path for a repo.
*
* @param string $repo Repository name (no @-suffix).
* @return string
*/
public function get_primary_path( string $repo ): string {
return $this->workspace_path . '/' . $this->sanitize_name( $repo );
}
/**
* Ensure the workspace directory exists with correct permissions.
*
* @return array{success: bool, path: string, created?: bool}|\WP_Error
*/
public function ensure_exists(): array|\WP_Error {
$path = $this->workspace_path;
if ( '' === $path ) {
$visible = $this->require_workspace_visible();
return null !== $visible ? $visible : new \WP_Error( 'workspace_unavailable', 'Workspace unavailable: no writable path outside the web root.', array( 'status' => 500 ) );
}
if ( is_dir( $path ) ) {
$visible = $this->require_workspace_visible();
if ( null !== $visible ) {
return $visible;
}
return array(
'success' => true,
'path' => $path,
'created' => false,
);
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
$created = wp_mkdir_p( $path );
if ( ! $created ) {
return new \WP_Error( 'workspace_create_failed', sprintf( 'Failed to create workspace directory: %s', $path ), array( 'status' => 500 ) );
}
// Set permissions for multi-user access (web server group).
$this->ensure_group_permissions( $path );
// Add .htaccess to block web access if inside web root.
$this->protect_directory( $path );
return array(
'success' => true,
'path' => $path,
'created' => true,
);
}
// =========================================================================
// Worktree operations
// =========================================================================
/**
* 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 merge 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.
*
* Signal (a) is 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{
* success: bool,
* dry_run: bool,
* candidates: array<int,array>,
* removed: array<int,array>,
* skipped: array<int,array>,
* }|\WP_Error
*/
public function worktree_cleanup_merged( array $opts = array() ): array|\WP_Error {
$dry_run = ! empty( $opts['dry_run'] );
$force = ! empty( $opts['force'] );
$skip_github = ! empty( $opts['skip_github'] );
$inventory_only = ! empty( $opts['inventory_only'] );
$include_repaired_metadata = ! empty( $opts['include_repaired_metadata'] );
$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;
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 );
}
$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;
}
$age_filter = null;
if ( '' !== $older_than ) {
$duration_seconds = $this->parse_worktree_cleanup_duration( $older_than );
if ( is_wp_error( $duration_seconds ) ) {
return $duration_seconds;
}
$threshold_ts = time() - $duration_seconds;
$age_filter = array(
'type' => 'older_than',
'older_than' => $older_than,
'duration_seconds' => $duration_seconds,
'threshold' => gmdate( 'c', $threshold_ts ),
'threshold_unix' => $threshold_ts,
'excluded' => 0,
'unknown_age' => 0,
);
}
$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();
$github_cache = array();
$all_worktrees = array_values( array_filter( (array) $listing['worktrees'], fn( $wt ) => empty( $wt['is_primary'] ) ) );
$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.
$fetched = array();
$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;
$disk_fields = $this->extract_worktree_disk_fields( $wt );
$primary_path = '' !== $repo ? $this->get_primary_path( $repo ) : '';
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 ( '' === $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,
'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 ( in_array( $branch, $protected_branches, true ) ) {
$skipped[] = array_merge( array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'protected_branch',
'reason' => sprintf( 'protected branch (%s)', $branch ),
'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_timeout_skip( $handle, $repo, $branch, $wt_path, $created_at, $metadata, $disk_fields, $dirty_probe );
continue;
}
$dirty_count = (int) $dirty_probe;
if ( $dirty_count > 0 && ! $force ) {
// 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'] ?? null,
'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_timeout_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_timeout_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 ( $this->is_git_timeout_error( $fetch ) ) {
$fetch_timeouts[ $repo ] = $fetch;
$skipped[] = $this->build_worktree_probe_timeout_skip( $handle, $repo, $branch, $wt_path, $created_at, $metadata, $disk_fields, $fetch );
continue;
}
$fetched[ $repo ] = true;
}
$signal = null;
if ( is_array( $metadata ) && WorktreeContextInjector::has_cleanup_signal( $metadata ) ) {
$signal = array(
'signal' => 'cleanup_eligible',
'reason' => 'worktree finalized or explicitly marked cleanup_eligible',
);
if ( ! empty( $metadata['pr_url'] ) ) {
$signal['pr_url'] = (string) $metadata['pr_url'];
}
} elseif ( $include_repaired_metadata && is_array( $metadata ) && ! empty( $metadata['metadata_repaired'] ) ) {
$signal = array(
'signal' => 'repaired_metadata',
'reason' => 'operator-approved cleanup of repaired metadata',
);
} else {
$signal = $this->detect_merge_signal( $primary_path, $repo, $branch, $skip_github, $github_cache );
}
if ( null === $signal ) {
$skipped[] = array_merge( array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'no_merge_signal',
'reason' => 'no merge signal — leaving in place',
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields );
continue;
}
if ( 'probe-timeout' === ( $signal['signal'] ?? '' ) ) {
$skipped[] = array_merge( array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'probe_timeout',
'reason' => $signal['reason'],
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields );
continue;
}
if ( 'github-unknown' === ( $signal['signal'] ?? '' ) ) {
$skipped[] = array_merge( array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'github_unknown',
'reason' => $signal['reason'],
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields );
continue;
}
$age_decision = null;
if ( null !== $age_filter ) {
$created_ts = is_string( $created_at ) && '' !== $created_at ? strtotime( $created_at ) : false;
if ( false === $created_ts ) {
++$age_filter['unknown_age'];
$skipped[] = array_merge( array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'unknown_age',
'reason' => 'missing or invalid created_at metadata - age filter cannot decide safely',
'created_at' => $created_at,
'metadata' => $metadata,
'age_filter' => array(
'type' => 'older_than',
'older_than' => $age_filter['older_than'],
'threshold' => $age_filter['threshold'],
'decision' => 'unknown_age',
),
), $disk_fields );
continue;
}
$age_seconds = time() - $created_ts;
$age_decision = array(
'type' => 'older_than',
'older_than' => $age_filter['older_than'],
'threshold' => $age_filter['threshold'],
'created_at' => $created_at,
'age_seconds' => $age_seconds,
);
if ( $created_ts > $age_filter['threshold_unix'] ) {
++$age_filter['excluded'];
$skipped[] = array_merge( array(
'handle' => $handle,
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'reason_code' => 'age_filter',
'reason' => sprintf( 'created_at %s is newer than --older-than=%s threshold %s', $created_at, $age_filter['older_than'], $age_filter['threshold'] ),
'created_at' => $created_at,
'metadata' => $metadata,
'age_filter' => array_merge( $age_decision, array( 'decision' => 'excluded' ) ),
), $disk_fields );
continue;
}
$age_decision['decision'] = 'included';
}
$candidate = array_merge( array(
'handle' => $wt['handle'],
'repo' => $repo,
'branch' => $branch,
'path' => $wt_path,
'dirty' => $dirty_count,
'signal' => $signal['signal'],
'reason_code' => $signal['signal'],
'reason' => $signal['reason'],
'pr_url' => $signal['pr_url'] ?? null,
'created_at' => $created_at,
'metadata' => $metadata,
), $disk_fields );
if ( null !== $age_decision ) {
$candidate['age_filter'] = $age_decision;
}
$candidates[] = $candidate;
}
$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 = $this->remove_worktree_by_path( $cand['repo'], $cand['branch'], $cand['path'], $force );
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'] );
$branch = $this->run_git( $primary_path, sprintf( 'branch -D %s', escapeshellarg( $cand['branch'] ) ) );
return is_wp_error( $branch ) ? $branch : $remove;
}
);
if ( is_wp_error( $remove ) ) {
$skipped[] = array(
'handle' => $cand['handle'],
'repo' => $cand['repo'] ?? '',
'branch' => $cand['branch'] ?? '',
'path' => $cand['path'] ?? '',
'reason_code' => 'remove_failed',
'reason' => 'remove failed: ' . $remove->get_error_message(),
'created_at' => $cand['created_at'] ?? null,
'metadata' => $cand['metadata'] ?? null,
'size_bytes' => $cand['size_bytes'] ?? null,
);
continue;
}
$removed[] = $cand;
++$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;
}