-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorkspaceWorktreeLifecycle.php
More file actions
1517 lines (1358 loc) · 56.9 KB
/
Copy pathWorkspaceWorktreeLifecycle.php
File metadata and controls
1517 lines (1358 loc) · 56.9 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
/**
* Workspace worktree lifecycle operations.
*
* @package DataMachineCode\Workspace
*/
namespace DataMachineCode\Workspace;
defined('ABSPATH') || exit;
trait WorkspaceWorktreeLifecycle {
/**
* Create a git worktree for a branch.
*
* Layout: `<workspace>/<repo>@<branch-slug>` is added as a worktree of
* `<workspace>/<repo>` checked out to `<branch>`. If the branch does not
* exist locally, it is created from `<from>` (default `origin/HEAD`).
*
* When `$inject_context` is true (default) and Data Machine's agent memory
* layer is available, the originating site's AGENTS.md is made visible to
* OpenCode: symlinked into the worktree root when no repo-owned AGENTS.md
* exists, otherwise added via local OpenCode instructions so both files load.
* MEMORY.md / USER.md / RULES.md are snapshotted into
* `.claude/CLAUDE.local.md`. Injected paths are added to the worktree's
* per-checkout `info/exclude`. When the memory layer is absent the worktree
* is still created successfully; injection silently
* skips.
*
* When `$bootstrap` is true (default), a bootstrap pass runs after the
* worktree is created: `git submodule update --init --recursive` if
* `.gitmodules` is present, package-manager installs for root or one-level
* nested dependency roots with lockfiles (pnpm/bun/yarn/npm), and
* `composer install` for root or one-level nested dependency roots with
* `composer.lock`. Steps are independent and each one is skipped gracefully
* when its tool is unavailable. A failing step is surfaced in the result
* but does not roll back the worktree — the checkout exists either way.
* Pass `$bootstrap = false` (or `--no-bootstrap` on the CLI) for a bare
* checkout when you only need to read code on that branch.
*
* When the branch/base is behind the remote default branch, worktree
* creation is refused unless `$allow_stale` is set. This check is
* zero-tolerance: any default-branch commits missing from the requested
* branch/base mean the worktree would start stale.
*
* When the materialized branch (or its local base) is more than
* `datamachine_worktree_stale_threshold` commits behind upstream and
* neither `$allow_stale` nor `$rebase_base` is set, the worktree is
* torn down and the call returns a `worktree_stale` WP_Error with
* remediation guidance. Pass `$allow_stale = true` to proceed anyway,
* or `$rebase_base = true` to auto-rebase onto the upstream tip before
* returning. On rebase conflicts the rebase is aborted (worktree stays
* at its pre-rebase state) and `rebase_failed: true` is surfaced in
* the response so the agent can resolve manually.
*
* @param string $repo Primary repo name (no @-suffix).
* @param string $branch Branch to check out (e.g. "fix/foo-bar").
* @param string|null $from Base ref when creating the branch.
* @param bool $inject_context Whether to inject site-agent context (default true).
* @param bool $bootstrap Whether to run submodule/package/composer install after creation (default true).
* @param bool $allow_stale Bypass the staleness gate (default false).
* @param bool $rebase_base Rebase onto upstream after creation (default false).
* @param bool $force Bypass the disk-budget refusal threshold (default false).
* @return array{success: bool, handle: string, path: string, branch: string, slug: string, created_branch: bool, message: string, disk_budget?: array, context_injected?: bool, context_files?: string[], context_skip_reason?: string, bootstrap?: array, fetch_failed?: bool, fetch_error?: string, stale_commits_behind?: int, upstream?: string, base_stale_commits_behind?: int, base_upstream?: string, default_branch_commits_behind?: int, default_branch_ref?: string, gate_threshold?: int, rebase_attempted?: bool, rebase_succeeded?: bool, rebase_error?: string, rebase_target?: string}|\WP_Error
*/
public function worktree_add( string $repo, string $branch, ?string $from = null, bool $inject_context = true, bool $bootstrap = true, bool $allow_stale = false, bool $rebase_base = false, bool $force = false, array $task = array() ): array|\WP_Error {
$visible = $this->require_workspace_visible();
if ( null !== $visible ) {
return $visible;
}
$repo = $this->resolve_primary_repo_name($repo);
$branch = trim($branch);
if ( is_wp_error($repo) ) {
return $repo;
}
if ( '' === $repo ) {
return new \WP_Error('invalid_repo', 'Repository name is required.', array( 'status' => 400 ));
}
if ( '' === $branch ) {
return new \WP_Error('invalid_branch', 'Branch name is required.', array( 'status' => 400 ));
}
$slug = $this->slugify_branch($branch);
if ( '' === $slug ) {
return new \WP_Error('invalid_branch', sprintf('Branch "%s" produced an empty slug.', $branch), array( 'status' => 400 ));
}
$primary_path = $this->get_primary_path($repo);
if ( ! is_dir($primary_path) || ! is_dir($primary_path . '/.git') ) {
return new \WP_Error('primary_not_found', sprintf('Primary checkout for "%s" does not exist. Clone it first.', $repo), array( 'status' => 404 ));
}
$wt_handle = $repo . '@' . $slug;
$wt_path = $this->workspace_path . '/' . $wt_handle;
if ( is_dir($wt_path) ) {
return new \WP_Error('worktree_exists', sprintf('Worktree handle "%s" already exists.', $wt_handle), array( 'status' => 400 ));
}
$disk_budget = WorktreeDiskBudget::inspect($this->workspace_path, WorktreeDiskBudget::thresholds($repo, $branch), $force);
if ( 'refused' === ( $disk_budget['status'] ?? '' ) ) {
return new \WP_Error(
'worktree_disk_budget_exceeded',
sprintf(
"Refusing to create worktree before bootstrap/install because the workspace disk budget is unsafe.\n%s\nThreshold: keep at least %.1f GiB free and %.1f%% free; effective floor on this filesystem is %.1f GiB.\nRun %s to review cleanup candidates, run %s to review artifact cleanup, or retry with --force only when a human explicitly accepts the disk-pressure risk.",
WorktreeDiskBudget::format_summary($disk_budget),
(float) ( $disk_budget['refuse_free_gib'] ?? 0 ),
(float) ( $disk_budget['refuse_free_percent'] ?? 0 ),
(float) ( $disk_budget['effective_refuse_gib'] ?? 0 ),
$disk_budget['cleanup_dry_run_command'],
$disk_budget['artifact_cleanup_command']
),
array(
'status' => 507,
'disk_budget' => $disk_budget,
)
);
}
$response = WorkspaceMutationLock::with_repo(
$this->workspace_path,
$repo,
fn() => $this->worktree_add_locked(
$repo,
$branch,
$from,
$inject_context,
$allow_stale,
$rebase_base,
$slug,
$wt_handle,
$wt_path,
$primary_path,
$task
)
);
if ( is_wp_error($response) ) {
return $response;
}
$response['disk_budget'] = $disk_budget;
if ( $bootstrap ) {
$response['bootstrap'] = WorktreeBootstrapper::bootstrap($wt_path);
}
$this->worktree_inventory()->upsert($this->build_worktree_inventory_row_from_handle($wt_handle));
$this->emit_workspace_changed('worktree_add', $repo, $wt_handle, $wt_path);
return $response;
}
/**
* Create a worktree while the primary repo lifecycle lock is held.
*
* @param string $repo Primary repo name.
* @param string $branch Branch to check out.
* @param string|null $from Base ref when creating the branch.
* @param bool $inject_context Whether to inject site-agent context.
* @param bool $allow_stale Bypass the staleness gate.
* @param bool $rebase_base Rebase onto upstream after creation.
* @param string $slug Branch slug.
* @param string $wt_handle Worktree handle.
* @param string $wt_path Worktree path.
* @param string $primary_path Primary checkout path.
* @return array|\WP_Error
*/
private function worktree_add_locked(
string $repo,
string $branch,
?string $from,
bool $inject_context,
bool $allow_stale,
bool $rebase_base,
string $slug,
string $wt_handle,
string $wt_path,
string $primary_path,
array $task = array()
): array|\WP_Error {
if ( is_dir($wt_path) ) {
return new \WP_Error('worktree_exists', sprintf('Worktree handle "%s" already exists.', $wt_handle), array( 'status' => 400 ));
}
// Always fetch first so staleness data (and the default base) reflects the
// current remote. Failure is logged but never aborts — offline work should
// still be possible, the agent just needs to know staleness is unknown.
$fetch = WorktreeStalenessProbe::fetch($primary_path);
$fetch_failed = ! $fetch['ok'];
$fetch_error = $fetch['error'] ?? null;
// Does the branch already exist locally?
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_exec
exec(sprintf('git -C %s show-ref --verify --quiet %s 2>&1', escapeshellarg($primary_path), escapeshellarg('refs/heads/' . $branch)), $_unused, $exists_local);
$created_branch = false;
$resolved_base = null;
if ( 0 === $exists_local ) {
if ( ! $allow_stale && ! $rebase_base && ! $fetch_failed ) {
$default_guard = $this->assert_ref_current_with_default_branch($primary_path, $branch, $repo, $branch, 'branch');
if ( is_wp_error($default_guard) ) {
return $default_guard;
}
}
$cmd = sprintf('worktree add %s %s', escapeshellarg($wt_path), escapeshellarg($branch));
} else {
$base = $from && '' !== trim($from) ? trim($from) : $this->resolve_default_base($primary_path);
$resolved_base = $base;
if ( ! $allow_stale && ! $rebase_base && ! $fetch_failed ) {
$default_guard = $this->assert_ref_current_with_default_branch($primary_path, $resolved_base, $repo, $branch, 'base');
if ( is_wp_error($default_guard) ) {
return $default_guard;
}
}
$cmd = sprintf('worktree add -b %s %s %s', escapeshellarg($branch), escapeshellarg($wt_path), escapeshellarg($base));
$created_branch = true;
}
$result = $this->run_git($primary_path, $cmd);
if ( is_wp_error($result) ) {
return $result;
}
$response = array(
'success' => true,
'handle' => $wt_handle,
'path' => $wt_path,
'branch' => $branch,
'slug' => $slug,
'created_branch' => $created_branch,
'message' => sprintf('Worktree "%s" added at %s (branch %s).', $wt_handle, $wt_path, $branch),
);
if ( $fetch_failed ) {
$response['fetch_failed'] = true;
if ( null !== $fetch_error && '' !== $fetch_error ) {
$response['fetch_error'] = $fetch_error;
}
}
// Compute staleness. Only meaningful when fetch succeeded — otherwise the
// upstream refs are potentially stale themselves and any behind-count we
// produce would be misleading.
if ( ! $fetch_failed ) {
if ( ! $created_branch ) {
// Existing local branch: compare against its configured upstream.
$behind = WorktreeStalenessProbe::behind_count($wt_path, $branch, '@{upstream}');
if ( is_int($behind) ) {
$response['stale_commits_behind'] = $behind;
// Derive a human-readable upstream label. Best-effort; silently
// skipped when git's plumbing doesn't cooperate.
$upstream_name = $this->run_git(
$wt_path,
sprintf('rev-parse --abbrev-ref --symbolic-full-name %s', escapeshellarg($branch . '@{upstream}'))
);
if ( ! is_wp_error($upstream_name) ) {
$label = trim( (string) ( $upstream_name['output'] ?? '' ));
if ( '' !== $label ) {
$response['upstream'] = $label;
}
}
}
// null → no upstream configured; WP_Error → unexpected failure.
// Both cases: silently omit staleness fields.
} elseif ( null !== $resolved_base && ! $this->is_remote_tracking_ref($resolved_base) && 'HEAD' !== $resolved_base ) {
// New branch cut from a local ref: compare that ref to its origin
// counterpart so the agent sees when the base itself was stale.
$base_upstream = 'origin/' . $resolved_base;
$behind = WorktreeStalenessProbe::behind_count($primary_path, $resolved_base, $base_upstream);
if ( is_int($behind) ) {
$response['base_stale_commits_behind'] = $behind;
$response['base_upstream'] = $base_upstream;
}
}
}
// Rebase BEFORE gating: if the agent explicitly asked to rebase, try
// that first. Success cancels the gate trigger entirely. Failure leaves
// the worktree at its pre-rebase state AND still trips the gate, so
// --rebase-base alone on a conflicting rebase isn't a silent bypass.
if ( $rebase_base && ! $fetch_failed ) {
$rebase_result = $this->try_rebase_worktree($wt_path, $response, $created_branch);
if ( null !== $rebase_result ) {
$response = array_merge($response, $rebase_result);
}
}
if ( ! $fetch_failed ) {
$this->populate_default_branch_behind_count($primary_path, $branch, $response);
}
// Staleness gate. Threshold filterable per-site / per-repo. Only fires
// when fetch succeeded (otherwise behind-counts are unreliable) and
// rebase didn't already zero out the staleness.
if ( ! $allow_stale && ! $fetch_failed ) {
if ( isset($response['default_branch_commits_behind']) && (int) $response['default_branch_commits_behind'] > 0 ) {
$this->run_git($primary_path, sprintf('worktree remove --force %s', escapeshellarg($wt_path)));
return $this->worktree_behind_default_branch_error(
(int) $response['default_branch_commits_behind'],
(string) ( $response['default_branch_ref'] ?? 'origin/HEAD' ),
$repo,
$branch,
'branch'
);
}
/**
* Filters the staleness threshold above which `worktree_add` refuses
* to return a stale worktree without explicit `--allow-stale` opt-in.
*
* @param int $threshold Default 50 commits behind upstream.
* @param string $repo Repository name.
* @param string $branch Branch being materialized.
*/
$threshold = (int) apply_filters('datamachine_worktree_stale_threshold', 50, $repo, $branch);
$response['gate_threshold'] = $threshold;
$effective_behind = $this->effective_behind_count($response);
if ( null !== $effective_behind && $effective_behind > $threshold ) {
// Tear the worktree down so we don't leak a half-cooked
// checkout on the user's disk.
$this->run_git($primary_path, sprintf('worktree remove --force %s', escapeshellarg($wt_path)));
$label = $response['upstream'] ?? ( $response['base_upstream'] ?? 'upstream' );
$guidance = sprintf(
'Worktree base is %d commits behind %s (threshold: %d).' . "\n"
. 'Options:' . "\n"
. ' - workspace git-pull %s --allow-primary-mutation (refresh primary first)' . "\n"
. ' - worktree add … --from=origin/%s (cut from remote ref directly)' . "\n"
. ' - worktree add … --rebase-base (auto-rebase onto upstream)' . "\n"
. ' - worktree add … --allow-stale (proceed with known-stale base)',
$effective_behind,
$label,
$threshold,
$repo,
ltrim( (string) ( $response['upstream'] ?? $resolved_base ?? 'main' ), 'origin/')
);
return new \WP_Error(
'worktree_stale',
$guidance,
array(
'status' => 409,
'stale_commits_behind' => $response['stale_commits_behind'] ?? null,
'base_stale_commits_behind' => $response['base_stale_commits_behind'] ?? null,
'upstream' => $response['upstream'] ?? null,
'base_upstream' => $response['base_upstream'] ?? null,
'gate_threshold' => $threshold,
'fetch_failed' => false,
)
);
}
}
$lifecycle_metadata = WorktreeContextInjector::build_lifecycle_metadata(
array(
'handle' => $wt_handle,
'path' => $wt_path,
'repo' => $repo,
'branch' => $branch,
'base_ref' => $created_branch ? $resolved_base : null,
'base_source' => $created_branch ? ( null !== $from && '' !== trim($from) ? 'requested_ref' : 'default_base' ) : 'existing_local_branch',
'task_url' => isset($task['task_url']) ? (string) $task['task_url'] : '',
'task_ref' => isset($task['task_ref']) ? (string) $task['task_ref'] : '',
)
);
WorktreeContextInjector::store_lifecycle_metadata($wt_handle, $lifecycle_metadata);
$response['created_at'] = $lifecycle_metadata['created_at'] ?? null;
$response['metadata'] = WorktreeContextInjector::get_metadata($wt_handle);
if ( ! $inject_context ) {
$response['context_injected'] = false;
$response['context_skip_reason'] = 'inject_context flag disabled';
} else {
$payload = WorktreeContextInjector::build_payload();
if ( null === $payload ) {
$response['context_injected'] = false;
$response['context_skip_reason'] = 'agent memory layer unavailable';
} else {
$injection = WorktreeContextInjector::inject($wt_path, $payload);
if ( is_wp_error($injection) ) {
$response['context_injected'] = false;
$response['context_skip_reason'] = 'inject failed: ' . $injection->get_error_message();
} else {
WorktreeContextInjector::store_metadata($wt_handle, $payload);
$response['metadata'] = WorktreeContextInjector::get_metadata($wt_handle);
$response['context_injected'] = true;
$response['context_files'] = $injection['written'];
if ( ! empty($injection['exclude_path']) ) {
$response['context_exclude_path'] = $injection['exclude_path'];
}
}
}
}
return $response;
}
/**
* Attach lifecycle finalizer metadata to a worktree record.
*
* @param string $handle Workspace worktree handle.
* @param string $state Lifecycle state.
* @param string|null $pr Optional PR URL or number.
* @return array{success: bool, handle: string, path: string, lifecycle_state: string, metadata: array, message: string}|\WP_Error
*/
public function worktree_finalize( string $handle, string $state, ?string $pr = null ): array|\WP_Error {
$parsed = $this->parse_handle($handle);
if ( ! $parsed['is_worktree'] ) {
return new \WP_Error('not_a_worktree', sprintf('Handle "%s" is a primary checkout, not a worktree.', $handle), array( 'status' => 400 ));
}
$normalized_state = WorktreeContextInjector::normalize_state($state);
if ( null === $normalized_state ) {
return new \WP_Error('invalid_lifecycle_state', sprintf('Invalid lifecycle state "%s". Valid states: %s.', $state, implode(', ', WorktreeContextInjector::VALID_STATES)), array( 'status' => 400 ));
}
$wt_path = $this->workspace_path . '/' . $parsed['dir_name'];
if ( ! is_dir($wt_path) ) {
return new \WP_Error('worktree_not_found', sprintf('Worktree "%s" does not exist on disk.', $parsed['dir_name']), array( 'status' => 404 ));
}
$metadata = WorktreeContextInjector::build_finalizer_metadata($normalized_state, $pr);
$metadata = array_merge(
array(
'handle' => $parsed['dir_name'],
'path' => $wt_path,
'repo' => $parsed['repo'],
// Finalize is itself an explicit liveness signal from the owner.
'last_seen_at' => gmdate('c'),
),
$metadata
);
WorktreeContextInjector::store_lifecycle_metadata($parsed['dir_name'], $metadata);
$stored = WorktreeContextInjector::get_metadata($parsed['dir_name']) ?? array();
$this->worktree_inventory()->upsert($this->build_worktree_inventory_row_from_handle($parsed['dir_name']));
return array(
'success' => true,
'handle' => $parsed['dir_name'],
'path' => $wt_path,
'lifecycle_state' => (string) ( $stored['lifecycle_state'] ?? $normalized_state ),
'metadata' => $stored,
'message' => sprintf('Worktree "%s" marked %s.', $parsed['dir_name'], (string) ( $stored['lifecycle_state'] ?? $normalized_state )),
);
}
/**
* Finalize and remove the local DMC worktree for a merged PR head branch.
*
* This is the targeted post-merge path used before remote branch deletion.
* It only touches workspace worktrees whose primary origin matches the exact
* GitHub `owner/repo` slug and whose checked-out branch matches the PR head.
*
* @param string $github_repo GitHub repository slug (`owner/repo`).
* @param string $branch Pull request head branch.
* @param string|null $pr_url Optional pull request URL for lifecycle metadata.
* @return array<string,mixed>|\WP_Error
*/
public function cleanup_merged_pr_worktree( string $github_repo, string $branch, ?string $pr_url = null ): array|\WP_Error {
$github_repo = trim($github_repo);
$branch = trim($branch);
if ( '' === $github_repo || '' === $branch ) {
return new \WP_Error('missing_pr_worktree_cleanup_params', 'GitHub repo and branch are required for merged PR worktree cleanup.', array( 'status' => 400 ));
}
if ( in_array($branch, array( 'main', 'master', 'trunk', 'develop', 'HEAD' ), true) ) {
return new \WP_Error('protected_head_branch', sprintf('Refusing to clean up protected branch %s.', $branch), array( 'status' => 409 ));
}
$listing = $this->worktree_list(
null,
null,
array(
'include_status' => false,
'include_disk' => false,
)
);
if ( $listing instanceof \WP_Error ) {
return $listing;
}
$matches = array();
foreach ( (array) ( $listing['worktrees'] ?? array() ) as $wt ) {
if ( ! empty($wt['is_primary']) || ! empty($wt['external']) ) {
continue;
}
$repo = (string) ( $wt['repo'] ?? '' );
$primary_path = '' !== $repo ? $this->get_primary_path($repo) : '';
if ( '' === $primary_path || ! is_dir($primary_path . '/.git') ) {
continue;
}
if ( $github_repo !== (string) $this->resolve_github_slug($primary_path) ) {
continue;
}
if ( (string) ( $wt['branch'] ?? '' ) !== $branch ) {
continue;
}
$matches[] = $wt;
}
if ( empty($matches) ) {
return array(
'success' => true,
'found' => false,
'repo' => $github_repo,
'branch' => $branch,
'message' => sprintf('No DMC worktree found for %s:%s.', $github_repo, $branch),
);
}
if ( count($matches) > 1 ) {
return new \WP_Error(
'ambiguous_pr_worktree_cleanup',
sprintf('Refusing merged PR worktree cleanup because %d worktrees match %s:%s.', count($matches), $github_repo, $branch),
array(
'status' => 409,
'matches' => array_map(static fn( array $wt ): string => (string) ( $wt['handle'] ?? '' ), $matches),
)
);
}
$wt = $matches[0];
$repo = (string) ( $wt['repo'] ?? '' );
$handle = (string) ( $wt['handle'] ?? '' );
$wt_path = (string) ( $wt['path'] ?? '' );
if ( '' === $repo || '' === $handle || '' === $wt_path ) {
return new \WP_Error('invalid_pr_worktree_match', 'Matched worktree is missing repo, handle, or path metadata.', array( 'status' => 500 ));
}
$dirty = $this->probe_worktree_dirty_count($wt_path, self::CLEANUP_GIT_PROBE_TIMEOUT);
if ( $dirty instanceof \WP_Error ) {
return $dirty;
}
if ( (int) $dirty > 0 ) {
return new \WP_Error('dirty_worktree', sprintf('Refusing merged PR cleanup for %s because the worktree has %d dirty file(s).', $handle, (int) $dirty), array( 'status' => 409 ));
}
$unpushed = $this->count_unpushed_commits($wt_path, self::CLEANUP_GIT_PROBE_TIMEOUT);
if ( $unpushed instanceof \WP_Error ) {
return $unpushed;
}
if ( (int) $unpushed > 0 ) {
return new \WP_Error('unpushed_commits', sprintf('Refusing merged PR cleanup for %s because it has %d unpushed commit(s).', $handle, (int) $unpushed), array( 'status' => 409 ));
}
$finalized = $this->worktree_finalize($handle, WorktreeContextInjector::STATE_MERGED, $pr_url);
if ( $finalized instanceof \WP_Error ) {
return $finalized;
}
$removed = WorkspaceMutationLock::with_repo(
$this->workspace_path,
$repo,
function () use ( $repo, $branch, $wt_path ) {
$remove = $this->remove_worktree_by_path($repo, $branch, $wt_path, false);
if ( $remove instanceof \WP_Error ) {
return $remove;
}
$primary_path = $this->get_primary_path($repo);
$delete = $this->run_git($primary_path, sprintf('branch -D %s', escapeshellarg($branch)));
if ( $delete instanceof \WP_Error ) {
$remove['local_branch_deleted'] = false;
$remove['local_branch_error'] = $delete->get_error_message();
return $remove;
}
$remove['local_branch_deleted'] = true;
return $remove;
}
);
if ( $removed instanceof \WP_Error ) {
return $removed;
}
$this->worktree_prune();
return array(
'success' => true,
'found' => true,
'repo' => $github_repo,
'branch' => $branch,
'handle' => $handle,
'path' => $wt_path,
'finalized' => $finalized,
'removed' => $removed,
'message' => sprintf('Cleaned up merged PR worktree %s before branch deletion.', $handle),
);
}
/**
* Rewrite a worktree's injected context files from the originating site's
* current memory state.
*
* Uses the site option snapshot stored at worktree-creation time for
* logging / diagnostics, then re-reads memory from the currently active
* Data Machine agent layer. Cross-machine refresh is deliberately not
* supported: callers must invoke this from the same site that created
* the worktree.
*
* @param string $handle Workspace handle (`<repo>@<branch-slug>`).
* @return array{success: bool, handle: string, path: string, written: string[], exclude_path: ?string, metadata: ?array, message: string}|\WP_Error
*/
public function worktree_refresh_context( string $handle ): array|\WP_Error {
$parsed = $this->parse_handle($handle);
if ( ! $parsed['is_worktree'] ) {
return new \WP_Error(
'not_a_worktree',
sprintf('Handle "%s" is a primary checkout, not a worktree. Context injection is worktree-only.', $handle),
array( 'status' => 400 )
);
}
$wt_path = $this->workspace_path . '/' . $parsed['dir_name'];
if ( ! is_dir($wt_path) ) {
return new \WP_Error(
'worktree_not_found',
sprintf('Worktree "%s" does not exist on disk.', $parsed['dir_name']),
array( 'status' => 404 )
);
}
$payload = WorktreeContextInjector::build_payload();
if ( null === $payload ) {
return new \WP_Error(
'agent_layer_unavailable',
'Data Machine agent memory layer is not available — cannot refresh context. Ensure this command is run from the site that created the worktree.',
array( 'status' => 500 )
);
}
$injection = WorktreeContextInjector::inject($wt_path, $payload);
if ( is_wp_error($injection) ) {
return $injection;
}
WorktreeContextInjector::store_metadata($parsed['dir_name'], $payload);
// refresh-context is a deliberate liveness signal: the originating site
// (and therefore some agent process there) just touched this worktree.
WorktreeContextInjector::record_heartbeat($parsed['dir_name']);
$this->worktree_inventory()->upsert($this->build_worktree_inventory_row_from_handle($parsed['dir_name']));
return array(
'success' => true,
'handle' => $parsed['dir_name'],
'path' => $wt_path,
'written' => $injection['written'],
'exclude_path' => $injection['exclude_path'] ?? null,
'metadata' => WorktreeContextInjector::get_metadata($parsed['dir_name']),
'message' => sprintf('Refreshed injected context in "%s" (%d file%s).', $parsed['dir_name'], count($injection['written']), 1 === count($injection['written']) ? '' : 's'),
);
}
/**
* List worktrees in the workspace.
*
* On large workspaces (hundreds of worktrees) the per-row `git status` and
* `du` probes are the dominant cost. Callers that only need cheap inventory
* (handle, repo, branch, head, lifecycle metadata) can opt out via
* `$opts['include_status']` / `$opts['include_disk']`. Skipped fields are
* returned as `null`/`0`/`array()` and the row's `fields_skipped` array
* lists which probe groups were skipped, so consumers can tell the
* difference between "absent" and "not measured".
*
* @param string|null $repo Optional repo filter (only this primary's worktrees).
* @param string|null $state Optional lifecycle state filter.
* @param array $opts {
* @type bool $include_status Whether to run `git status --porcelain` per worktree. Default true.
* @type bool $include_disk Whether to run size/artifact `du` probes per worktree. Default true.
* }
* @return array{success: bool, worktrees: array, fields_skipped: array<int,string>}|\WP_Error
*/
public function worktree_list( ?string $repo = null, ?string $state = null, array $opts = array() ): array|\WP_Error {
$include_status = array_key_exists('include_status', $opts) ? (bool) $opts['include_status'] : true;
$include_disk = array_key_exists('include_disk', $opts) ? (bool) $opts['include_disk'] : true;
$skipped_groups = array();
if ( ! $include_status ) {
$skipped_groups[] = 'status';
}
if ( ! $include_disk ) {
$skipped_groups[] = 'disk';
}
if ( null !== $state && '' !== trim($state) ) {
$state = WorktreeContextInjector::normalize_state( (string) $state);
if ( null === $state ) {
return new \WP_Error('invalid_lifecycle_state', sprintf('Invalid lifecycle state. Valid states: %s.', implode(', ', WorktreeContextInjector::VALID_STATES)), array( 'status' => 400 ));
}
} else {
$state = null;
}
if ( ! is_dir($this->workspace_path) ) {
return array(
'success' => true,
'worktrees' => array(),
'fields_skipped' => $skipped_groups,
);
}
$primaries = array();
$entries = scandir($this->workspace_path);
foreach ( $entries as $entry ) {
if ( '.' === $entry || '..' === $entry || str_contains($entry, '@') ) {
continue;
}
$entry_path = $this->workspace_path . '/' . $entry;
if ( ! file_exists($entry_path . '/.git') ) {
continue;
}
$primaries[] = $entry;
}
if ( null !== $repo ) {
$repo = $this->sanitize_name($repo);
$primaries = array_values(array_filter($primaries, fn( $p ) => $p === $repo));
}
$worktrees = array();
foreach ( $primaries as $primary ) {
$primary_path = $this->workspace_path . '/' . $primary;
$result = $this->run_git($primary_path, 'worktree list --porcelain');
if ( is_wp_error($result) ) {
continue;
}
$blocks = preg_split("/\n\n+/", trim( (string) ( $result['output'] ?? '' )));
foreach ( $blocks as $block ) {
$wt = $this->parse_worktree_block($block);
if ( null === $wt ) {
continue;
}
$is_primary = ( $wt['path'] === $primary_path );
$workspace_pfx = $this->workspace_path . '/';
$inside_ws = str_starts_with($wt['path'], $workspace_pfx);
$relative = $inside_ws ? substr($wt['path'], strlen($workspace_pfx)) : '';
$parsed = $inside_ws ? $this->parse_handle($relative) : array( 'branch_slug' => null );
if ( $is_primary ) {
$handle = $primary;
} elseif ( $inside_ws ) {
$handle = $relative;
} else {
// External worktree (created via raw `git worktree add` outside the workspace).
// Show the absolute path so it is still useful, even though it has no `<repo>@<slug>` handle.
$handle = $wt['path'];
}
if ( $include_status ) {
$dirty_result = $this->run_git($wt['path'], 'status --porcelain');
$dirty_files = is_wp_error($dirty_result)
? 0
: count(array_filter(array_map('trim', explode("\n", $dirty_result['output'] ?? ''))));
} else {
$dirty_files = null;
}
$metadata = ( ! $is_primary && $inside_ws ) ? WorktreeContextInjector::get_metadata($relative) : null;
$created_at = is_array($metadata) ? ( $metadata['created_at'] ?? null ) : null;
$lifecycle_state = is_array($metadata) ? ( $metadata['lifecycle_state'] ?? null ) : null;
if ( null !== $state && $lifecycle_state !== $state ) {
continue;
}
if ( $include_disk ) {
$disk = $this->build_worktree_disk_report($primary, $wt['path'], ! $is_primary, $created_at, $metadata);
} else {
$disk = array(
'size_bytes' => null,
'estimated_size_bytes' => null,
'last_touched_at' => null,
'age_days' => $this->calculate_age_days($created_at),
'artifacts' => array(),
'artifact_size_bytes' => 0,
);
}
// Stale-reason detection requires both signals to be reliable; only
// flag dirty/threshold reasons when the underlying probe ran. The
// metadata-only signal still works without disk/status probes.
$stale_reason = $this->detect_worktree_stale_reason(
! $is_primary,
(int) ( $dirty_files ?? 0 ),
$disk['age_days'] ?? null,
$created_at,
array(
'status_probed' => $include_status,
'disk_probed' => $include_disk,
)
);
if ( null !== $stale_reason ) {
$disk['stale_reason'] = $stale_reason;
}
$liveness = WorktreeContextInjector::classify_liveness(is_array($metadata) ? $metadata : null);
$owner = WorktreeContextInjector::summarize_owner(is_array($metadata) ? $metadata : null);
$session_view = WorktreeContextInjector::summarize_session(is_array($metadata) ? $metadata : null);
$task_view = is_array($metadata) && is_array($metadata['origin_task'] ?? null) ? $metadata['origin_task'] : null;
$row = array_merge(
array(
'handle' => $handle,
'repo' => $primary,
'is_worktree' => ! $is_primary,
'is_primary' => $is_primary,
'external' => ! $is_primary && ! $inside_ws,
'branch_slug' => $is_primary ? null : ( $parsed['branch_slug'] ?? null ),
'branch' => $wt['branch'],
'head' => $wt['head'],
'path' => $wt['path'],
'dirty' => $dirty_files,
'created_at' => $created_at,
'lifecycle_state' => $lifecycle_state,
'pr_url' => is_array($metadata) ? ( $metadata['pr_url'] ?? null ) : null,
'pr_number' => is_array($metadata) ? ( $metadata['pr_number'] ?? null ) : null,
'last_seen_at' => is_array($metadata) ? ( $metadata['last_seen_at'] ?? null ) : null,
'liveness' => $liveness['liveness'],
'liveness_reason' => $liveness['reason'],
'heartbeat_age_seconds' => $liveness['heartbeat_age_seconds'],
'owner' => $owner,
'session' => $session_view,
'task' => $task_view,
'metadata' => $metadata,
),
$disk
);
if ( $is_primary ) {
$row['primary_freshness'] = $this->build_primary_freshness_report($wt['path'], $handle);
}
$base_branch_warning = $this->base_branch_worktree_warning($row);
if ( null !== $base_branch_warning ) {
$row['base_branch_warning'] = $base_branch_warning;
}
if ( ! empty($skipped_groups) ) {
$row['fields_skipped'] = $skipped_groups;
}
$worktrees[] = $row;
}
}
$duplicates = WorktreeContextInjector::find_duplicate_task_ownership($worktrees);
$base_branch_worktrees = array_values(
array_filter(
array_map(
fn( $row ) => $row['base_branch_warning'] ?? null,
$worktrees
)
)
);
return array(
'success' => true,
'worktrees' => $worktrees,
'duplicates' => $duplicates,
'base_branch_worktrees' => $base_branch_worktrees,
'fields_skipped' => $skipped_groups,
);
}
/**
* Return warning metadata when a non-primary worktree holds a base branch.
*
* GitHub CLI merge flows may try to check out or delete the PR base branch
* during local cleanup. If another worktree has that branch checked out, the
* remote merge can succeed while local cleanup reports a fatal git error.
*
* @param array<string,mixed> $row Worktree listing row.
* @return array<string,string>|null
*/
private function base_branch_worktree_warning( array $row ): ?array {
if ( empty($row['is_worktree']) || ! empty($row['is_primary']) || ! empty($row['external']) ) {
return null;
}
$branch = (string) ( $row['branch'] ?? '' );
if ( '' === $branch || ! in_array($branch, $this->protected_base_branch_names(), true) ) {
return null;
}
return array(
'handle' => (string) ( $row['handle'] ?? '' ),
'repo' => (string) ( $row['repo'] ?? '' ),
'branch' => $branch,
'path' => (string) ( $row['path'] ?? '' ),
'reason_code' => 'base_branch_checked_out_in_worktree',
'message' => sprintf('Worktree %s has base branch %s checked out; gh pr merge --delete-branch may merge remotely but fail local cleanup.', (string) ( $row['handle'] ?? '' ), $branch),
);
}
/**
* Branch names that should normally be held by primaries, not feature worktrees.
*
* @return array<int,string>
*/
private function protected_base_branch_names(): array {
return array( 'main', 'master', 'trunk', 'develop' );
}
/**
* Refresh the DB-backed worktree inventory from the current filesystem/git view.
*
* Current rows are upserted. Previously known rows missing from the current
* scan are marked `missing_path` so operators can see drift explicitly.
*
* @return array<string,mixed>|\WP_Error
*/
public function worktree_inventory_refresh(): array|\WP_Error {
$listing = $this->worktree_list(
null,
null,
array(
'include_status' => false,
'include_disk' => false,
)
);
if ( $listing instanceof \WP_Error ) {
return $listing;
}
$repository = $this->worktree_inventory();
$current_handles = array();
$upserted = array();
$marked_missing = array();
foreach ( (array) ( $listing['worktrees'] ?? array() ) as $row ) {
$handle = (string) ( $row['handle'] ?? '' );
if ( '' === $handle || ! empty($row['external']) ) {
continue;
}
$current_handles[ $handle ] = true;
if ( $repository->upsert($row) ) {
$upserted[] = $handle;
}
}
foreach ( $repository->list() as $stored ) {
$handle = (string) ( $stored['handle'] ?? '' );
if ( '' === $handle || isset($current_handles[ $handle ]) ) {
continue;
}
if ( $repository->mark_missing($handle) ) {
$marked_missing[] = $handle;
}
}
return array(
'success' => true,
'refreshed_at' => gmdate('c'),
'upserted' => $upserted,
'marked_missing' => $marked_missing,
'summary' => array(
'upserted' => count($upserted),
'marked_missing' => count($marked_missing),
),
);
}
/**
* Build a single inventory row for a known workspace handle.
*
* @param string $handle Workspace handle.
* @return array<string,mixed>
*/
private function build_worktree_inventory_row_from_handle( string $handle ): array {
$parsed = $this->parse_handle($handle);
$path = $this->workspace_path . '/' . $parsed['dir_name'];
$metadata = $parsed['is_worktree'] ? WorktreeContextInjector::get_metadata($parsed['dir_name']) : null;
$metadata = is_array($metadata) ? $metadata : array();
$liveness = WorktreeContextInjector::classify_liveness($metadata);
$owner = WorktreeContextInjector::summarize_owner($metadata);
$session = WorktreeContextInjector::summarize_session($metadata);
$task = is_array($metadata['origin_task'] ?? null) ? (array) $metadata['origin_task'] : null;
return array(