-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorkspaceCommand.php
More file actions
5640 lines (5169 loc) · 200 KB
/
Copy pathWorkspaceCommand.php
File metadata and controls
5640 lines (5169 loc) · 200 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
/**
* WP-CLI Workspace Command
*
* Provides CLI access to the agent workspace — a managed directory
* for cloning repos and working with files outside the web root.
*
* Commands delegate to the same services as WordPress Abilities API primitives.
* The CLI layer handles argument parsing, confirmation prompts, and output
* formatting only.
*
* @package DataMachineCode\Cli\Commands
* @since 0.1.0
*/
namespace DataMachineCode\Cli\Commands;
use WP_CLI;
use DataMachine\Cli\BaseCommand;
use DataMachineCode\Cleanup\CleanupRunEvidenceStoreInterface;
use DataMachineCode\Cleanup\DataMachineJobCleanupRunEvidenceStore;
use DataMachineCode\Workspace\Workspace;
use DataMachineCode\Workspace\WorktreeContextInjector;
use DataMachineCode\Workspace\WorkspaceMutationLock;
defined('ABSPATH') || exit;
class WorkspaceCommand extends BaseCommand {
private const CLEANUP_CLI_SOURCE = 'workspace_cleanup_cli';
private const CLEANUP_MODES = array( 'inventory', 'artifacts', 'retention', 'emergency' );
private ?CleanupRunEvidenceStoreInterface $cleanup_run_evidence_store = null;
/**
* Show the workspace directory path.
*
* Displays the resolved workspace path. The path is determined by:
* 1. DATAMACHINE_WORKSPACE_PATH constant (if defined)
* 2. /var/lib/datamachine/workspace (if writable — VPS)
* 3. $HOME/.datamachine-code/workspace (local/macOS)
*
* ## OPTIONS
*
* [--ensure]
* : Create the directory if it doesn't exist.
*
* ## EXAMPLES
*
* # Show workspace path
* wp datamachine-code workspace path
*
* # Show path and create if missing
* wp datamachine-code workspace path --ensure
*
* @subcommand path
*/
public function path( array $args, array $assoc_args ): void {
$ability = wp_get_ability('datamachine-code/workspace-path');
if ( ! $ability ) {
WP_CLI::error('Workspace path ability not available.');
return;
}
$result = $ability->execute(
array(
'ensure' => ! empty($assoc_args['ensure']),
)
);
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
if ( ! empty($result['created']) ) {
WP_CLI::success(sprintf('Created workspace: %s', $result['path']));
return;
}
WP_CLI::log($result['path']);
if ( empty($result['exists']) && empty($assoc_args['ensure']) ) {
WP_CLI::warning('Directory does not exist yet. Use --ensure to create it.');
}
}
/**
* List repositories in the workspace.
*
* ## OPTIONS
*
* [--repo=<repo>]
* : Filter by primary repository name. Includes the primary checkout and its worktrees.
*
* [--type=<type>]
* : Filter by checkout type.
* ---
* options:
* - primary
* - worktree
* ---
*
* [--format=<format>]
* : Output format.
* ---
* default: table
* options:
* - table
* - json
* - csv
* - yaml
* ---
*
* ## EXAMPLES
*
* # List workspace repos
* wp datamachine-code workspace list
*
* # List as JSON
* wp datamachine-code workspace list --format=json
*
* # List one primary checkout and its worktrees
* wp datamachine-code workspace list --repo=my-plugin
*
* # List only worktrees for one primary checkout
* wp datamachine-code workspace list --repo=my-plugin --type=worktree --format=json
*
* @subcommand list
*/
public function list_repos( array $args, array $assoc_args ): void {
$ability = wp_get_ability('datamachine-code/workspace-list');
if ( ! $ability ) {
WP_CLI::error('Workspace list ability not available.');
return;
}
$input = array();
if ( isset($assoc_args['repo']) ) {
$input['repo'] = (string) $assoc_args['repo'];
}
if ( isset($assoc_args['type']) ) {
$input['type'] = (string) $assoc_args['type'];
}
$result = $ability->execute($input);
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
if ( empty($result['repos']) ) {
if ( isset($assoc_args['repo']) ) {
WP_CLI::log(sprintf('No repos matching "%s" in workspace (%s).', (string) $assoc_args['repo'], $result['path'] ?? ''));
return;
}
WP_CLI::log(sprintf('No repos in workspace (%s).', $result['path'] ?? ''));
WP_CLI::log('Clone one with: wp datamachine-code workspace clone <url>');
return;
}
$items = array_map(
function ( $repo ) {
$freshness = is_array($repo['primary_freshness'] ?? null) ? $repo['primary_freshness'] : null;
return array(
'name' => $repo['name'],
'kind' => ! empty($repo['is_worktree']) ? 'worktree' : 'primary',
'repo' => $repo['repo'] ?? $repo['name'],
'branch' => $repo['branch'] ?? '-',
'freshness' => is_array($freshness) ? (string) ( $freshness['status'] ?? '-' ) : '-',
'behind' => is_array($freshness) && null !== ( $freshness['behind'] ?? null ) ? (string) $freshness['behind'] : '-',
'remote' => $repo['remote'] ?? '-',
'git' => $repo['git'] ? 'yes' : 'no',
'path' => $repo['path'],
);
},
$result['repos']
);
$this->format_items(
$items,
array( 'name', 'kind', 'repo', 'branch', 'freshness', 'behind', 'remote', 'git' ),
$assoc_args,
'name'
);
}
/**
* Clone a git repository into the workspace.
*
* ## OPTIONS
*
* <url>
* : Git repository URL to clone.
*
* [--name=<name>]
* : Directory name in workspace (derived from URL if omitted).
*
* [--full]
* : Disable the default blobless partial clone (`--filter=blob:none`). Useful for servers that do not support partial clone or when all blobs are needed immediately.
*
* [--allow-duplicate-remote]
* : Explicitly allow cloning a second top-level primary for a remote already present in the workspace. Use only for deliberate release/proof checkouts.
*
* ## EXAMPLES
*
* # Clone a repo
* wp datamachine-code workspace clone https://github.com/example/my-plugin.git
*
* # Clone with custom name
* wp datamachine-code workspace clone https://github.com/example/my-plugin.git --name=my-plugin-dev
*
* @subcommand clone
*/
public function clone_repo( array $args, array $assoc_args ): void {
if ( empty($args[0]) ) {
WP_CLI::error('Repository URL is required.');
return;
}
$workspace = new Workspace();
$result = $workspace->clone_repo(
$args[0],
$assoc_args['name'] ?? null,
array(
'full' => isset($assoc_args['full']),
'allow_duplicate_remote' => isset($assoc_args['allow-duplicate-remote']),
'progress_callback' => static function ( array $event ): void {
$elapsed = number_format( (float) ( $event['elapsed'] ?? 0 ), 1);
WP_CLI::log(sprintf('[clone %ss] %s', $elapsed, (string) ( $event['message'] ?? '' )));
},
)
);
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
WP_CLI::success( (string) ( $result['message'] ?? 'Repository cloned.' ));
WP_CLI::log(sprintf('Path: %s', (string) ( $result['path'] ?? '' )));
}
/**
* Adopt an existing primary checkout already under the workspace root.
*
* ## OPTIONS
*
* <path>
* : Existing git primary checkout path to adopt.
*
* [--name=<name>]
* : Workspace name (derived from path basename if omitted).
*
* ## EXAMPLES
*
* wp datamachine-code workspace adopt /Users/chubes/Developer/my-plugin --name=my-plugin
*
* @subcommand adopt
*/
public function adopt_repo( array $args, array $assoc_args ): void {
if ( empty($args[0]) ) {
WP_CLI::error('Checkout path is required.');
return;
}
$ability = wp_get_ability('datamachine-code/workspace-adopt');
if ( ! $ability ) {
WP_CLI::error('Workspace adopt ability not available.');
return;
}
$input = array( 'path' => $args[0] );
if ( ! empty($assoc_args['name']) ) {
$input['name'] = $assoc_args['name'];
}
$result = $ability->execute($input);
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
WP_CLI::success($result['message']);
WP_CLI::log(sprintf('Name: %s', $result['name']));
WP_CLI::log(sprintf('Path: %s', $result['path']));
}
/**
* Control task-backed workspace cleanup runs.
*
* This is the high-level operator surface for cleanup. Destructive runs are
* scheduled through Data Machine's system-task scheduler and return immediately
* with a run_id. Status, resume, cancel, and evidence commands take that run_id.
* Dry-runs stay synchronous and delegate to the same workspace abilities as the
* lower-level `workspace worktree cleanup*` commands until DB-backed cleanup
* plans land.
*
* ## OPTIONS
*
* <operation>
* : Cleanup operation. One of: <plan|apply|run|status|resume|cancel|evidence>.
* Existing task-backed controls remain: <run|status|resume|cancel|evidence>.
*
* [<run-id>]
* : Run identifier returned by `plan` or `run`. DB-backed plan IDs look like
* cleanup-run-<timestamp>-<nonce>; job-backed run IDs may be cleanup-run-<job_id>.
*
* [--mode=<mode>]
* : Cleanup mode for `run`.
* ---
* default: retention
* options:
* - inventory
* - metadata
* - artifacts
* - retention
* - emergency
* ---
*
* [--dry-run]
* : Run the selected cleanup review synchronously through workspace abilities.
*
* [--force]
* : Pass force=true into the cleanup task params for modes that support it.
*
* [--older-than=<duration>]
* : Pass an age gate such as 7d or 24h into cleanup task params.
*
* [--limit=<count>]
* : For DB-backed `apply` / `resume`, maximum pending rows to process in this
* invocation (default 25, max 100). For `--mode=artifacts` pages, maximum
* worktrees to scan; dry-run reviews scan this bounded page synchronously,
* and apply runs freeze eligible candidates from the same bounded page.
* Artifact page scans default to 100. Use 0 to disable the artifact scan cap
* (combine with --exhaustive for a full audit).
*
* [--offset=<count>]
* : Pagination offset (0-indexed) for `--mode=artifacts` dry-run and apply
* pages. Walk huge workspaces by feeding the previous response's
* `pagination.next_offset` until `pagination.complete` is true.
*
* [--exhaustive]
* : For `--mode=artifacts --dry-run`, scan every worktree AND run per-worktree
* git status / unpushed-commit safety probes. Slow on huge workspaces; use
* sparingly for full audits.
*
* [--safety-probes]
* : For `--mode=artifacts --dry-run`, run the per-worktree git safety probes
* without disabling the bounded scan. Useful when you want a small slice
* audited with full safety information.
*
* [--verbose]
* : Include full diagnostic child job ID lists in task-backed cleanup status output.
*
* [--format=<format>]
* : Output format.
* ---
* default: table
* options:
* - table
* - json
* - yaml
* ---
*
* ## EXAMPLES
*
* # Create a DB-backed cleanup plan for review
* wp datamachine-code workspace cleanup plan --mode=retention
*
* # Apply a reviewed DB-backed run
* wp datamachine-code workspace cleanup apply cleanup-run-20260504120000-abc123
*
* # Start task-backed retention cleanup and capture the returned run_id
* wp datamachine-code workspace cleanup run --mode=retention
*
* # Review artifact cleanup synchronously (bounded; default limit=100)
* wp datamachine-code workspace cleanup run --mode=artifacts --dry-run
*
* # Walk a huge workspace in 100-worktree pages
* wp datamachine-code workspace cleanup run --mode=artifacts --dry-run --offset=0 --format=json
* wp datamachine-code workspace cleanup run --mode=artifacts --dry-run --offset=100 --format=json
*
* # Full audit (slow on huge workspaces)
* wp datamachine-code workspace cleanup run --mode=artifacts --dry-run --exhaustive --format=json
*
* # Inspect progress for a returned run
* wp datamachine-code workspace cleanup status cleanup-run-123
*
* # Retry a failed/incomplete run through Data Machine jobs
* wp datamachine-code workspace cleanup resume cleanup-run-123
*
* # Cancel a processing run safely by failing the parent job
* wp datamachine-code workspace cleanup cancel cleanup-run-123
*
* # Print recorded evidence / engine data
* wp datamachine-code workspace cleanup evidence cleanup-run-123 --format=json
*
* @subcommand cleanup
*/
public function cleanup( array $args, array $assoc_args ): void {
$operation = (string) ( $args[0] ?? '' );
if ( '' === $operation ) {
WP_CLI::error('Usage: wp datamachine-code workspace cleanup <plan|apply|run|status|resume|cancel|evidence> [<run-id>] [--mode=<mode>]');
return;
}
switch ( $operation ) {
case 'plan':
$this->run_cleanup_plan($assoc_args);
return;
case 'apply':
$this->run_cleanup_control_ability('apply', (string) ( $args[1] ?? '' ), $assoc_args);
return;
case 'run':
$this->run_cleanup_task($assoc_args);
return;
case 'status':
case 'evidence':
if ( ! $this->is_job_cleanup_run_id( (string) ( $args[1] ?? '' )) ) {
$this->run_cleanup_control_ability($operation, (string) ( $args[1] ?? '' ), $assoc_args);
return;
}
$job_id = $this->cleanup_run_job_id( (string) ( $args[1] ?? '' ));
if ( $job_id <= 0 ) {
WP_CLI::error('Usage: wp datamachine-code workspace cleanup ' . $operation . ' <run-id>');
return;
}
$this->render_cleanup_run_status($job_id, $assoc_args, 'evidence' === $operation);
return;
case 'resume':
case 'cancel':
if ( ! $this->is_job_cleanup_run_id( (string) ( $args[1] ?? '' )) ) {
$this->run_cleanup_control_ability($operation, (string) ( $args[1] ?? '' ), $assoc_args);
return;
}
$job_id = $this->cleanup_run_job_id( (string) ( $args[1] ?? '' ));
if ( $job_id <= 0 ) {
WP_CLI::error('Usage: wp datamachine-code workspace cleanup ' . $operation . ' <run-id>');
return;
}
$this->control_cleanup_run_job($operation, $job_id, $assoc_args);
return;
default:
WP_CLI::error(sprintf('Unknown cleanup operation: %s', $operation));
return;
}
}
private function run_cleanup_task( array $assoc_args ): void {
if ( isset($assoc_args['dry-run']) ) {
$this->run_cleanup_review($assoc_args);
return;
}
$mode = strtolower(preg_replace('/[^a-z0-9_\-]/', '', (string) ( $assoc_args['mode'] ?? 'retention' )));
if ( ! in_array($mode, self::CLEANUP_MODES, true) ) {
WP_CLI::error(sprintf('Unknown cleanup mode: %s. Expected one of: %s.', $mode, implode(', ', self::CLEANUP_MODES)));
return;
}
$ability = wp_get_ability('datamachine-code/workspace-cleanup-run');
if ( ! $ability ) {
WP_CLI::error('Workspace cleanup run ability not registered.');
return;
}
$result = $ability->execute($this->cleanup_run_input($mode, $assoc_args));
if ( ! ( $result['success'] ?? false ) ) {
WP_CLI::error( (string) ( $result['error'] ?? 'Failed to schedule cleanup run.' ));
return;
}
$this->render_cleanup_control_result($result, $assoc_args);
}
private function cleanup_run_input( string $mode, array $assoc_args ): array {
$input = array(
'mode' => $mode,
'source' => self::CLEANUP_CLI_SOURCE,
);
if ( isset($assoc_args['force']) ) {
$input['force'] = (bool) $assoc_args['force'];
}
if ( isset($assoc_args['older-than']) && '' !== trim( (string) $assoc_args['older-than']) ) {
$input['older_than'] = trim( (string) $assoc_args['older-than']);
}
if ( 'artifacts' === $mode ) {
if ( isset($assoc_args['limit']) ) {
$input['limit'] = (int) $assoc_args['limit'];
}
if ( isset($assoc_args['offset']) ) {
$input['offset'] = (int) $assoc_args['offset'];
}
if ( ! empty($assoc_args['exhaustive']) ) {
$input['exhaustive'] = true;
}
}
return $input;
}
private function run_cleanup_plan( array $assoc_args ): void {
$ability = wp_get_ability('datamachine-code/workspace-cleanup-plan');
if ( ! $ability ) {
WP_CLI::error('Workspace cleanup plan ability not registered.');
return;
}
$input = array(
'mode' => strtolower(preg_replace('/[^a-z0-9_\-]/', '', (string) ( $assoc_args['mode'] ?? 'retention' ))),
'include_resolvers' => true,
);
if ( isset($assoc_args['older-than']) && '' !== trim( (string) $assoc_args['older-than']) ) {
$input['worktree_older_than'] = trim( (string) $assoc_args['older-than']);
}
if ( isset($assoc_args['force']) ) {
$input['force_artifact_cleanup'] = (bool) $assoc_args['force'];
}
$result = $ability->execute($input);
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
$this->render_cleanup_plan_result($result, $assoc_args);
}
private function run_cleanup_control_ability( string $operation, string $run_id, array $assoc_args ): void {
$run_id = trim($run_id);
if ( '' === $run_id ) {
WP_CLI::error('Usage: wp datamachine-code workspace cleanup ' . $operation . ' <run-id>');
return;
}
$ability = wp_get_ability('datamachine-code/workspace-cleanup-' . $operation);
if ( ! $ability ) {
WP_CLI::error(sprintf('Workspace cleanup %s ability not registered.', $operation));
return;
}
$result = $ability->execute(
array(
'run_id' => $run_id,
'force' => ! empty($assoc_args['force']),
) + ( isset($assoc_args['limit']) ? array( 'limit' => (int) $assoc_args['limit'] ) : array() )
);
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
$this->render_cleanup_control_result($result, $assoc_args);
}
private function run_cleanup_review( array $assoc_args ): void {
$mode = strtolower(preg_replace('/[^a-z0-9_\-]/', '', (string) ( $assoc_args['mode'] ?? 'retention' )));
if ( ! in_array($mode, self::CLEANUP_MODES, true) ) {
WP_CLI::error(sprintf('Unknown cleanup mode: %s. Expected one of: %s.', $mode, implode(', ', self::CLEANUP_MODES)));
return;
}
switch ( $mode ) {
case 'inventory':
$ability = wp_get_ability('datamachine-code/workspace-hygiene-report');
$result = $ability ? $ability->execute(
array(
'include_cleanup' => true,
'include_sizes' => true,
'include_worktree_status' => false,
'size_limit' => 200,
)
) : new \WP_Error('workspace_hygiene_ability_missing', 'Workspace hygiene ability not registered.');
$this->render_workspace_hygiene_report_from_ability($result, $assoc_args);
return;
case 'artifacts':
$ability = wp_get_ability('datamachine-code/workspace-worktree-cleanup-artifacts');
$artifact_input = array(
'dry_run' => true,
'force' => ! empty($assoc_args['force']),
);
if ( isset($assoc_args['limit']) ) {
$artifact_input['limit'] = (int) $assoc_args['limit'];
}
if ( isset($assoc_args['offset']) ) {
$artifact_input['offset'] = (int) $assoc_args['offset'];
}
if ( ! empty($assoc_args['exhaustive']) ) {
$artifact_input['exhaustive'] = true;
}
if ( ! empty($assoc_args['safety-probes']) ) {
$artifact_input['safety_probes'] = true;
}
$result = $ability ? $ability->execute($artifact_input) : new \WP_Error('artifact_cleanup_ability_missing', 'Artifact cleanup ability not registered.');
$this->render_worktree_artifact_cleanup_result_from_ability($result, $assoc_args);
return;
case 'emergency':
$ability = wp_get_ability('datamachine-code/workspace-worktree-emergency-cleanup');
$result = $ability ? $ability->execute(
array(
'dry_run' => true,
'force' => ! empty($assoc_args['force']),
)
) : new \WP_Error('emergency_cleanup_ability_missing', 'Emergency cleanup ability not registered.');
$this->render_worktree_emergency_cleanup_result_from_ability($result, $assoc_args);
return;
case 'retention':
default:
$ability = wp_get_ability('datamachine-code/workspace-worktree-cleanup');
$input = array(
'dry_run' => true,
'force' => ! empty($assoc_args['force']),
'skip_github' => true,
);
if ( isset($assoc_args['older-than']) && '' !== trim( (string) $assoc_args['older-than']) ) {
$input['older_than'] = trim( (string) $assoc_args['older-than']);
}
$result = $ability ? $ability->execute($input) : new \WP_Error('worktree_cleanup_ability_missing', 'Worktree cleanup ability not registered.');
$this->render_worktree_cleanup_result_from_ability($result, $assoc_args);
return;
}
}
private function render_workspace_hygiene_report_from_ability( array|\WP_Error $result, array $assoc_args ): void {
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
$this->render_workspace_hygiene_report($result, $assoc_args);
}
private function render_worktree_cleanup_result_from_ability( array|\WP_Error $result, array $assoc_args ): void {
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
$this->render_worktree_cleanup_result($result, $assoc_args);
}
private function render_worktree_artifact_cleanup_result_from_ability( array|\WP_Error $result, array $assoc_args ): void {
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
$this->render_worktree_artifact_cleanup_result($result, $assoc_args);
}
private function render_worktree_emergency_cleanup_result_from_ability( array|\WP_Error $result, array $assoc_args ): void {
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
$this->render_worktree_emergency_cleanup_result($result, $assoc_args);
}
private function render_cleanup_run_status( int $job_id, array $assoc_args, bool $evidence ): void {
$output = $this->cleanup_run_evidence_store()->read($this->cleanup_run_id($job_id), $evidence, ! empty($assoc_args['verbose']));
if ( $output instanceof \WP_Error ) {
WP_CLI::error($output->get_error_message());
return;
}
$this->render_cleanup_control_result($output, $assoc_args);
}
private function cleanup_run_evidence_store(): CleanupRunEvidenceStoreInterface {
if ( null === $this->cleanup_run_evidence_store ) {
$this->cleanup_run_evidence_store = new DataMachineJobCleanupRunEvidenceStore();
}
return $this->cleanup_run_evidence_store;
}
private function control_cleanup_run_job( string $operation, int $job_id, array $assoc_args ): void {
$ability_name = 'resume' === $operation ? 'datamachine-code/retry-job' : 'datamachine-code/fail-job';
$ability = wp_get_ability($ability_name);
if ( ! $ability ) {
WP_CLI::error(sprintf('Job control ability not registered: %s', $ability_name));
return;
}
$target_job_ids = $this->cleanup_run_control_job_ids($operation, $job_id);
$results = array();
foreach ( $target_job_ids as $target_job_id ) {
$input = array( 'job_id' => $target_job_id );
if ( 'resume' === $operation ) {
$input['force'] = ! empty($assoc_args['force']);
} else {
$input['reason'] = 'cleanup_cancelled';
}
$result = $ability->execute($input);
if ( ! ( $result['success'] ?? false ) ) {
WP_CLI::error( (string) ( $result['error'] ?? 'Cleanup run control failed.' ));
return;
}
$results[] = $result;
}
$output = $results[0] ?? array(
'success' => true,
'job_id' => $job_id,
);
$output['run_id'] = $this->cleanup_run_id($job_id);
$output['state'] = 'resume' === $operation ? 'running' : 'cancelled';
$output['controlled_job_ids'] = $target_job_ids;
$output['results'] = $results;
$this->render_cleanup_control_result($output, $assoc_args);
}
/**
* Resolve which Data Machine jobs should be controlled for a job-backed cleanup run.
*
* @param string $operation Cleanup control operation.
* @param int $job_id Cleanup parent job ID.
* @return array<int,int>
*/
private function cleanup_run_control_job_ids( string $operation, int $job_id ): array {
$output = $this->cleanup_run_evidence_store()->read($this->cleanup_run_id($job_id), true, true);
if ( $output instanceof \WP_Error ) {
return array( $job_id );
}
$children = (array) ( $output['evidence']['children'] ?? array() );
$processing_ids = array_map('intval', (array) ( $children['processing_job_ids'] ?? array() ));
$failed_ids = array_map('intval', (array) ( $children['failed_job_ids'] ?? array() ));
$pending_ids = array_map('intval', (array) ( $children['pending_job_ids'] ?? array() ));
if ( 'resume' === $operation ) {
$child_targets = array_values(array_unique(array_filter(array_merge($processing_ids, $failed_ids))));
return array() !== $child_targets ? $child_targets : array( $job_id );
}
return array_values(array_unique(array_filter(array_merge(array( $job_id ), $pending_ids, $processing_ids))));
}
private function render_cleanup_control_result( array $result, array $assoc_args ): void {
$format = (string) ( $assoc_args['format'] ?? 'table' );
if ( 'json' === $format ) {
WP_CLI::log( (string) wp_json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
return;
}
if ( 'yaml' === $format && class_exists('Spyc') ) {
WP_CLI::log( (string) \Spyc::YAMLDump($result, false, false, true));
return;
}
WP_CLI::log(sprintf('State: %s', $result['state'] ?? 'unknown'));
foreach ( array( 'run_id', 'job_id', 'mode', 'task_type', 'status' ) as $key ) {
if ( isset($result[ $key ]) && '' !== (string) $result[ $key ] ) {
WP_CLI::log(sprintf('%s: %s', ucfirst(str_replace('_', ' ', $key)), (string) $result[ $key ]));
}
}
if ( ! empty($result['remaining_work_summary']) && is_array($result['remaining_work_summary']) ) {
$this->render_cleanup_remaining_work_summary( (array) $result['remaining_work_summary']);
}
if ( ! empty($result['evidence']) ) {
WP_CLI::log( (string) wp_json_encode($result['evidence'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
}
/**
* Render compact cleanup remaining-work summary.
*
* @param array<string,mixed> $summary Remaining-work summary.
* @return void
*/
private function render_cleanup_remaining_work_summary( array $summary ): void {
WP_CLI::log('');
WP_CLI::log('Remaining work summary:');
$this->format_items(
array(
array(
'metric' => 'remaining_reclaimable_artifact_bytes',
'value' => $this->format_bytes($summary['remaining_reclaimable_artifact_bytes'] ?? 0),
),
array(
'metric' => 'remaining_safely_removable_worktrees',
'value' => (int) ( $summary['remaining_safely_removable_worktrees'] ?? 0 ),
),
),
array( 'metric', 'value' ),
array( 'format' => 'table' ),
'metric'
);
$this->render_cleanup_summary_type_rows('Applied rows by type:', (array) ( $summary['applied_by_type'] ?? array() ));
$this->render_cleanup_summary_reason_rows('Skipped rows by reason:', (array) ( $summary['skipped_by_reason'] ?? array() ));
$this->render_cleanup_summary_reason_rows('Blocked resolver rows by reason:', (array) ( $summary['blocked_resolvers_by_reason'] ?? array() ));
$commands = (array) ( $summary['recommended_commands'] ?? array() );
if ( array() !== $commands ) {
WP_CLI::log('');
WP_CLI::log('Recommended next commands:');
$rows = array_map(
fn( $row ) => array(
'bucket' => is_array($row) ? (string) ( $row['bucket'] ?? '' ) : '',
'command' => is_array($row) ? (string) ( $row['command'] ?? '' ) : '',
),
array_slice($commands, 0, 10)
);
$this->format_items($rows, array( 'bucket', 'command' ), array( 'format' => 'table' ), 'bucket');
}
}
private function render_cleanup_summary_type_rows( string $label, array $types ): void {
if ( array() === $types ) {
return;
}
WP_CLI::log('');
WP_CLI::log($label);
$rows = array();
foreach ( $types as $type => $bucket ) {
$bucket = (array) $bucket;
$rows[] = array(
'type' => (string) $type,
'count' => (int) ( $bucket['count'] ?? 0 ),
'bytes_reclaimed' => $this->format_bytes($bucket['bytes_reclaimed'] ?? 0),
);
}
$this->format_items($rows, array( 'type', 'count', 'bytes_reclaimed' ), array( 'format' => 'table' ), 'type');
}
private function render_cleanup_summary_reason_rows( string $label, array $reasons ): void {
if ( array() === $reasons ) {
return;
}
WP_CLI::log('');
WP_CLI::log($label);
$rows = array();
foreach ( $reasons as $reason => $bucket ) {
$bucket = (array) $bucket;
$examples = array_map(fn( $row ) => is_array($row) ? (string) ( $row['handle'] ?? '' ) : (string) $row, (array) ( $bucket['examples'] ?? array() ));
$rows[] = array(
'reason' => (string) $reason,
'count' => (int) ( $bucket['count'] ?? 0 ),
'examples' => implode(', ', array_filter($examples)),
);
}
$this->format_items($rows, array( 'reason', 'count', 'examples' ), array( 'format' => 'table' ), 'reason');
}
private function render_cleanup_plan_result( array $result, array $assoc_args ): void {
$format = (string) ( $assoc_args['format'] ?? 'table' );
if ( 'json' === $format ) {
WP_CLI::log( (string) wp_json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
return;
}
$summary = (array) ( $result['summary'] ?? array() );
WP_CLI::success(sprintf('Cleanup plan stored as %s.', (string) ( $result['run_id'] ?? '' )));
WP_CLI::log(sprintf('Run ID: %s', (string) ( $result['run_id'] ?? '' )));
WP_CLI::log(sprintf('Plan ID: %s', (string) ( $result['plan_id'] ?? '' )));
WP_CLI::log(sprintf('Rows: %d', (int) ( $summary['total_rows'] ?? 0 )));
WP_CLI::log(sprintf('Bytes: %s', $this->format_bytes($summary['total_size_bytes'] ?? 0)));
WP_CLI::log(sprintf('Apply: wp datamachine-code workspace cleanup apply %s', (string) ( $result['run_id'] ?? '' )));
}
private function cleanup_run_id( int $job_id ): string {
return 'cleanup-run-' . $job_id;
}
private function cleanup_run_job_id( string $run_id ): int {
$run_id = trim($run_id);
if ( is_numeric($run_id) ) {
return (int) $run_id;
}
if ( preg_match('/^cleanup-run-(\d+)$/', $run_id, $matches) ) {
return (int) $matches[1];
}
return 0;
}
private function is_job_cleanup_run_id( string $run_id ): bool {
return $this->cleanup_run_job_id($run_id) > 0;
}
/**
* Remove a repository from the workspace.
*
* ## OPTIONS
*
* <name>
* : Repository directory name to remove.
*
* [--yes]
* : Skip confirmation prompt.
*
* ## EXAMPLES
*
* # Remove a repo (with confirmation)
* wp datamachine-code workspace remove my-plugin
*
* # Remove without confirmation
* wp datamachine-code workspace remove my-plugin --yes
*
* @subcommand remove
*/
public function remove_repo( array $args, array $assoc_args ): void {
if ( empty($args[0]) ) {
WP_CLI::error('Repository name is required.');
return;
}
$name = $args[0];
// Confirm unless --yes is passed. This stays in CLI — abilities don't prompt.
if ( empty($assoc_args['yes']) ) {
$workspace = new Workspace();
$repo_path = $workspace->get_repo_path($name);
WP_CLI::confirm(sprintf('Remove "%s" from workspace? This deletes %s', $name, $repo_path));
}
$ability = wp_get_ability('datamachine-code/workspace-remove');
if ( ! $ability ) {
WP_CLI::error('Workspace remove ability not available.');
return;
}
$result = $ability->execute(array( 'name' => $name ));
if ( is_wp_error($result) ) {
WP_CLI::error($result->get_error_message());
return;
}
WP_CLI::success($result['message']);
}
/**
* Show a non-destructive workspace hygiene report.
*
* ## OPTIONS
*
* [--format=<format>]
* : Output format.
* ---
* default: table
* options:
* - table
* - json
* ---
*
* [--skip-cleanup]
* : Skip the local cleanup dry-run summary.
*
* [--skip-sizes]
* : Skip best-effort workspace size collection.
*
* [--include-worktree-status]
* : Include full per-worktree git status. This can be expensive on huge workspaces.
*
* [--refresh-inventory]
* : Refresh the DB-backed worktree inventory before reporting freshness.
*
* [--size-limit=<count>]
* : Maximum top-level workspace entries to size.
* ---
* default: 1000
* ---
*
* ## EXAMPLES
*
* wp datamachine-code workspace hygiene
* wp datamachine-code workspace hygiene --format=json
*
* @subcommand hygiene
*/
public function hygiene( array $args, array $assoc_args ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
$ability = wp_get_ability('datamachine-code/workspace-hygiene-report');
if ( ! $ability ) {
WP_CLI::error('Workspace hygiene ability not available.');
return;
}
$input = array(
'include_cleanup' => empty($assoc_args['skip-cleanup']),
'include_sizes' => empty($assoc_args['skip-sizes']),
'include_worktree_status' => ! empty($assoc_args['include-worktree-status']),
'refresh_inventory' => ! empty($assoc_args['refresh-inventory']),
);
if ( isset($assoc_args['size-limit']) ) {
$input['size_limit'] = (int) $assoc_args['size-limit'];
}