forked from kunchenguid/firstmate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfm-teardown.sh
More file actions
executable file
·5375 lines (5144 loc) · 214 KB
/
Copy pathfm-teardown.sh
File metadata and controls
executable file
·5375 lines (5144 loc) · 214 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
#!/usr/bin/env bash
# Tear down a finished task: return the treehouse worktree, release the Orca
# worktree, or retire a secondmate home; kill the recorded runtime endpoint,
# clear volatile state, refresh/prune the project's clone for PR-based ship
# tasks, then print a backlog-refresh reminder for ship and scout teardowns
# (a secondmate teardown prints none, since secondmates are not backlog items).
# REFUSES if the worktree holds work that has not LANDED, because cleanup
# hard-resets/removes the worktree and kills its processes. Work has landed when it is
# reachable from any remote-tracking branch (a fork counts as a remote, so
# upstream-contribution PRs pushed to a fork satisfy this in any mode), OR - for a
# normal ship task whose commits are not so reachable - when its PR is merged and
# GitHub reports a PR head that contains the current local work, or its content is
# already present in the up-to-date default branch. This recognizes the common
# squash-merge-then-delete-branch flow, where the branch's own commits live nowhere
# on a remote yet the change is fully in main.
# The PR itself is resolved from the task's recorded pr= when present, or - when
# no pr= was ever recorded (e.g. a yolo-authorized merge on a repo with no PR CI,
# where the usual "checks green" fm-pr-check.sh trigger never fires) - by looking
# up a merged PR whose head branch matches the worktree's branch, fetching its head
# via refs/pull/<n>/head when the branch itself was deleted. So a missing pr= never
# by itself causes a false refusal of landed work.
# A gh lookup error falls back to the content check; if that is also inconclusive,
# teardown refuses rather than risk discarding unlanded work.
# Origin-backed content checks hold the shared checkout lock and require bounded
# remote HEAD probes before and after fetch to agree before comparing trees.
# Every authorized Treehouse return is process-tree bounded by
# FM_TREEHOUSE_RETURN_TIMEOUT while holding the same common checkout mutation
# lock across its retry and stale-index-lock recovery sequence.
# Uncommitted changes are never landed.
# Ordinary teardown first proves that metadata names the exact registered project,
# worktree, and task lease, then quiesces the endpoint before its final safety checks.
# Each locked Treehouse return repeats repository, lease, and landed-work checks
# immediately before the destructive return command.
# A cleanly unleased Treehouse slot means an operator already returned it.
# Teardown still repeats the landed-work proof under the checkout lock, skips a
# second return, and clears only the orphaned task bookkeeping.
# Only the explicit patterns in teardown_path_is_known_tool_artifact are excluded
# from non-ignored dirty-work detection.
# Git-ignored files do not block reclaim and are not preserved as scratch.
# Before returning a leased worktree, teardown reports their directory-collapsed
# count and deduplicated top-level paths without inventorying or archiving them.
# --preserve-scratch first proves committed work landed, captures tracked diffs
# and non-ignored untracked payloads under data/<task-id>/scratch/, then cleans
# and repeats the ordinary safety proof before reclaim proceeds.
# local-only projects additionally accept work merged into the local default
# branch (firstmate performs that merge on the captain's approval) as a fallback
# for the common case where there is no remote at all.
# Scout tasks (kind=scout in meta) carve out of that check: their worktree is
# declared scratch and the report at data/<task-id>/report.md is the work
# product. A pre-cutover scout proceeds once that report exists; a task carrying
# report_required=1 must satisfy the shared completion and publication contract
# owned by docs/report-stack.md before teardown discards the scratch worktree.
# Orca tasks use the same safety checks, then close the recorded terminal, prove
# the handle stale, and remove the recorded worktree under its checkout lock;
# teardown never substitutes the shared window alias for a missing terminal.
# Secondmates (kind=secondmate in meta) are retired explicitly. Teardown proves
# the home clean and every ref and reflog commit landed. Without --force it also
# proves the child-secondmate registry empty before quiescing the endpoint, so a
# known refusal never stops a live supervisor; the same proof is repeated after
# quiescence. It still refuses while the home has in-flight crewmate meta files.
# --force authorizes recursive retirement only after every child passes the same
# endpoint, identity, cleanliness, stash, and landed-work proofs. A retiring
# project's linked worktrees are admitted only when attributable to registered
# child metadata. Project retirement also rejects symlinked operational
# directories, mount boundaries, rewritten history, and landing authorities whose
# complete Git object storage or network transport may depend on the retiring home
# or local machine. Removing a leased home releases its durable treehouse lease so
# the pool slot is freed,
# never left leased forever. If the treehouse return fails, teardown leaves the
# leased home and state in place instead of hiding a still-held lease.
# Usage: fm-teardown.sh <task-id> [--force] [--preserve-scratch] [--reap-dead]
# --force permits recursive kind=secondmate retirement. It never bypasses
# dirty, untracked, stash, landed-work, endpoint, identity, or report proofs.
# --preserve-scratch permits a ship/scout teardown to preserve tracked diffs
# and non-ignored untracked files under data/<task-id>/scratch/ before cleaning.
# Ignored files remain exempt and are summarized before a leased return.
# Committed work must still pass the ordinary landed-work proof first.
# --reap-dead is the conservative dead-endpoint path used by
# bin/fm-treehouse-reap.sh.
# It refuses a present or unknown endpoint, repeats that absence proof under
# the checkout lock, and uses non-forcing `treehouse return` after the ordinary
# identity, cleanliness, stash, and landed-work proofs pass.
# Classified safety refusals exit 77; operational failures retain their normal
# nonzero status so bin/fm-treehouse-reap.sh can distinguish the outcomes.
#
# Transient / stale worktree git lock recovery (teardown-lock-race): a crewmate process
# killed mid-git-operation can leave a .git/worktrees/<wt>/index.lock (or, for a
# non-linked worktree, .git/index.lock) that makes `treehouse return --force` fail
# with Unable to create '...index.lock': File exists. That lock is usually transient
# (the dying process finishes or exits within seconds) and must never be force-deleted
# while a live git process might still own it - the fix is patience, not rm.
#
# On that failure signature only, teardown_treehouse_return:
# 1. Retries up to FM_TREEHOUSE_RETURN_LOCK_RETRIES times (default 3), waiting
# FM_TREEHOUSE_RETURN_LOCK_RETRY_WAIT_SECS (default 1s; falls back to the older
# FM_STALE_WORKTREE_LOCK_RETRY_WAIT_SECS name when the new one is unset) between
# attempts. Retries key off the error text, not whether the lock file still
# exists after the failed attempt - a lock that self-clears mid-check still
# deserves a retry of the return.
# 2. Other treehouse return failures still abort immediately and loudly (no retry).
# 3. If every retry still hits the lock signature and the lock remains, it is removed
# and the return tried once more ONLY when the lock is provably stale per
# bin/fm-lock-lib.sh's fm_lock_is_provably_stale, passing the worktree dir as the
# companion directory and FM_STALE_WORKTREE_LOCK_AGE_SECS (default 30s) as the age
# threshold. That shared proof owns the exact lsof-holder, mtime-age, and fail-safe
# rules.
# 4. If retries exhaust and the lock is not provably stale, teardown fails as loudly
# as a normal return failure and notes that the lock persisted across the retry
# window. A missing `lsof`, or a lock that fails any stale check, is treated as
# NOT provably stale (fail safe): the lock is left untouched.
# The same proof is used when non-force safety inspection cannot run because the lock
# is present; teardown clears only a provably stale lock, then re-runs the safety
# checks before any destructive return. Teardown output notes every wait, retry, and
# removal so the operator can see what happened.
set -eu
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}"
FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}"
STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}"
DATA="${FM_DATA_OVERRIDE:-$FM_HOME/data}"
CONFIG="${FM_CONFIG_OVERRIDE:-$FM_HOME/config}"
# Same canonical resolution every other script uses (fm-spawn, fm-bootstrap,
# fm-home-seed, fm-fleet-sync, fm-fleet-snapshot, fm-checkout-refresh): with
# FM_HOME set, `projects/` is an operational dir of the HOME, not of the repo.
PROJECTS="${FM_PROJECTS_OVERRIDE:-$FM_HOME/projects}"
CHECKOUT_STATE_BASE="${FM_CHECKOUT_REFRESH_STATE_BASE:-${XDG_STATE_HOME:-$HOME/.local/state}/firstmate/checkout-refresh}"
SECONDMATE_REG="$DATA/secondmates.md"
SUB_HOME_MARKER=".fm-secondmate-home"
# shellcheck source=bin/fm-checkout-lock-lib.sh
. "$SCRIPT_DIR/fm-checkout-lock-lib.sh"
CHECKOUT_LOCK_ROOT=$(fm_checkout_lock_root "$CHECKOUT_STATE_BASE")
# shellcheck source=bin/fm-tasks-axi-lib.sh
. "$SCRIPT_DIR/fm-tasks-axi-lib.sh"
# shellcheck source=bin/fm-backend.sh
. "$SCRIPT_DIR/fm-backend.sh"
# shellcheck source=bin/fm-lock-lib.sh
. "$SCRIPT_DIR/fm-lock-lib.sh"
# shellcheck source=bin/fm-process-tree-lib.sh
. "$SCRIPT_DIR/fm-process-tree-lib.sh"
# shellcheck source=bin/fm-gate-refuse-lib.sh
. "$SCRIPT_DIR/fm-gate-refuse-lib.sh"
# Fail closed before any fleet mutation: a no-mistakes gate agent must never tear
# down a worktree (see bin/fm-gate-refuse-lib.sh).
fm_refuse_if_gate_agent
# shellcheck source=bin/fm-account-routing-lib.sh
. "$SCRIPT_DIR/fm-account-routing-lib.sh"
# shellcheck source=bin/fm-treehouse-lib.sh
. "$SCRIPT_DIR/fm-treehouse-lib.sh"
FM_LOCK_LOG_PREFIX=teardown
"$FM_ROOT/bin/fm-guard.sh" || true
TEARDOWN_UPSTREAM_TIMEOUT=${FM_CHECKOUT_REFRESH_PROBE_TIMEOUT:-15}
case "$TEARDOWN_UPSTREAM_TIMEOUT" in
''|*[!0-9]*|0)
echo "error: FM_CHECKOUT_REFRESH_PROBE_TIMEOUT must be a positive integer" >&2
exit 2
;;
esac
[ "$#" -ge 1 ] || {
echo "usage: fm-teardown.sh <task-id> [--force] [--preserve-scratch] [--reap-dead]" >&2
exit 2
}
ID=$1
shift
FORCE=
PRESERVE_SCRATCH=0
REAP_DEAD=0
TEARDOWN_REAP_SAFETY_REFUSAL=77
for option in "$@"; do
case "$option" in
--force)
[ -z "$FORCE" ] || {
echo "error: duplicate teardown option: --force" >&2
exit 2
}
FORCE=--force
;;
--preserve-scratch)
[ "$PRESERVE_SCRATCH" -eq 0 ] || {
echo "error: duplicate teardown option: --preserve-scratch" >&2
exit 2
}
PRESERVE_SCRATCH=1
;;
--reap-dead)
[ "$REAP_DEAD" -eq 0 ] || {
echo "error: duplicate teardown option: --reap-dead" >&2
exit 2
}
REAP_DEAD=1
;;
*)
echo "error: unknown teardown option: $option" >&2
exit 2
;;
esac
done
if [ "$REAP_DEAD" -eq 1 ] && { [ -n "$FORCE" ] || [ "$PRESERVE_SCRATCH" -eq 1 ]; }; then
echo "error: --reap-dead cannot be combined with --force or --preserve-scratch" >&2
exit 2
fi
META="$STATE/$ID.meta"
require_safe_task_metadata() {
local state_root meta_parent
[ -d "$STATE" ] && [ ! -L "$STATE" ] || {
echo "error: task state must be a real directory: $STATE" >&2
return 1
}
[ -f "$META" ] && [ ! -L "$META" ] && [ -r "$META" ] || {
echo "error: task metadata must be a real readable file for $ID at $META" >&2
return 1
}
state_root=$(cd "$STATE" 2>/dev/null && pwd -P) || return 1
meta_parent=$(cd "$(dirname "$META")" 2>/dev/null && pwd -P) || return 1
[ "$state_root" = "$meta_parent" ] && [ "$(basename "$META")" = "$ID.meta" ] || {
echo "error: task metadata identity does not match requested task $ID" >&2
return 1
}
}
require_safe_task_metadata || exit 1
TEARDOWN_ACCOUNT_LOCKS=('')
MANAGED_ACCOUNT_LOCK=
ACCOUNT_DELETE_LOCK=
SECONDMATE_HOME_LIFECYCLE_LOCK=
SECONDMATE_REGISTRY_LOCK=
PREPARED_REGISTRY_PATH=
PREPARED_REGISTRY_BACKUP=
PREPARED_REGISTRY_ID=
PREPARED_REGISTRY_HOME=
PREPARED_REGISTRY_LOCK=
release_teardown_account_locks() {
local lock
for lock in "${TEARDOWN_ACCOUNT_LOCKS[@]}"; do
[ -n "$lock" ] || continue
fm_account_lifecycle_lock_release "$lock" >/dev/null 2>&1 || true
done
}
trap release_teardown_account_locks EXIT
managed_account_meta() {
[ -n "$(fm_meta_get "$1" account_profile)" ] || [ "$(fm_meta_get "$1" account_rollback_cleanup)" = pending ]
}
MANAGED_ACCOUNT=0
PRELOCK_KIND=$(fm_meta_get "$META" kind)
[ -n "$PRELOCK_KIND" ] || PRELOCK_KIND=ship
if [ "$PRELOCK_KIND" = secondmate ]; then
PRELOCK_HOME=$(fm_meta_get "$META" home)
[ -n "$PRELOCK_HOME" ] || PRELOCK_HOME=$(fm_meta_get "$META" worktree)
SECONDMATE_HOME_LIFECYCLE_LOCK=$(fm_secondmate_home_lifecycle_lock_acquire "$CHECKOUT_LOCK_ROOT" "$PRELOCK_HOME") || {
echo "error: secondmate home lifecycle identity is missing, redirected, or uninspectable for $ID" >&2
exit 1
}
TEARDOWN_ACCOUNT_LOCKS+=("$SECONDMATE_HOME_LIFECYCLE_LOCK")
fi
ACCOUNT_DELETE_LOCK=$(fm_account_lifecycle_lock_acquire "$STATE" "$ID") || exit 1
TEARDOWN_ACCOUNT_LOCKS+=("$ACCOUNT_DELETE_LOCK")
require_safe_task_metadata || { echo "error: task metadata changed while teardown waited for $ID" >&2; exit 1; }
if managed_account_meta "$META"; then
MANAGED_ACCOUNT=1
managed_account_meta "$META" || { echo "error: managed task metadata changed while teardown waited for $ID" >&2; exit 1; }
fi
WT=$(grep '^worktree=' "$META" | cut -d= -f2- || true)
T=$(grep '^window=' "$META" | cut -d= -f2-)
PROJ=$(grep '^project=' "$META" | cut -d= -f2-)
BACKEND=$(fm_backend_of_meta "$META")
if [ "$BACKEND" = orca ]; then
T_ORCA=$(grep '^terminal=' "$META" | tail -1 | cut -d= -f2- || true)
T=$T_ORCA
fm_backend_source orca || exit 1
fm_backend_orca_authority_capabilities_check || exit 1
fi
HOME_PATH=$(grep '^home=' "$META" | cut -d= -f2- || true)
PR_URL=$(grep '^pr=' "$META" | tail -1 | cut -d= -f2- || true)
# tasktmp is recorded by fm-spawn for tasks that set up a per-generation temp root;
# absent for tasks spawned before that change, so tolerate empty legacy metadata.
TASK_TMP=$(grep '^tasktmp=' "$META" | cut -d= -f2- || true)
TASK_GENERATION=$(grep '^generation_id=' "$META" | cut -d= -f2- || true)
classify_teardown_task_tmp() { # <task-id> <path> <generation-id>
local task=$1 target=$2 generation=$3 generation_root suffix
if [ -z "$target" ]; then
printf 'absent\n'
elif fm_account_task_tmp_is_current "$task" "$target" "$generation"; then
printf 'current\n'
elif fm_account_task_tmp_is_legacy "$task" "$target"; then
printf 'legacy\n'
elif fm_account_task_tmp_is_previous "$task" "$target"; then
printf 'previous\n'
elif fm_account_task_tmp_path "$task" "$generation" >/dev/null 2>&1 \
&& generation_root=$(fm_account_previous_task_tmp_path "$task"); then
case "$target" in
"$generation_root"-*)
suffix=${target#"$generation_root"-}
if fm_account_valid_id "$suffix"; then
printf 'different-generation\n'
else
printf 'unknown\n'
fi
;;
*) printf 'unknown\n' ;;
esac
else
printf 'unknown\n'
fi
}
TASK_TMP_CLASSIFICATION=$(classify_teardown_task_tmp "$ID" "$TASK_TMP" "$TASK_GENERATION")
case "$TASK_TMP_CLASSIFICATION" in
absent|current|legacy|previous) ;;
different-generation)
echo "REFUSED: task temp path belongs to a different task generation for $ID: $TASK_TMP" >&2
exit 1
;;
unknown)
echo "REFUSED: unsafe task temp path in metadata for $ID; unknown or unprovable task temp path: $TASK_TMP" >&2
exit 1
;;
*)
echo "REFUSED: invalid task temp path classification for $ID" >&2
exit 1
;;
esac
TASK_TMP_PHASE=$(fm_meta_get "$META" tasktmp_phase)
case "$TASK_TMP_PHASE" in
'') ;;
created)
case "$TASK_TMP_CLASSIFICATION" in
current|legacy) ;;
*) echo "error: created task temp phase is not bound to the exact task generation for $ID" >&2; exit 1 ;;
esac
;;
not-created)
fm_account_task_tmp_is_current "$ID" "$TASK_TMP" "$TASK_GENERATION" || {
echo "error: not-created task temp phase is not bound to the exact task generation for $ID" >&2
exit 1
}
;;
*) echo "error: invalid task temp phase for $ID" >&2; exit 1 ;;
esac
ORCA_WORKTREE_ID=$(fm_meta_get "$META" orca_worktree_id)
ORCA_PATH_MATCH_VERIFIED=0
DIRECT_SPAWN_CLEANUP=$(fm_meta_get "$META" direct_spawn_cleanup)
DIRECT_SPAWN_ENDPOINT=$(fm_meta_get "$META" direct_spawn_endpoint)
DIRECT_SPAWN_BACKUP=$(fm_meta_get "$META" direct_spawn_backup)
DIRECT_SPAWN_ARTIFACTS=$(fm_meta_get "$META" direct_spawn_artifacts)
case "$DIRECT_SPAWN_CLEANUP" in
'')
[ -z "$DIRECT_SPAWN_ENDPOINT" ] || {
echo "error: direct_spawn_endpoint metadata exists without pending cleanup for $ID" >&2
exit 1
}
;;
pending)
case "$DIRECT_SPAWN_ENDPOINT" in
''|not-created) ;;
*) echo "error: invalid direct_spawn_endpoint metadata for $ID" >&2; exit 1 ;;
esac
;;
*) echo "error: invalid direct_spawn_cleanup metadata for $ID" >&2; exit 1 ;;
esac
if [ "$DIRECT_SPAWN_ENDPOINT" = not-created ]; then
[ -z "$T" ] \
&& [ -z "$(fm_meta_get "$META" tmux_window_id)" ] \
&& [ -z "$(fm_meta_get "$META" tmux_session_target)" ] \
&& [ -z "$(fm_meta_get "$META" herdr_session)" ] \
&& [ -z "$(fm_meta_get "$META" herdr_workspace_id)" ] \
&& [ -z "$(fm_meta_get "$META" herdr_tab_id)" ] \
&& [ -z "$(fm_meta_get "$META" herdr_pane_id)" ] \
&& [ -z "$(fm_meta_get "$META" zellij_session)" ] \
&& [ -z "$(fm_meta_get "$META" zellij_tab_id)" ] \
&& [ -z "$(fm_meta_get "$META" zellij_pane_id)" ] \
&& [ -z "$(fm_meta_get "$META" cmux_workspace_id)" ] \
&& [ -z "$(fm_meta_get "$META" cmux_surface_id)" ] || {
echo "error: never-created endpoint metadata for $ID contains an endpoint identity" >&2
exit 1
}
fi
SPAWN_NEVER_LAUNCHED=0
if [ "$DIRECT_SPAWN_CLEANUP" = pending ] && [ "$DIRECT_SPAWN_ENDPOINT" = not-created ]; then
SPAWN_NEVER_LAUNCHED=1
fi
ORCA_CLEANUP_PENDING_COUNT=$(grep -c '^orca_cleanup_pending=' "$META" 2>/dev/null || true)
ORCA_CLEANUP_PENDING=0
if [ "$ORCA_CLEANUP_PENDING_COUNT" -ne 0 ]; then
if [ "$ORCA_CLEANUP_PENDING_COUNT" -ne 1 ] \
|| [ "$(fm_meta_get "$META" orca_cleanup_pending)" != 1 ] \
|| [ "$BACKEND" != orca ]; then
echo "error: invalid Orca cleanup quarantine metadata for $ID" >&2
exit 1
fi
case "$(fm_meta_get "$META" orca_cleanup_phase)" in
spawn-preparing|spawn-abort) ;;
*)
echo "error: invalid Orca cleanup quarantine phase for $ID" >&2
exit 1
;;
esac
[ "$(fm_meta_get "$META" orca_expected_task)" = "fm-$ID" ] || {
echo "error: Orca cleanup quarantine is not bound to requested task $ID" >&2
exit 1
}
if [ -z "$ORCA_WORKTREE_ID" ]; then
[ "$(fm_meta_get "$META" orca_discovery_label)" = "fm-$ID" ] \
&& [ -n "$(fm_meta_get "$META" orca_provider_scope)" ] || {
echo "error: Orca cleanup quarantine discovery authority is unavailable for $ID" >&2
exit 1
}
fi
ORCA_CLEANUP_PENDING=1
fi
KIND=$(grep '^kind=' "$META" | cut -d= -f2- || true)
[ -n "$KIND" ] || KIND=ship
[ "$KIND" = "$PRELOCK_KIND" ] || {
echo "error: task kind changed while teardown waited for lifecycle ownership" >&2
exit 1
}
if [ "$PRESERVE_SCRATCH" -eq 1 ] && [ "$KIND" = secondmate ]; then
echo "error: --preserve-scratch is supported only for ship and scout worktrees" >&2
exit 2
fi
if [ "$REAP_DEAD" -eq 1 ] && [ "$KIND" != ship ]; then
echo "error: --reap-dead is supported only for ship worktrees" >&2
exit 2
fi
MODE=$(grep '^mode=' "$META" | cut -d= -f2- || true)
[ -n "$MODE" ] || MODE=no-mistakes
REPORT_GATED=0
REPORT_REQUIRED_COUNT=$(grep -c '^report_required=' "$META" 2>/dev/null || true)
if [ "$BACKEND" = orca ] && [ "$REPORT_REQUIRED_COUNT" -ne 0 ]; then
echo "error: invalid report_required metadata for legacy Orca task $ID; the marker must be absent" >&2
exit 1
elif [ "$REPORT_REQUIRED_COUNT" -gt 0 ]; then
if [ "$REPORT_REQUIRED_COUNT" -ne 1 ] || [ "$(fm_meta_get "$META" report_required)" != 1 ]; then
echo "error: invalid report_required metadata for $ID; refusing teardown" >&2
exit 1
fi
if [ "$KIND" != secondmate ]; then
REPORT_GATED=1
fi
fi
managed_endpoint_is_gone() { # <backend> <target> <expected-label> [probe-home] [recorded-scoped-target]
local backend=$1 target=$2 expected=$3 probe_home=${4:-} recorded_scoped_target=${5:-}
local attempt state last=unknown
[ -n "$target" ] || return 2
for attempt in 1 2 3 4 5 6 7 8 9 10; do
if [ -n "$probe_home" ]; then
state=$(unset FM_ROOT_OVERRIDE; FM_HOME="$probe_home" FM_ROOT="$probe_home" fm_backend_target_state "$backend" "$target" "$expected" "$recorded_scoped_target" 2>/dev/null)
else
state=$(fm_backend_target_state "$backend" "$target" "$expected" "$recorded_scoped_target" 2>/dev/null)
fi
case "$state" in
absent) return 0 ;;
present) last=present ;;
unknown) last=unknown ;;
*) last=unknown ;;
esac
sleep 0.1
done
[ "$last" != unknown ] || return 2
return 1
}
managed_endpoint_blocker() { # <status> <task> [restored]
local status=$1 task=$2 restored=${3:-} qualifier=
[ -z "$restored" ] || qualifier='restored '
if [ "$status" -eq 2 ]; then
echo "error: ${qualifier}managed endpoint state for $task is unknown; retaining its Agent Fleet lease and metadata" >&2
else
echo "error: ${qualifier}managed endpoint for $task is still alive; retaining its Agent Fleet lease and metadata" >&2
fi
}
teardown_backend_target_of_meta() {
local meta=$1 backend
backend=$(fm_backend_of_meta "$meta")
if [ "$backend" = orca ]; then
fm_meta_get "$meta" terminal || true
return 0
else
fm_backend_target_of_meta "$meta"
fi
}
quiesce_authoritative_orca_endpoint() {
local target=$1 worktree_id=$2 expected_label=$3 state
[ -n "$worktree_id" ] || return 1
if [ -n "$target" ]; then
state=$(fm_backend_target_state orca "$target" "$expected_label" "$worktree_id")
case "$state" in
present|absent) ;;
*) return 1 ;;
esac
fi
fm_backend_quiesce_worktree_terminals orca "$worktree_id" "$expected_label" "$target"
}
quiesce_secondmate_endpoint() {
local endpoint_home probe_home='' endpoint_status
endpoint_home=$(fm_backend_endpoint_home "$BACKEND" "$KIND" "$FM_HOME" "$HOME_PATH")
[ "$endpoint_home" = "$FM_HOME" ] || probe_home=$endpoint_home
if managed_endpoint_is_gone "$BACKEND" "$T" "fm-$ID" "$probe_home" "$(meta_value "$META" tmux_session_target)"; then
return 0
fi
if [ -n "$T" ]; then
if [ -n "$probe_home" ]; then
( unset FM_ROOT_OVERRIDE; FM_HOME="$probe_home" FM_ROOT="$probe_home" fm_backend_kill "$BACKEND" "$T" "$(meta_value "$META" zellij_tab_id)" "fm-$ID" "$(meta_value "$META" tmux_session_target)" ) 2>/dev/null || {
echo "error: failed to stop secondmate endpoint for $ID; refusing child cleanup" >&2
return 1
}
else
fm_backend_kill "$BACKEND" "$T" "$(meta_value "$META" zellij_tab_id)" "fm-$ID" "$(meta_value "$META" tmux_session_target)" 2>/dev/null || {
echo "error: failed to stop secondmate endpoint for $ID; refusing child cleanup" >&2
return 1
}
fi
fi
if managed_endpoint_is_gone "$BACKEND" "$T" "fm-$ID" "$probe_home" "$(meta_value "$META" tmux_session_target)"; then
return 0
fi
endpoint_status=$?
if [ "$endpoint_status" -eq 2 ]; then
echo "error: secondmate endpoint state for $ID is unknown; refusing child cleanup" >&2
else
echo "error: secondmate endpoint for $ID is still alive; refusing child cleanup" >&2
fi
return 1
}
quiesce_child_endpoint() {
local meta=$1 task=$2 owner_home=$3 child_home=${4:-}
local backend target kind endpoint_home probe_home='' endpoint_status scoped_target zellij_tab
backend=$(fm_backend_of_meta "$meta")
target=$(teardown_backend_target_of_meta "$meta")
kind=$(meta_value "$meta" kind)
[ -n "$kind" ] || kind=ship
endpoint_home=$(fm_backend_endpoint_home "$backend" "$kind" "$owner_home" "$child_home")
[ "$endpoint_home" = "$FM_HOME" ] || probe_home=$endpoint_home
scoped_target=$(meta_value "$meta" tmux_session_target)
[ "$backend" != orca ] || scoped_target=$(meta_value "$meta" orca_worktree_id)
zellij_tab=$(meta_value "$meta" zellij_tab_id)
if [ "$backend" = zellij ] && [ -n "$zellij_tab" ]; then
if [ -n "$probe_home" ]; then
( unset FM_ROOT_OVERRIDE; FM_HOME="$probe_home" FM_ROOT="$probe_home" \
fm_backend_kill "$backend" "$target" "$zellij_tab" "fm-$task" "$scoped_target" ) 2>/dev/null || {
echo "error: failed to stop child endpoint for $task; refusing destructive cleanup" >&2
return 1
}
else
fm_backend_kill "$backend" "$target" "$zellij_tab" "fm-$task" "$scoped_target" 2>/dev/null || {
echo "error: failed to stop child endpoint for $task; refusing destructive cleanup" >&2
return 1
}
fi
fi
if [ "$backend" = orca ]; then
[ -n "$target" ] || {
echo "error: child endpoint identity for $task is missing; refusing destructive cleanup" >&2
return 1
}
quiesce_authoritative_orca_endpoint "$target" "$scoped_target" "fm-$task" || {
echo "error: child Orca endpoint authority or quiescence is unproven for $task" >&2
return 1
}
return 0
fi
if managed_endpoint_is_gone "$backend" "$target" "fm-$task" "$probe_home" "$scoped_target"; then
return 0
else
endpoint_status=$?
fi
if [ "$endpoint_status" -eq 2 ]; then
echo "error: child endpoint identity or state for $task is unknown; refusing destructive cleanup" >&2
return 1
fi
[ -n "$target" ] || {
echo "error: child endpoint identity for $task is missing; refusing destructive cleanup" >&2
return 1
}
if [ -n "$probe_home" ]; then
( unset FM_ROOT_OVERRIDE; FM_HOME="$probe_home" FM_ROOT="$probe_home" fm_backend_kill "$backend" "$target" "$(meta_value "$meta" zellij_tab_id)" "fm-$task" "$(meta_value "$meta" tmux_session_target)" ) 2>/dev/null || {
echo "error: failed to stop child endpoint for $task; refusing destructive cleanup" >&2
return 1
}
else
( unset FM_ROOT_OVERRIDE; FM_HOME="$owner_home" FM_ROOT="$owner_home" fm_backend_kill "$backend" "$target" "$(meta_value "$meta" zellij_tab_id)" "fm-$task" "$(meta_value "$meta" tmux_session_target)" ) 2>/dev/null || {
echo "error: failed to stop child endpoint for $task; refusing destructive cleanup" >&2
return 1
}
fi
if managed_endpoint_is_gone "$backend" "$target" "fm-$task" "$probe_home" "$scoped_target"; then
return 0
fi
endpoint_status=$?
if [ "$endpoint_status" -eq 2 ]; then
echo "error: child endpoint state for $task is unknown; refusing destructive cleanup" >&2
else
echo "error: child endpoint for $task is still alive; refusing destructive cleanup" >&2
fi
return 1
}
quiesce_managed_account_endpoint() { # <meta> <task> [probe-home]
local meta=$1 task=$2 probe_home=${3:-} meta_state lock profile backend target zellij_tab tmux_session_target endpoint_status
meta_state=$(dirname "$meta")
lock=$(fm_account_meta_lock_acquire "$meta_state" "$task") || return 1
[ -f "$meta" ] || {
echo "error: managed metadata for $task disappeared during teardown" >&2
fm_account_meta_lock_release "$lock" >/dev/null 2>&1 || true
return 1
}
profile=$(fm_meta_get "$meta" account_profile)
if [ -z "$profile" ] && [ "$(fm_meta_get "$meta" account_rollback_cleanup)" != pending ]; then
echo "error: managed metadata for $task changed during teardown" >&2
fm_account_meta_lock_release "$lock" >/dev/null 2>&1 || true
return 1
fi
backend=$(fm_backend_of_meta "$meta")
target=$(teardown_backend_target_of_meta "$meta")
zellij_tab=$(fm_meta_get "$meta" zellij_tab_id)
tmux_session_target=$(fm_meta_get "$meta" tmux_session_target)
[ -n "$tmux_session_target" ] || tmux_session_target=$(fm_meta_get "$meta" window)
fm_account_meta_lock_release "$lock" || return 1
if [ "$backend" = orca ]; then
tmux_session_target=$(fm_meta_get "$meta" orca_worktree_id)
quiesce_authoritative_orca_endpoint "$target" "$tmux_session_target" "fm-$task" || {
echo "error: managed Orca endpoint authority or quiescence is unproven for $task" >&2
return 1
}
return 0
fi
if managed_endpoint_is_gone "$backend" "$target" "fm-$task" "$probe_home" "$tmux_session_target"; then
return 0
fi
if [ -n "$target" ]; then
if [ -n "$probe_home" ]; then
( unset FM_ROOT_OVERRIDE; FM_HOME="$probe_home" FM_ROOT="$probe_home" fm_backend_kill "$backend" "$target" "$zellij_tab" "fm-$task" "$tmux_session_target" ) 2>/dev/null || {
echo "error: failed to stop managed endpoint for $task; retaining its Agent Fleet lease and metadata" >&2
return 1
}
else
fm_backend_kill "$backend" "$target" "$zellij_tab" "fm-$task" "$tmux_session_target" 2>/dev/null || {
echo "error: failed to stop managed endpoint for $task; retaining its Agent Fleet lease and metadata" >&2
return 1
}
fi
fi
if managed_endpoint_is_gone "$backend" "$target" "fm-$task" "$probe_home" "$tmux_session_target"; then
return 0
else
endpoint_status=$?
fi
managed_endpoint_blocker "$endpoint_status" "$task"
return 1
}
reconcile_managed_account_rollback() { # <meta> <task> [data-dir]
local meta=$1 task=$2 owner_data=${3:-$DATA} rollback_backup
[ "$(fm_meta_get "$meta" account_rollback_cleanup)" = pending ] || return 0
rollback_backup=$(fm_meta_get "$meta" account_rollback_backup)
fm_account_cleanup_rollback "$meta" "$owner_data" "$task" || {
echo "error: failed to clean rolled-back Agent Fleet state for $task; retaining metadata for retry" >&2
return 1
}
if [ -n "$rollback_backup" ]; then
echo "error: rolled-back Agent Fleet state for $task was restored; rerun teardown against the restored task generation" >&2
return 2
fi
}
release_managed_account() { # <meta> <task> [probe-home] [held-lock] [data-dir]
local meta=$1 task=$2 probe_home=${3:-} lifecycle_lock=${4:-} owner_data=${5:-$DATA} profile account_task meta_state lock
MANAGED_ACCOUNT_LOCK=
profile=$(fm_meta_get "$meta" account_profile)
[ -n "$profile" ] || [ "$(fm_meta_get "$meta" account_rollback_cleanup)" = pending ] || return 0
meta_state=$(dirname "$meta")
if [ -z "$lifecycle_lock" ]; then
lifecycle_lock=$(fm_account_lifecycle_lock_acquire "$meta_state" "$task") || return 1
TEARDOWN_ACCOUNT_LOCKS+=("$lifecycle_lock")
fi
quiesce_managed_account_endpoint "$meta" "$task" "$probe_home" || return 1
lock=$(fm_account_meta_lock_acquire "$meta_state" "$task") || return 1
[ -f "$meta" ] || {
echo "error: managed metadata for $task disappeared during teardown" >&2
fm_account_meta_lock_release "$lock" >/dev/null 2>&1 || true
return 1
}
profile=$(fm_meta_get "$meta" account_profile)
if [ -z "$profile" ] && [ "$(fm_meta_get "$meta" account_rollback_cleanup)" != pending ]; then
echo "error: managed metadata for $task changed during teardown" >&2
fm_account_meta_lock_release "$lock" >/dev/null 2>&1 || true
return 1
fi
account_task=$(fm_meta_get "$meta" account_task)
[ -n "$account_task" ] || account_task=$task
fm_account_meta_lock_release "$lock" || return 1
if [ "$(fm_meta_get "$meta" account_rollback_cleanup)" = pending ]; then
reconcile_managed_account_rollback "$meta" "$task" "$owner_data" || return $?
profile=$(fm_meta_get "$meta" account_profile)
if [ -z "$profile" ]; then
return 0
fi
fi
if [ "$(fm_meta_get "$meta" account_task)" != "$account_task" ]; then
echo "error: managed task generation changed during teardown for $task" >&2
return 1
fi
fm_account_release "$account_task" --force || {
echo "error: failed to release Agent Fleet lease for $task; retaining metadata for retry" >&2
return 1
}
fm_account_session_remove "$account_task" || {
echo "error: failed to remove Agent Fleet session mapping for $task; retaining metadata for retry" >&2
return 1
}
fm_account_cleanup_predecessor_serialized "$meta" "$owner_data" "$task" || {
echo "error: failed to clean predecessor Agent Fleet state for $task; retaining metadata for retry" >&2
return 1
}
}
default_branch() {
local ref branch
ref=$(git -C "$PROJ" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)
if [ -n "$ref" ]; then
echo "${ref#origin/}"
return 0
fi
for branch in main master; do
if git -C "$PROJ" show-ref --verify --quiet "refs/heads/$branch"; then
echo "$branch"
return 0
fi
done
return 1
}
LIVE_DEFAULT_BRANCH=
LIVE_DEFAULT_TIP=
LIVE_DEFAULT_OUTPUT=
probe_live_origin_default() {
local line ref status
LIVE_DEFAULT_BRANCH=
LIVE_DEFAULT_TIP=
if fm_run_bounded_capture --combine-stderr LIVE_DEFAULT_OUTPUT "$TEARDOWN_UPSTREAM_TIMEOUT" \
git -C "$WT" ls-remote --symref origin HEAD; then
status=0
else
status=$?
fi
[ "$status" -eq 0 ] && fm_process_tree_cleanup_verified || return 1
while IFS= read -r line; do
case "$line" in
"ref: refs/heads/"*$'\t'"HEAD")
ref=${line#ref: refs/heads/}
LIVE_DEFAULT_BRANCH=${ref%$'\t'HEAD}
;;
*$'\t'"HEAD")
LIVE_DEFAULT_TIP=${line%$'\t'HEAD}
;;
esac
done <<EOF
$LIVE_DEFAULT_OUTPUT
EOF
[ -n "$LIVE_DEFAULT_BRANCH" ] \
&& [ -n "$LIVE_DEFAULT_TIP" ] \
&& git check-ref-format --branch "$LIVE_DEFAULT_BRANCH" >/dev/null 2>&1
}
meta_value() {
local meta=$1 key=$2
fm_meta_get "$meta" "$key"
}
require_orca_worktree_id() {
local meta=$1 id
id=$(meta_value "$meta" orca_worktree_id)
if [ -z "$id" ]; then
echo "error: missing orca_worktree_id in $meta; cannot remove Orca worktree" >&2
return 1
fi
printf '%s\n' "$id"
}
require_orca_task_metadata_identity() {
local meta=$1 expected_id=$2 window_count expected_count discovery_count scope_count provider_count provider_task
window_count=$(grep -c '^window=' "$meta" 2>/dev/null || true)
if [ "$window_count" -ne 1 ] || [ "$(meta_value "$meta" window)" != "fm-$expected_id" ]; then
echo "error: Orca metadata is not bound to requested task $expected_id" >&2
return 1
fi
expected_count=$(grep -c '^orca_expected_task=' "$meta" 2>/dev/null || true)
if [ "$expected_count" -ne 0 ] \
&& { [ "$expected_count" -ne 1 ] || [ "$(meta_value "$meta" orca_expected_task)" != "fm-$expected_id" ]; }; then
echo "error: Orca metadata expected-task authority drifted for $expected_id" >&2
return 1
fi
discovery_count=$(grep -c '^orca_discovery_label=' "$meta" 2>/dev/null || true)
if [ "$discovery_count" -ne 0 ] \
&& { [ "$discovery_count" -ne 1 ] || [ "$(meta_value "$meta" orca_discovery_label)" != "fm-$expected_id" ]; }; then
echo "error: Orca metadata discovery-label authority drifted for $expected_id" >&2
return 1
fi
scope_count=$(grep -c '^orca_provider_scope=' "$meta" 2>/dev/null || true)
if [ "$scope_count" -ne 0 ] \
&& { [ "$scope_count" -ne 1 ] \
|| [ "$(meta_value "$meta" orca_provider_scope)" != "repo-path:$(meta_value "$meta" project)" ]; }; then
echo "error: Orca metadata provider scope is unavailable for $expected_id" >&2
return 1
fi
provider_count=$(grep -c '^orca_provider_task=' "$meta" 2>/dev/null || true)
provider_task=$(meta_value "$meta" orca_provider_task)
if [ "$provider_count" -ne 0 ] \
&& { [ "$provider_count" -ne 1 ] || { [ -n "$provider_task" ] && [ "$provider_task" != "fm-$expected_id" ]; }; }; then
echo "error: Orca metadata provider-task authority drifted for $expected_id" >&2
return 1
fi
}
require_orca_terminal() {
local meta=$1 terminal
terminal=$(meta_value "$meta" terminal)
if [ -z "$terminal" ]; then
echo "error: missing terminal in $meta; cannot close Orca terminal" >&2
return 1
fi
printf '%s\n' "$terminal"
}
if [ "$BACKEND" = orca ] && [ "$KIND" != secondmate ]; then
ORCA_WORKTREE_ID=$(meta_value "$META" orca_worktree_id)
if [ "$ORCA_CLEANUP_PENDING" != 1 ] && [ -z "$ORCA_WORKTREE_ID" ]; then
ORCA_WORKTREE_ID=$(require_orca_worktree_id "$META") || exit 1
fi
T_ORCA=$(meta_value "$META" terminal)
if [ "$ORCA_CLEANUP_PENDING" != 1 ] && [ -z "$T_ORCA" ]; then
T_ORCA=$(require_orca_terminal "$META") || exit 1
fi
[ -z "$T_ORCA" ] || T=$T_ORCA
fi
remove_grok_turnend_auth() {
local state_dir=$1 id=$2 token hooks_dir
token=$(cat "$state_dir/$id.grok-turnend-token" 2>/dev/null || true)
case "$token" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esac
hooks_dir="${GROK_HOME:-$HOME/.grok}/hooks/fm-turn-end.d"
rm -f "$hooks_dir/$token"
}
# Resolve the PR number for a worktree branch via gh-axi. Echoes the number on a
# single match and returns 0; returns non-zero on no match or any lookup failure,
# so the caller treats it as "no PR found" (fail-safe).
pr_number_from_branch() {
local branch=$1 out n status
[ -n "$branch" ] && [ "$branch" != HEAD ] \
|| return "$TEARDOWN_REAP_SAFETY_REFUSAL"
if out=$(cd "$WT" && gh-axi pr list --state all --head "$branch" --limit 1 2>/dev/null); then
:
else
status=$?
return "$status"
fi
n=$(printf '%s\n' "$out" | sed -n 's/^[[:space:]]*\([0-9][0-9]*\),.*/\1/p' | head -1)
[ -n "$n" ] || return "$TEARDOWN_REAP_SAFETY_REFUSAL"
printf '%s' "$n"
}
pr_number_from_target() {
local target=$1 n
case "$target" in
'' ) return 1 ;;
*"/pull/"*)
n=${target##*/pull/}
n=${n%%[!0-9]*}
;;
[0-9]*)
n=${target%%[!0-9]*}
;;
*) return 1 ;;
esac
[ -n "$n" ] || return 1
printf '%s' "$n"
}
ensure_commit_object() {
local target=$1 commit=$2 n
git -C "$WT" cat-file -e "$commit^{commit}" 2>/dev/null && return 0
n=$(pr_number_from_target "$target") || return 1
git -C "$WT" remote get-url origin >/dev/null 2>&1 || return 1
git -C "$WT" fetch --quiet origin "refs/pull/$n/head" >/dev/null 2>&1 || return 1
git -C "$WT" cat-file -e "$commit^{commit}" 2>/dev/null
}
patch_id_for_commit() {
local commit=$1
git -C "$WT" show --pretty=medium --no-ext-diff "$commit" 2>/dev/null \
| git patch-id --stable 2>/dev/null \
| awk 'NR == 1 { print $1 }'
}
unpushed_patches_are_in_pr_head() {
local pr_head=$1 current base pr_patch_ids commit patch_id unpushed
current=$(git -C "$WT" rev-parse --verify HEAD 2>/dev/null) || return 1
base=$(git -C "$WT" merge-base "$current" "$pr_head" 2>/dev/null) || return 1
pr_patch_ids=$(
git -C "$WT" log --format=%H "$base..$pr_head" -- 2>/dev/null \
| while IFS= read -r commit; do
patch_id_for_commit "$commit"
done \
| sed '/^$/d' \
| sort -u
) || return 1
[ -n "$pr_patch_ids" ] || return 1
unpushed=$(git -C "$WT" log --format=%H HEAD --not --remotes -- 2>/dev/null) || return 1
[ -n "$unpushed" ] || return 1
while IFS= read -r commit; do
[ -n "$commit" ] || continue
patch_id=$(patch_id_for_commit "$commit") || return 1
[ -n "$patch_id" ] || return 1
printf '%s\n' "$pr_patch_ids" | grep -qxF "$patch_id" || return 1
done <<EOF
$unpushed
EOF
}
# Is the worktree's PR merged for local work contained in that PR? Resolves the
# PR from the recorded pr= URL first, then from the branch name, and asks GitHub
# for both the PR state and head. Returns non-zero when the PR is not merged, the
# current work is not contained in the PR head, no PR is found, or any gh error
# occurs - the caller then falls back to the content check.
pr_is_merged() {
local branch=$1 target view state head current status
if [ -n "$PR_URL" ]; then
target=$PR_URL
else
if target=$(pr_number_from_branch "$branch"); then
:
else
status=$?
return "$status"
fi
fi
[ -n "$target" ] || return "$TEARDOWN_REAP_SAFETY_REFUSAL"
view=$(cd "$WT" && gh pr view "$target" --json state,headRefOid -q '.state + "\t" + .headRefOid' 2>/dev/null) || return 1
state=${view%%$'\t'*}
head=${view#*$'\t'}
[ "$state" != "$view" ] || return 1
case "$state" in
MERGED|merged) ;;
*) return "$TEARDOWN_REAP_SAFETY_REFUSAL" ;;
esac
[ -n "$head" ] || return 1
ensure_commit_object "$target" "$head" || return 1
current=$(git -C "$WT" rev-parse --verify HEAD 2>/dev/null) || return 1
git -C "$WT" merge-base --is-ancestor "$current" "$head" 2>/dev/null && return 0
unpushed_patches_are_in_pr_head "$head" \
|| return "$TEARDOWN_REAP_SAFETY_REFUSAL"
}
# Is the branch's content already present in the up-to-date default branch?
# Origin-backed proof holds the common checkout lock across probe, fetch,
# unchanged branch-and-tip re-probe, and tree comparison.
content_matches_ref() {
local ref=$1 default_tree merged_tree
default_tree=$(git -C "$WT" rev-parse --quiet --verify "$ref^{tree}" 2>/dev/null) || return 1
[ -n "$default_tree" ] || return 1
merged_tree=$(git -C "$WT" merge-tree --write-tree "$ref" HEAD 2>/dev/null) || return 1
merged_tree=$(printf '%s\n' "$merged_tree" | head -1)
if [ "$merged_tree" != "$default_tree" ]; then
echo "teardown: task content is not present in authoritative $ref; retaining $WT" >&2
return "$TEARDOWN_REAP_SAFETY_REFUSAL"
fi
return 0
}
content_in_origin_default() {
local initial_branch initial_tip ref fetched fetch_output reason fetch_status
if ! probe_live_origin_default; then
reason=$(printf '%s\n' "$LIVE_DEFAULT_OUTPUT" | sed -n '1s/[[:space:]]\{1,\}/ /g;1p')
echo "teardown: cannot prove the live origin default for $PROJ${reason:+: $reason}; retaining $WT" >&2
return 1
fi
initial_branch=$LIVE_DEFAULT_BRANCH
initial_tip=$LIVE_DEFAULT_TIP
if fm_run_bounded_capture --combine-stderr fetch_output "$TEARDOWN_UPSTREAM_TIMEOUT" \
git -C "$WT" fetch --quiet origin \
"+refs/heads/$initial_branch:refs/remotes/origin/$initial_branch"; then
fetch_status=0
else
fetch_status=$?
fi
if [ "$fetch_status" -ne 0 ] || ! fm_process_tree_cleanup_verified; then
reason=$(printf '%s\n' "$fetch_output" | sed -n '1s/[[:space:]]\{1,\}/ /g;1p')
echo "teardown: cannot fetch live origin/$initial_branch for landing proof${reason:+: $reason}; retaining $WT" >&2