-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev_session.sh
More file actions
executable file
·1073 lines (1007 loc) · 56.2 KB
/
Copy pathdev_session.sh
File metadata and controls
executable file
·1073 lines (1007 loc) · 56.2 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
# dev_session.sh — manage isolated parallel dev sessions (worktree + state sandbox).
#
# The easy front-door for working several agent/dev sessions at once without
# them clobbering each other's git checkout OR each other's state/cache/. Each
# session gets:
# • its own git worktree off fresh origin/<base> on a new branch, and
# • its own absolute DEVKIT_STATE_ROOT sandbox, so every state/ write the
# session makes lands in the sandbox, never prod.
#
# This is the activation the state-sandbox primitive (scripts/lib/state_paths)
# was waiting for: nothing exports DEVKIT_STATE_ROOT on its own, so the sandbox
# runs in zero sessions until something sets it. `new` is what finally sets it.
#
# Usage:
# scripts/dev_session.sh new <scope> [--base <protected>] [--prefix <configured>] [--branch <full>] [--merge-class self|operator] [--force] [--headless] [--runtime <name>] [--launcher <command>]
# scripts/dev_session.sh list [--watch [interval]]
# scripts/dev_session.sh path <scope>
# scripts/dev_session.sh pr-watch <scope> [pr-watch options]
# scripts/dev_session.sh merge <scope>
# scripts/dev_session.sh rm <scope> [--force] [--keep-branch]
# scripts/dev_session.sh print-contract
#
# `list --watch [interval]` is a live board: it re-renders every <interval>
# seconds (default 30) and marks rows whose state changed since the last render
# (a CI ✓/✗/… flip, a new commit, a DIRTY-count change, or a PR-state change)
# with a `*` until Ctrl-C. Bare `list` is a one-shot snapshot, byte-identical to
# before.
#
# `new` prints a copy-paste line that cd's into the worktree, exports the
# sandbox, and prints a runtime-configured launch command — or `source
# <session>/activate` in any shell.
#
# `new --headless` instead writes a sticky `<worktree>/.devkit_state_root`
# marker (the sandbox path) and prints a JSON descriptor to stdout — so an
# unattended launcher (background agent / cloud runtime) can point an agent at the
# worktree and its state/ writes isolate via the marker, no env export needed.
# Diagnostics go to stderr in this mode so stdout is clean JSON. The
# descriptor also carries `prompt_preamble` — the canonical lane-contract text
# a launcher MUST prepend verbatim to the lane's prompt — a persisted
# `merge_class`, and an `env` map the launcher MUST use to replace inherited
# lane-root values. This prevents an already-sandboxed cockpit's environment
# from overriding the new lane's marker; the fail-closed guard also refuses a
# marker-resolution failure rather than silently falling back to prod `state/`.
# The same guard is baked into
# the worktree's `activate` snippet for the interactive fallback (`source
# <session>/activate`). Interactive `new` (no `--headless`) and cron are
# byte-identical — neither sets this flag.
#
# `print-contract` prints ONLY the lane-contract text (no JSON, no worktree
# side effects) — for a launcher that wants the raw preamble once and reuses it
# across many lanes (e.g. a parallel-workflow fan-out path), or for
# eyeballing the current contract.
#
# Sessions live outside the repo (a sibling `dev-model-sessions/` dir by
# default; override with $DEVKIT_SESSIONS_DIR), so the repo tree stays clean
# and cron — which sets neither env var — is completely unaffected.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/lib/repo_root.sh
source "$SCRIPT_DIR/lib/repo_root.sh"
REPO_ROOT="$(devkit_find_repo_root "$SCRIPT_DIR")" || {
echo "[dev-session] error: no .git repository found above $SCRIPT_DIR" >&2
exit 1
}
ENGINE_DIR_REL="${SCRIPT_DIR#"$REPO_ROOT"/}"
CONFIG_FILE="$REPO_ROOT/config/dev-model.yaml"
# Configuration owns the integration branch and lane namespace. Environment
# overrides remain available for unusual launchers; missing legacy keys fall
# back to the historical defaults.
CONFIGURED_PROTECTED_BRANCH="$(devkit_config_scalar "$CONFIG_FILE" vcs "" protected_branch || true)"
[[ -n "$CONFIGURED_PROTECTED_BRANCH" ]] || {
echo "[dev-session] error: config must define vcs.protected_branch" >&2
exit 1
}
git check-ref-format --branch "$CONFIGURED_PROTECTED_BRANCH" >/dev/null 2>&1 || {
echo "[dev-session] error: invalid vcs.protected_branch '$CONFIGURED_PROTECTED_BRANCH'" >&2
exit 1
}
PROTECTED_BRANCH="$CONFIGURED_PROTECTED_BRANCH"
DEFAULT_BASE="${DEV_SESSION_BASE:-$PROTECTED_BRANCH}"
CONFIGURED_PREFIX="$(devkit_config_scalar "$CONFIG_FILE" vcs "" dev_branch_prefix || true)"
DEFAULT_PREFIX="${DEV_SESSION_PREFIX:-${CONFIGURED_PREFIX:-dev}}"
# Sessions container (sibling of the repo by default). Each session is one
# subdir holding wt/ (worktree) + state/ (sandbox) + activate (env snippet).
SESSIONS_DIR="${DEVKIT_SESSIONS_DIR:-$(dirname "$REPO_ROOT")/dev-model-sessions}"
case "$SESSIONS_DIR" in
/*) ;;
*) SESSIONS_DIR="$(python3 -c 'import os, sys; print(os.path.abspath(sys.argv[1]))' "$SESSIONS_DIR")" ;;
esac
# Sticky sandbox marker written at the worktree root by `new --headless`. MUST
# match scripts/lib/state_paths's STATE_ROOT_MARKER — the resolver reads it to
# select the sandbox when DEVKIT_STATE_ROOT is unset.
STATE_ROOT_MARKER=".devkit_state_root"
# Env var that makes an unsandboxed state/ write a hard error instead of a
# warning (scripts/lib/state_paths's REFUSE_UNSANDBOXED_ENV). `new
# --headless` sets this to "1" by default (pulling the guard forward from warn
# to refuse for headless lanes specifically) — a lane whose marker resolution
# fails refuses to write prod state/ rather than silently falling through.
# Interactive `new` and cron never set it — byte-identical.
REFUSE_UNSANDBOXED_ENV_VALUE="1"
# Whether the current `new` is headless. Set by cmd_new flag parsing; consulted
# by _info so headless stdout carries ONLY the JSON descriptor a launcher parses.
HEADLESS=0
# The canonical headless-lane launch contract. Every mechanism that hands a
# lane prompt to an agent (the --headless JSON descriptor's `prompt_preamble`,
# `print-contract`, and any Workflow fan-out / single-background-Agent paths
# your own dispatcher documents) MUST inject this text verbatim ahead of the
# task-specific prompt — a rule that only lives in a memory or in prose can't
# bind a freshly spawned lane. Keep this the SINGLE source of the contract
# text — any doc that quotes it should quote it, not restate it independently.
_lane_contract() {
local handoff friction protected
local escaped_engine_dir escaped_handoff escaped_friction escaped_protected
handoff="$(_config_scalar paths "" handoff)"
friction="$(_config_scalar paths "" friction_log)"
protected="$(_config_scalar vcs "" protected_branch)"
escaped_engine_dir="$(_sed_replacement "$ENGINE_DIR_REL")"
escaped_handoff="$(_sed_replacement "${handoff:-<configured handoff>}")"
escaped_friction="$(_sed_replacement "${friction:-<configured friction log>}")"
escaped_protected="$(_sed_replacement "${protected:-the protected branch}")"
sed \
-e "s|@ENGINE_DIR@|$escaped_engine_dir|g" \
-e "s|@HANDOFF@|$escaped_handoff|g" \
-e "s|@FRICTION_LOG@|$escaped_friction|g" \
-e "s|@PROTECTED_BRANCH@|$escaped_protected|g" <<'CONTRACT'
LANE CONTRACT (binding):
- Actively poll your PR's CI at a bounded cadence (e.g. `gh pr checks <PR#>` every few minutes, capped around 30 min) until it is fully green. Never stop to idly wait on a "monitor", a timer, or someone else's watcher — you are the one polling.
- Your run ends ONLY at the terminal state. Never stop early to wait for a watcher, monitor, or timer of any kind — if you need to wait on anything, poll it yourself with a bounded until-loop.
- Open completed work ready for review by default. Draft is ONLY for a material unfinished-work window that must already exist on the remote pull request because required forge-hosted validation cannot run before the pull request exists. If the branch can be completed and validated locally first, finish it and open ready.
- Immediately after a ready creation, run `uv run @ENGINE_DIR@/pr_watch.py <pr> --assert-ready` before the watch-and-fix loop so a silently drifted draft bit cannot starve review.
- If that exception applies, after `gh pr create --draft` run `uv run @ENGINE_DIR@/pr_watch.py <pr> --assert-draft`, finish the required remote work and body, then run `gh pr ready <pr>` and `--assert-ready` before the watch-and-fix loop. A finished PR left in draft is a PR that never gets reviewed.
- Do NOT merge. That is the one authority the cockpit keeps — marking ready is yours, landing it is not.
- `gh`'s draft bit is flaky in both directions, so neither route trusts the transition: the ready path owns `--assert-ready`, and the bounded exception also owns `--assert-draft`.
- Report every finding, decision, and open question in your FINAL TEXT response — that is the durable channel back to the cockpit. Never rely exclusively on a runtime-specific peer-message mechanism.
- If you spawn sub-agents of your own, hold them to the same rule: they return findings in their final text rather than relying exclusively on peer messages.
- Never edit @HANDOFF@ or @FRICTION_LOG@ — those are cockpit-owned shared narrative files. Put your handoff (what shipped, lessons, deferrals) in the PR body instead.
- Run `git branch --show-current` before every commit to confirm you are on your own lane branch, never @PROTECTED_BRANCH@.
CONTRACT
}
_die() {
echo "[dev-session] error: $*" >&2
exit 1
}
# Progress/diagnostic line. In --headless mode it goes to stderr so stdout stays
# clean for the JSON descriptor; interactive keeps it on stdout.
_info() {
if [[ "$HEADLESS" -eq 1 ]]; then
echo "$@" >&2
else
echo "$@"
fi
}
# Best-effort `gh` with a short timeout so `list` never hangs on a slow network.
_gh() {
local to
if command -v timeout >/dev/null 2>&1; then
to="timeout 8"
elif command -v gtimeout >/dev/null 2>&1; then
to="gtimeout 8"
else
to=""
fi
# shellcheck disable=SC2086
$to gh "$@" 2>/dev/null || true
}
_slug_ok() {
[[ "$1" =~ ^[a-z0-9][a-z0-9-]*$ ]]
}
_config_scalar() {
devkit_config_scalar "$CONFIG_FILE" "$1" "$2" "$3"
}
_sed_replacement() {
local value="$1"
value="${value//\\/\\\\}"
value="${value//&/\\&}"
value="${value//|/\\|}"
printf '%s' "$value"
}
_resolve_launcher() {
local requested_runtime="$1" requested_launcher="$2"
local runtime launcher
runtime="${requested_runtime:-${DEVKIT_RUNTIME:-$(_config_scalar runtime "" default)}}"
launcher="${requested_launcher:-${DEVKIT_AGENT_LAUNCHER:-}}"
if [[ -z "$launcher" && -n "$runtime" && "$runtime" != "none" ]]; then
launcher="$(_config_scalar runtime launchers "$runtime")"
fi
[[ "$launcher" == "none" ]] && launcher=""
printf '%s\t%s\n' "${runtime:-none}" "$launcher"
}
# True when $1 is a branch `rm` must never delete, regardless of merged status:
# the session's base branch, or the universal mainlines main/master. The last
# line of defense against a worktree HEAD that wandered onto main after a
# post-merge `git checkout` resolving branch=main and running `git branch -D
# main`, deleting the cockpit's checkout. $2 is the session's base branch
# (every caller passes it, defaulting to "main" before the call — the function
# itself requires it and aborts under `set -u` if omitted).
_is_protected_branch() {
local b="$1" base="$2"
# allow-hardcoded — main/master are the universal protected mainlines by definition
[[ "$b" == "$base" || "$b" == "$PROTECTED_BRANCH" || "$b" == "main" || "$b" == "master" ]]
}
cmd_new() {
local scope="" base="$DEFAULT_BASE" prefix="$DEFAULT_PREFIX" branch="" merge_class="operator" force=0
local requested_runtime="" requested_launcher="" runtime="" launcher=""
HEADLESS=0
while [[ $# -gt 0 ]]; do
case "$1" in
--base) [[ $# -ge 2 ]] || _die "--base needs a value"; base="$2"; shift 2 ;;
--prefix) [[ $# -ge 2 ]] || _die "--prefix needs a value"; prefix="$2"; shift 2 ;;
--branch) [[ $# -ge 2 ]] || _die "--branch needs a value"; branch="$2"; shift 2 ;;
--merge-class) [[ $# -ge 2 ]] || _die "--merge-class needs self or operator"; merge_class="$2"; shift 2 ;;
--force) force=1; shift ;;
--headless) HEADLESS=1; shift ;;
--runtime) [[ $# -ge 2 ]] || _die "--runtime needs a value"; requested_runtime="$2"; shift 2 ;;
--launcher) [[ $# -ge 2 ]] || _die "--launcher needs a value"; requested_launcher="$2"; shift 2 ;;
-*) _die "unknown flag: $1" ;;
*) [[ -z "$scope" ]] && scope="$1" && shift || _die "unexpected arg: $1" ;;
esac
done
[[ -n "$scope" ]] || _die "usage: dev_session.sh new <scope> [--base <protected>] [--prefix <configured>] [--branch <full>] [--merge-class self|operator] [--force] [--headless] [--runtime <name>] [--launcher <command>]"
_slug_ok "$scope" || _die "scope must be a lowercase slug ([a-z0-9-]): got '$scope'"
[[ "$merge_class" == "self" || "$merge_class" == "operator" ]] \
|| _die "merge class must be 'self' or 'operator' (got '$merge_class')"
[[ -z "$branch" ]] && branch="${prefix}/${scope}"
IFS=$'\t' read -r runtime launcher <<< "$(_resolve_launcher "$requested_runtime" "$requested_launcher")"
# Refuse a protected branch as the session branch BEFORE any side effect. `--branch`
# is unvalidated, so `new x --branch main --force` would otherwise tear the existing
# session down and then `git branch -D main` — the catastrophe via `new`'s recreate
# path. Checked here (not inside --force) so a refusal NEVER destroys the current
# worktree/state first.
if _is_protected_branch "$branch" "$base"; then
_die "refusing to use protected branch '$branch' (base/main/master) as a session branch"
fi
# In --headless mode, fold ALL of this function's stdout into stderr (saving
# the real stdout on fd 3) so stray output — git's "HEAD is now at …",
# branch-tracking notices, progress — can't pollute the JSON descriptor, which
# is the ONLY thing written back to fd 3 at the end. Interactive is untouched.
if [[ "$HEADLESS" -eq 1 ]]; then
exec 3>&1 1>&2
fi
local session_dir="$SESSIONS_DIR/$scope"
local worktree="$session_dir/wt"
local sandbox="$session_dir/state"
if [[ "$force" -eq 1 ]]; then
# Recreate: tear down any existing worktree/session/branch first, so the
# `git worktree add -b` below doesn't collide with a stale one.
if [[ -d "$worktree" ]]; then
git -C "$REPO_ROOT" worktree remove --force "$worktree" 2>/dev/null || true
fi
rm -rf "$session_dir"
git -C "$REPO_ROOT" worktree prune 2>/dev/null || true
# $branch was already proven non-protected at the top of cmd_new, so this
# recreate-time delete can never target main/master/base.
git -C "$REPO_ROOT" branch -D "$branch" 2>/dev/null || true
else
if [[ -e "$session_dir" ]]; then
_die "session '$scope' already exists at $session_dir (use --force to recreate, or 'rm $scope' first)"
fi
if git -C "$REPO_ROOT" show-ref --verify --quiet "refs/heads/$branch"; then
_die "branch '$branch' already exists locally (use --branch to pick another, or --force)"
fi
fi
_info "[dev-session] fetching origin/$base …"
git -C "$REPO_ROOT" fetch origin "$base" -q || _die "could not fetch origin/$base"
if git -C "$REPO_ROOT" show-ref --verify --quiet "refs/remotes/origin/$branch"; then
_die "branch '$branch' already exists on origin — pick another scope/--branch"
fi
_info "[dev-session] creating worktree at $worktree (branch $branch off origin/$base)"
mkdir -p "$session_dir"
git -C "$REPO_ROOT" worktree add -b "$branch" "$worktree" "origin/$base" \
|| _die "git worktree add failed"
mkdir -p "$sandbox"
# Carry gitignored MCP credentials into the worktree, if present.
if [[ -f "$REPO_ROOT/.mcp.json" ]]; then
cp "$REPO_ROOT/.mcp.json" "$worktree/.mcp.json"
fi
# Same reason, same mechanism: the local config overlay is gitignored, so
# `git worktree add` does not materialise it, and a lane would resolve
# notify.user_key to the tracked blank. Copy only the ONE file load_config
# actually reads, never overwrite, and refuse if the lane's base ref does not
# ignore it — `--base` takes any ref, and `/adopt` does not run init.sh, so the
# pattern may be absent there. The archive records `git add -A` sweeping stray
# files into a lane commit; this is an operator identity (panel, adversarial).
_overlay="$REPO_ROOT/config/dev-model.local.yaml"
if [[ -f "$_overlay" ]]; then
if [[ -e "$worktree/config/dev-model.local.yaml" ]]; then
echo "note: lane already has config/dev-model.local.yaml — keeping it" >&2
elif ! git -C "$worktree" check-ignore -q config/dev-model.local.yaml 2>/dev/null; then
echo "warning: lane base does not ignore config/dev-model.local.yaml —" >&2
echo " not copying it, so a lane commit cannot capture it." >&2
echo " Add 'config/*.local.yaml' to .gitignore on the base ref." >&2
else
mkdir -p "$worktree/config"
cp "$_overlay" "$worktree/config/dev-model.local.yaml"
fi
fi
# Headless descriptors, markers, and activation exports are one path
# contract. Resolve them before writing any artifact: DEVKIT_SESSIONS_DIR
# may be relative, and an explicit relative root outranks (and therefore
# suppresses) an otherwise-valid absolute marker.
local activate_worktree="$worktree" activate_sandbox="$sandbox" activate_repo_root="$REPO_ROOT"
local worktree_abs="" sandbox_abs="" repo_root_abs=""
if [[ "$HEADLESS" -eq 1 ]]; then
worktree_abs="$(cd "$worktree" && pwd -P)" || _die "could not resolve worktree path"
sandbox_abs="$(cd "$sandbox" && pwd -P)" || _die "could not resolve sandbox path"
repo_root_abs="$(cd "$REPO_ROOT" && pwd -P)" || _die "could not resolve repo root"
activate_worktree="$worktree_abs"
activate_sandbox="$sandbox_abs"
activate_repo_root="$repo_root_abs"
fi
# Activation snippet: the sandbox is this session's state/ (writes isolate
# here); DEVKIT_ROOT points the read-cascade's prod twin at the MAIN
# checkout so the session can still reuse its fresh caches read-only.
cat > "$session_dir/activate" <<ACTIVATE
# source this to enter the '$scope' dev session
cd "$activate_worktree" || return 1
export DEVKIT_STATE_ROOT="$activate_sandbox"
export DEVKIT_ROOT="$activate_repo_root"
echo "[dev-session] $scope active — branch $branch, sandbox \$DEVKIT_STATE_ROOT"
ACTIVATE
# A --headless session's activate snippet ALSO fails closed — if someone
# falls back to `source activate` on a headless-created worktree (or the
# marker resolution somehow misses), an unsandboxed state/ write still
# refuses rather than silently landing in prod state/. Appended as a
# separate write (not folded into the heredoc above) so interactive `new`
# stays byte-identical: this line is ONLY ever written when HEADLESS=1.
if [[ "$HEADLESS" -eq 1 ]]; then
printf 'export DEVKIT_REFUSE_UNSANDBOXED_STATE="%s"\n' "$REFUSE_UNSANDBOXED_ENV_VALUE" \
>> "$session_dir/activate"
fi
# Record the session's identity — its OWN branch + base — so `rm` deletes THIS
# branch at teardown, never whatever branch the worktree happens to be sitting
# on (a worktree that wandered onto main post-merge could otherwise make `rm`
# target main). Lives beside the worktree in the out-of-repo session dir, so it
# is never committed. Written for both the interactive and --headless paths.
printf '%s\n' "$branch" > "$session_dir/branch"
printf '%s\n' "$base" > "$session_dir/base"
printf '%s\n' "$merge_class" > "$session_dir/merge_class"
if [[ "$HEADLESS" -eq 1 ]]; then
# Sticky marker: makes the sandbox a property of the worktree on disk, so
# a background agent's stateless Bash calls (no shared shell, no surviving
# `export`) resolve it via the state-paths resolver with no env gymnastics
# in the prompt. Gitignored so a lane never commits it.
printf '%s\n' "$sandbox_abs" > "$worktree_abs/$STATE_ROOT_MARKER"
# Machine-readable descriptor (NOT the human copy-paste block) so a
# launcher can `json.load` it. The canonical bytes are persisted beside
# the lane metadata before those same bytes become the sole stdout
# payload. `prompt_preamble` is the canonical lane-contract text the
# launcher MUST prepend verbatim to the lane's prompt; `env` is the map
# of env vars the launcher MUST REPLACE in the lane process.
# Explicit lane roots are load-bearing: an inherited cockpit
# DEVKIT_STATE_ROOT otherwise outranks this lane's marker and collapses
# multiple headless lanes into one shared state directory.
local session_dir_abs descriptor_ttl base_oid lane_oid origin_url origin_push_url
session_dir_abs="$(cd "$session_dir" && pwd -P)" || _die "could not resolve session path"
descriptor_ttl="$(_config_scalar parallel "" descriptor_ttl_seconds)"
[[ "$descriptor_ttl" =~ ^[1-9][0-9]*$ ]] \
|| _die "config parallel.descriptor_ttl_seconds must be a positive integer"
base_oid="$(git -C "$worktree_abs" rev-parse "refs/remotes/origin/$base")" \
|| _die "could not resolve origin/$base for the launch descriptor"
lane_oid="$(git -C "$worktree_abs" rev-parse HEAD)" \
|| _die "could not resolve lane head for the launch descriptor"
origin_url="$(git -C "$worktree_abs" remote get-url origin)" \
|| _die "could not resolve origin URL for the launch descriptor"
origin_push_url="$(git -C "$worktree_abs" remote get-url --push origin)" \
|| _die "could not resolve origin push URL for the launch descriptor"
python3 - "$scope" "$branch" "$worktree_abs" "$sandbox_abs" "$repo_root_abs" "$base" \
"$merge_class" "$(_lane_contract)" "$REFUSE_UNSANDBOXED_ENV_VALUE" "$runtime" "$launcher" \
"$session_dir_abs" "$descriptor_ttl" "$base_oid" "$lane_oid" "$origin_url" \
"$origin_push_url" >&3 <<'PY'
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import sys
import tempfile
import uuid
(
scope, branch, worktree, state_root, repo_root, base, merge_class,
prompt_preamble, refuse_unsandboxed, runtime, launcher, session_dir,
descriptor_ttl, base_oid, lane_oid, origin_url, origin_push_url,
) = sys.argv[1:18]
issued = dt.datetime.now(dt.timezone.utc)
expires = issued + dt.timedelta(seconds=int(descriptor_ttl))
descriptor_path = Path(session_dir, "launch-descriptor.json")
authority_path = Path(session_dir, "launch-authority.json")
descriptor = {
"schema_version": 1,
"descriptor_id": str(uuid.uuid4()),
"issued_at": issued.isoformat().replace("+00:00", "Z"),
"expires_at": expires.isoformat().replace("+00:00", "Z"),
"descriptor_path": str(descriptor_path),
"scope": scope,
"branch": branch,
"worktree": worktree,
"state_root": state_root,
"repo_root": repo_root,
"session_dir": session_dir,
"base": base,
"base_oid": base_oid,
"lane_oid": lane_oid,
"origin_url": origin_url,
"origin_push_url": origin_push_url,
"merge_class": merge_class,
"prompt_preamble": prompt_preamble,
"env": {
"DEVKIT_STATE_ROOT": state_root,
"DEVKIT_ROOT": repo_root,
"DEVKIT_REFUSE_UNSANDBOXED_STATE": refuse_unsandboxed,
},
"runtime": runtime,
"launcher": launcher or None,
}
payload = (json.dumps(descriptor, sort_keys=True, separators=(",", ":")) + "\n").encode()
fd, tmp_name = tempfile.mkstemp(prefix=".launch-descriptor.", dir=session_dir)
try:
with os.fdopen(fd, "wb") as handle:
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp_name, 0o600)
os.replace(tmp_name, descriptor_path)
directory_fd = os.open(session_dir, os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
finally:
if os.path.exists(tmp_name):
os.unlink(tmp_name)
authority = {
"schema_version": 1,
"descriptor_id": descriptor["descriptor_id"],
"descriptor_sha256": hashlib.sha256(payload).hexdigest(),
}
authority_payload = (
json.dumps(authority, sort_keys=True, separators=(",", ":")) + "\n"
).encode()
authority_fd = os.open(
authority_path,
os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
0o400,
)
with os.fdopen(authority_fd, "wb") as handle:
handle.write(authority_payload)
handle.flush()
os.fsync(handle.fileno())
directory_fd = os.open(session_dir, os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
sys.stdout.buffer.write(payload)
PY
return 0
fi
echo
echo "✓ session '$scope' ready (merge class: $merge_class)."
echo
if [[ -n "$launcher" ]]; then
echo " Start it with $runtime (copy-paste):"
echo " cd \"$worktree\" && export DEVKIT_STATE_ROOT=\"$sandbox\" && export DEVKIT_ROOT=\"$REPO_ROOT\" && $launcher"
else
echo " Activate it, then start your agent runtime:"
echo " source \"$session_dir/activate\""
fi
echo
echo " …or in any shell: source \"$session_dir/activate\""
echo " When done: \"${BASH_SOURCE[0]}\" rm $scope"
}
# Gather one TAB-separated record per active session, the shared data behind both
# bare `list` and `list --watch`:
# scope <TAB> branch <TAB> pr <TAB> ci <TAB> dirty <TAB> sandbox <TAB> sig
# `sig` is the change-tracking signature watch mode diffs on. It folds in the
# short HEAD sha and the PR state/draft/review on top of the displayed columns, so
# a new commit or a PR-state flip (draft→open, review approved) is detected even
# though neither is its own column. Bare `list` ignores `sig`. The single
# python3 parse (vs two) is the only consolidation — the resulting `pr` and `ci`
# strings are unchanged. Keeps the _gh short-timeout idiom so a slow network
# can't hang a watch loop.
_collect_board() {
local d scope worktree branch head dirty pr ci pr_json parsed num state draft review sig pr_ok
for d in "$SESSIONS_DIR"/*/; do
worktree="${d}wt"
[[ -d "$worktree" ]] || continue
scope="$(basename "$d")"
branch="$(git -C "$worktree" rev-parse --abbrev-ref HEAD 2>/dev/null || echo '?')"
head="$(git -C "$worktree" rev-parse --short HEAD 2>/dev/null || echo '?')"
dirty="$(git -C "$worktree" status --porcelain 2>/dev/null | wc -l | tr -d ' ')"
pr="—"; ci="—"; state=""; draft=""; review=""; pr_ok=0
pr_json="$(_gh pr view "$branch" --json number,state,isDraft,reviewDecision,statusCheckRollup)"
if [[ -n "$pr_json" ]]; then
pr_ok=1
# CI rollup → one glyph. The failing/pending vocabularies mirror
# scripts/pr_watch.py:summarize_checks (the other cockpit CI surface) so
# the board and pr-watch agree — notably TIMED_OUT/ACTION_REQUIRED render
# ✗, not a misleading ✓, and EXPECTED/QUEUED render … (pending).
parsed="$(printf '%s' "$pr_json" | python3 -c '
import sys, json
d = json.load(sys.stdin)
n = d.get("number")
num = str(n) if n else "—"
roll = d.get("statusCheckRollup") or []
states = [c.get("conclusion") or c.get("state") for c in roll]
FAIL = ("FAILURE", "ERROR", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE")
PEND = ("PENDING", "IN_PROGRESS", "QUEUED", "WAITING", "REQUESTED", "EXPECTED", None)
if not states: ci = "—"
elif any(s in FAIL for s in states): ci = "✗"
elif any(s in PEND for s in states): ci = "…"
else: ci = "✓"
print("\t".join([num, ci, str(d.get("state") or ""), str(d.get("isDraft")), str(d.get("reviewDecision") or "")]))
' 2>/dev/null || true)"
if [[ -n "$parsed" ]]; then
IFS=$'\t' read -r num ci state draft review <<< "$parsed"
else
num="—"; ci="?"
fi
pr="#$num"
fi
sig="${branch}|${head}|${pr}|${ci}|${dirty}|${state}|${draft}|${review}"
# Trailing pr_ok lets _list_render distinguish "gh failed/timed out this
# frame" (carry forward last-known PR data) from a real PR change.
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$scope" "$branch" "$pr" "$ci" "$dirty" "${d}state" "$sig" "$pr_ok"
done
}
cmd_list() {
local watch=0 interval=30 max_iters=""
while [[ $# -gt 0 ]]; do
case "$1" in
--watch)
watch=1; shift
# An optional numeric interval may immediately follow --watch.
# Reject 0 — `sleep 0` would busy-loop, hammering gh every render.
if [[ $# -gt 0 && "$1" =~ ^[0-9]+$ ]]; then
interval="$1"; shift
[[ "$interval" -ge 1 ]] || _die "--watch interval must be a positive integer (got $interval)"
fi
;;
--max-iters)
[[ $# -ge 2 ]] || _die "--max-iters needs a value"
[[ "$2" =~ ^[0-9]+$ ]] || _die "--max-iters must be a non-negative integer"
max_iters="$2"; shift 2 ;;
-*) _die "unknown flag: $1" ;;
*) _die "unexpected arg: $1 (list takes no positional args)" ;;
esac
done
if [[ "$watch" -eq 1 ]]; then
_list_watch "$interval" "$max_iters"
return
fi
# Bare one-shot board — byte-identical to the pre-watch output.
printf "%-16s %-26s %-7s %-4s %-7s %s\n" "SCOPE" "BRANCH" "PR" "CI" "DIRTY" "SANDBOX"
printf "%-16s %-26s %-7s %-4s %-7s %s\n" "----" "------" "--" "--" "-----" "-------"
[[ -d "$SESSIONS_DIR" ]] || { echo "(no sessions — $SESSIONS_DIR does not exist yet)"; return 0; }
local found=0 scope branch pr ci dirty sandbox sig pr_ok
while IFS=$'\t' read -r scope branch pr ci dirty sandbox sig pr_ok; do
found=1
printf "%-16s %-26s %-7s %-4s %-7s %s\n" "$scope" "$branch" "$pr" "$ci" "$dirty" "$sandbox"
done < <(_collect_board)
[[ "$found" -eq 1 ]] || echo "(no active sessions)"
}
# Abbreviate $HOME → ~ in an absolute path. No-op when HOME is unset/empty (the
# `${HOME:-}` read keeps this safe under `set -u` — a bare $HOME would abort) or
# when the path is not under HOME. Used by the live board to keep cells short.
_home_abbrev() {
local p="$1" home="${HOME:-}"
if [[ -n "$home" && "$p" == "$home"/* ]]; then
printf '~/%s' "${p#"$home"/}"
else
printf '%s' "$p"
fi
}
# Render the board ONCE, marking with a leading `*` every row whose signature
# changed vs the snapshot in <sigfile>, then rewrite <sigfile> with the current
# signatures. An empty/absent sigfile is the baseline render — nothing is marked
# (you can't diff against nothing), it only records — which is why a watch loop's
# first frame highlights nothing. A row for a session not in the snapshot (a new
# lane that appeared) marks too. ANSI bold is added only on a TTY; the `*` marker
# is always emitted so the change is visible (and testable) when piped. Kept
# separate from the loop so it is unit-testable against a supplied snapshot file.
_list_render() {
local sigfile="$1"
local had_baseline=0
[[ -s "$sigfile" ]] && had_baseline=1
printf "%-2s %-16s %-26s %-7s %-4s %-7s %s\n" "" "SCOPE" "BRANCH" "PR" "CI" "DIRTY" "SANDBOX"
printf "%-2s %-16s %-26s %-7s %-4s %-7s %s\n" "" "----" "------" "--" "--" "-----" "-------"
# The snapshot always opens with a sentinel line so even an empty-board frame
# leaves a non-empty file — otherwise the next frame reads "no baseline" and
# wouldn't mark the first session that appears. awk lookups never match it (no
# real scope is "#baseline").
local tmp; tmp="$(mktemp "${TMPDIR:-/tmp}/dev_session_sig.XXXXXX")"
printf '#baseline\n' > "$tmp"
local found=0 scope branch pr ci dirty sandbox sig pr_ok prev marker
local c_branch c_head c_pr c_ci c_dirty c_state c_draft c_review
local p_pr p_ci p_state p_draft p_review p_skip
while IFS=$'\t' read -r scope branch pr ci dirty sandbox sig pr_ok; do
found=1
prev="$(awk -F'\t' -v s="$scope" '$1==s{print $2; exit}' "$sigfile")"
# Carry forward the PR-derived columns when gh failed/timed out this frame
# (pr_ok=0) but a prior snapshot exists, so a transient gh blip isn't
# reported as a change (the whole board lighting up). The git-stable fields
# (branch/head/dirty) stay live, so a real commit or dirty-count change in
# the same frame still marks.
if [[ "$pr_ok" -eq 0 && -n "$prev" ]]; then
IFS='|' read -r c_branch c_head c_pr c_ci c_dirty c_state c_draft c_review <<< "$sig"
IFS='|' read -r p_skip p_skip p_pr p_ci p_skip p_state p_draft p_review <<< "$prev"
pr="$p_pr"; ci="$p_ci"
sig="${c_branch}|${c_head}|${p_pr}|${p_ci}|${c_dirty}|${p_state}|${p_draft}|${p_review}"
fi
printf '%s\t%s\n' "$scope" "$sig" >> "$tmp"
# Compact the sandbox for the live board: every sandbox lives under the
# shared $SESSIONS_DIR (printed once in the watch banner), so strip that
# prefix → the cell is just "<scope>/state" and the row no longer wraps
# past the terminal width (the long-absolute-path mess on small terminals).
# A path outside SESSIONS_DIR (unusual) falls back to ~-abbreviation. Bare
# `list` is untouched — it keeps the full absolute path (byte-identical AC).
local sandbox_disp="$sandbox"
if [[ "$sandbox_disp" == "$SESSIONS_DIR/"* ]]; then
sandbox_disp="${sandbox_disp#"$SESSIONS_DIR"/}"
else
sandbox_disp="$(_home_abbrev "$sandbox_disp")"
fi
marker=""
[[ "$had_baseline" -eq 1 && "$prev" != "$sig" ]] && marker="*"
if [[ -n "$marker" && -t 1 ]]; then
printf '\033[1m%-2s %-16s %-26s %-7s %-4s %-7s %s\033[0m\n' "$marker" "$scope" "$branch" "$pr" "$ci" "$dirty" "$sandbox_disp"
else
printf '%-2s %-16s %-26s %-7s %-4s %-7s %s\n' "$marker" "$scope" "$branch" "$pr" "$ci" "$dirty" "$sandbox_disp"
fi
done < <(_collect_board)
mv -f "$tmp" "$sigfile"
if [[ "$found" -ne 1 ]]; then
# Mirror bare `list`'s two empty states (dir-absent vs present-but-empty).
if [[ -d "$SESSIONS_DIR" ]]; then
echo "(no active sessions)"
else
echo "(no sessions — $SESSIONS_DIR does not exist yet)"
fi
fi
}
# Live board: re-render every <interval>s, marking changed rows, until Ctrl-C (or
# <max_iters> renders, if given — mainly for scripting/tests). Each render diffs
# against the previous via a private snapshot file cleaned up on exit.
_list_watch() {
local interval="$1" max_iters="$2" sigfile sigfile_q
sigfile="$(mktemp "${TMPDIR:-/tmp}/dev_session_watch.XXXXXX")"
# Remove the snapshot on any exit; treat Ctrl-C / TERM as a clean stop (exit 0)
# rather than the 130/143 a bare signal would yield. The path is %q-escaped and
# embedded into the trap string now, so the EXIT handler neither dereferences a
# function-local that's out of scope by script-exit time (under `set -u`) nor
# breaks on a TMPDIR containing shell metacharacters.
printf -v sigfile_q '%q' "$sigfile"
# on_tty: a real, escape-capable terminal (not piped/redirected, not dumb) — so
# piped runs stay clean escape-free text and the tests stay valid, and a TERM
# without cursor control doesn't get raw control bytes sprayed at it.
local on_tty=""; [[ -t 1 && "${TERM:-}" != "dumb" ]] && on_tty=1
# use_alt: drive the board on the alternate screen buffer (like top/less) so the
# loop repaints in place instead of scrolling a fresh copy into scrollback, and
# the pre-watch screen is restored on exit. ONLY for an UNBOUNDED watch (the
# Ctrl-C-terminated dashboard) — a bounded --max-iters run must leave its final
# frame on the normal screen, not have the EXIT-trap restore wipe it on
# completion (it still repaints in place via the per-frame clear below).
local use_alt=""; [[ -n "$on_tty" && -z "$max_iters" ]] && use_alt=1
local _restore="rm -f -- $sigfile_q"
[[ -n "$use_alt" ]] && _restore="printf '\\033[?1049l'; $_restore"
# shellcheck disable=SC2064 # intentional: expand the escaped path/restore now, not on signal.
trap "$_restore" EXIT
# shellcheck disable=SC2064 # intentional: expand the escaped path/restore now, not on signal.
trap "$_restore; exit 0" INT TERM
[[ -n "$use_alt" ]] && printf '\033[?1049h'
# Sandbox root shown once in the banner so each row's SANDBOX cell can stay the
# short "<scope>/state" tail (see _list_render) instead of a wrapping abs path.
local sroot; sroot="$(_home_abbrev "$SESSIONS_DIR")"
# Loop until <max_iters> renders (if given), with no trailing sleep after the
# last frame. `--max-iters 0` renders zero times; unset runs until Ctrl-C.
local iter=0
while [[ -z "$max_iters" || "$iter" -lt "$max_iters" ]]; do
[[ -n "$on_tty" ]] && printf '\033[H\033[2J'
printf '[dev-session] watch — every %ss · %s · sandboxes under %s · Ctrl-C to stop\n\n' "$interval" "$(date '+%H:%M:%S')" "$sroot"
_list_render "$sigfile"
iter=$((iter + 1))
[[ -z "$max_iters" || "$iter" -lt "$max_iters" ]] && sleep "$interval"
done
# The loop's last command (the guarded sleep) is falsy on the final frame;
# return 0 explicitly so a clean finish isn't reported as failure under `set -e`.
return 0
}
cmd_path() {
local scope="${1:-}"
[[ -n "$scope" ]] || _die "usage: dev_session.sh path <scope>"
_slug_ok "$scope" || _die "scope must be a lowercase slug ([a-z0-9-]): got '$scope'"
local worktree="$SESSIONS_DIR/$scope/wt"
[[ -d "$worktree" ]] || _die "no session '$scope' (looked in $worktree)"
echo "$worktree"
}
# Print ONLY the canonical lane-contract text (no JSON, no side effects) — for
# a launcher that wants the raw preamble once and reuses it across every lane
# in a batch (e.g. a parallel-workflow fan-out path), rather than
# parsing it back out of each --headless JSON descriptor.
cmd_print_contract() {
_lane_contract
}
# Resolve exactly one same-repository open PR for a recorded lane branch/base.
# Prints `<repo-nwo> TAB <pr-number> TAB <listed-head>`; every caller then invokes
# gh/pr-watch in that same repository and the lane's own state sandbox.
_resolve_lane_pr() {
local branch="$1" base="$2"
local repo_json repo_nwo repo_owner pr_json pr_meta
local pr listed_base listed_branch listed_head listed_owner listed_cross
# GH_REPO overrides local checkout discovery. Unset it for identity
# resolution, then explicitly pin that resolved repository everywhere else.
repo_json="$(cd "$REPO_ROOT" && env -u GH_REPO gh repo view --json nameWithOwner)" \
|| _die "could not resolve the GitHub repository for $REPO_ROOT"
repo_nwo="$(printf '%s' "$repo_json" | python3 -c '
import json, sys
try:
row = json.load(sys.stdin)
except Exception:
raise SystemExit(1)
value = row.get("nameWithOwner") if isinstance(row, dict) else None
if not isinstance(value, str) or value.count("/") != 1 or not all(value.split("/")):
raise SystemExit(1)
print(value)
')" || _die "GitHub returned an invalid repository identity"
repo_owner="${repo_nwo%%/*}"
pr_json="$(cd "$REPO_ROOT" && GH_REPO="$repo_nwo" gh pr list --repo "$repo_nwo" --head "$branch" --state open \
--json number,baseRefName,headRefName,headRefOid,headRepositoryOwner,isCrossRepository --limit 2)" \
|| _die "could not resolve an open PR for '$branch'"
pr_meta="$(printf '%s' "$pr_json" | python3 -c '
import json, sys
rows = json.load(sys.stdin)
if len(rows) != 1:
raise SystemExit(2)
row = rows[0]
if type(row.get("number")) is not int:
raise SystemExit(2)
for key in ("baseRefName", "headRefName", "headRefOid"):
if not isinstance(row.get(key), str) or not row[key]:
raise SystemExit(2)
if type(row.get("isCrossRepository")) is not bool:
raise SystemExit(2)
owner = row.get("headRepositoryOwner") or {}
if isinstance(owner, dict):
owner = owner.get("login") or owner.get("name") or ""
def f(v):
# Same scrub, same reason as the merge gate further down this file. These
# extracted fields are tab-joined and the shell splits them, so a control
# character in an EARLIER field shifts every later one -- and the checks
# that follow (base, branch, head-repo owner, fork status, and head) are what
# keep a wrong-repository or wrong-revision PR off the merge path. Measured
# on the equivalent shape, empty trailing fields can collapse while the last
# name in a `read` absorbs a shifted remainder.
# A control character becomes a SPACE, never deleted, so a scrubbed value
# cannot fuse into a legitimate ref name; every comparison fails CLOSED.
# Unreachable through gh today -- a PR number is an int, and ref names and
# logins admit no control characters -- so this is defence in depth on an
# AUTHORIZATION path (#537), not a live bypass.
# NB: no apostrophes in this block -- it lives inside python3 -c SINGLE
# quotes, so one would terminate the string and break the extraction.
return "".join(" " if ch < "\x20" or ch == "\x7f" else ch for ch in str(v))
print("\t".join(f(row.get(k) or "") for k in ("number", "baseRefName", "headRefName", "headRefOid")) + "\t" + f(owner) + "\t" + ("true" if row["isCrossRepository"] else "false"))
')" || _die "expected exactly one open PR for '$branch'"
IFS=$'\t' read -r pr listed_base listed_branch listed_head listed_owner listed_cross <<< "$pr_meta"
[[ -n "$pr" ]] || _die "open PR metadata for '$branch' has no number"
[[ "$listed_base" == "$base" ]] \
|| _die "PR #$pr targets '$listed_base', not recorded base '$base'"
[[ "$listed_branch" == "$branch" ]] \
|| _die "PR #$pr head '$listed_branch' does not match recorded branch '$branch'"
[[ "$listed_owner" == "$repo_owner" ]] \
|| _die "PR #$pr head owner '$listed_owner' does not match repository owner '$repo_owner'"
[[ "$listed_cross" == "false" ]] \
|| _die "PR #$pr is cross-repository; same-repository lane required"
[[ -n "$listed_head" ]] || _die "PR #$pr has no head commit"
printf '%s\t%s\t%s\n' "$repo_nwo" "$pr" "$listed_head"
}
# Scope-aware front door for the PR watcher. Cockpit review happens outside the
# lane process, so this wrapper is what keeps its polls, acknowledgments, and
# head-bound review receipt in the same lane sandbox that cmd_merge re-checks.
cmd_pr_watch() {
local scope="${1:-}"
[[ -n "$scope" ]] || _die "usage: dev_session.sh pr-watch <scope> [pr-watch options]"
shift
_slug_ok "$scope" || _die "scope must be a lowercase slug ([a-z0-9-]): got '$scope'"
local session_dir="$SESSIONS_DIR/$scope" branch="" base="$DEFAULT_BASE" resolved repo_nwo pr listed_head
[[ -d "$session_dir" ]] || _die "no session '$scope' at $session_dir"
session_dir="$(cd "$session_dir" && pwd -P)" \
|| _die "could not resolve session '$scope' at $SESSIONS_DIR/$scope"
[[ -s "$session_dir/branch" ]] && branch="$(cat "$session_dir/branch")"
[[ -s "$session_dir/base" ]] && base="$(cat "$session_dir/base")"
[[ -n "$branch" ]] || _die "session '$scope' has no recorded branch"
_is_protected_branch "$branch" "$base" \
&& _die "refusing to watch protected branch '$branch' as a lane"
resolved="$(_resolve_lane_pr "$branch" "$base")" || return
IFS=$'\t' read -r repo_nwo pr listed_head <<< "$resolved"
[[ -n "$repo_nwo" && -n "$pr" ]] || _die "could not resolve lane PR identity"
GH_REPO="$repo_nwo" DEVKIT_STATE_ROOT="$session_dir/state" DEVKIT_ROOT="$REPO_ROOT" \
uv run "$SCRIPT_DIR/pr_watch.py" "$pr" "$@"
}
# Autonomous/headless self-merges must pass through this wrapper. The merge
# class is a deterministic artifact written at lane creation, and pr-watch is
# re-polled at act time so stale green state cannot authorize a merge.
cmd_merge() {
local scope="${1:-}"
[[ -n "$scope" ]] || _die "usage: dev_session.sh merge <scope>"
_slug_ok "$scope" || _die "scope must be a lowercase slug ([a-z0-9-]): got '$scope'"
local session_dir="$SESSIONS_DIR/$scope"
[[ -d "$session_dir" ]] || _die "no session '$scope' at $session_dir"
session_dir="$(cd "$session_dir" && pwd -P)" \
|| _die "could not resolve session '$scope' at $SESSIONS_DIR/$scope"
local merge_class="operator" branch="" base="$DEFAULT_BASE"
local resolved repo_nwo pr listed_head
local report mergeable validated_pr validated_base validated_head
[[ -s "$session_dir/merge_class" ]] && merge_class="$(cat "$session_dir/merge_class")"
[[ "$merge_class" == "self" ]] \
|| _die "lane '$scope' is operator-merge (or missing metadata); autonomous merge refused"
[[ -s "$session_dir/branch" ]] && branch="$(cat "$session_dir/branch")"
[[ -s "$session_dir/base" ]] && base="$(cat "$session_dir/base")"
[[ -n "$branch" ]] || _die "session '$scope' has no recorded branch"
if _is_protected_branch "$branch" "$base"; then
_die "refusing to merge protected branch '$branch' as a lane"
fi
resolved="$(_resolve_lane_pr "$branch" "$base")" || return
IFS=$'\t' read -r repo_nwo pr listed_head <<< "$resolved"
[[ -n "$repo_nwo" && -n "$pr" ]] || _die "could not resolve lane PR identity"
report="$(GH_REPO="$repo_nwo" DEVKIT_STATE_ROOT="$session_dir/state" DEVKIT_ROOT="$REPO_ROOT" \
uv run "$SCRIPT_DIR/pr_watch.py" "$pr" --json --no-persist)" \
|| _die "pr-watch failed for PR #$pr"
# Gate on `mergeable`: converged AND no deterministic merge blocker AND
# independent-review evidence bound to this head — either a recorded receipt
# or a configured bot's own review of it (#350). Which route answered sits in
# `review_evidence.route`; this gate reads neither, by the same rule that
# keeps it reading `mergeable` rather than re-deriving it.
# The report's `done` is an unchanged
# alias of `mergeable`, and every pre-split pr_watch emitted `done` with this
# same merge-authorization meaning — so either key is safe against a kit
# version skew, and `mergeable` additionally fails CLOSED when absent. Read
# `mergeable` because it is the precise name and is not the one retained for
# backward compatibility. The key that must NEVER gate a merge is `converged` —
# the watch-loop predicate ("anything left to fix?"), which is deliberately
# true on a green, comment-clean PR carrying no receipt.
# Read the flag pr_watch computes — never re-derive it here, or this gate
# becomes a second copy of the contract that can drift from the engine's.
IFS=$'\t' read -r mergeable validated_pr validated_base validated_head <<< "$(printf '%s' "$report" | python3 -c '
import json, sys
d = json.load(sys.stdin)
def f(v):
# Load-bearing for AUTHORIZATION, not cosmetics. These fields are emitted
# tab-separated and the shell splits on tabs, so a tab inside `pr` shifts
# every later field: `base` is then read out of `pr` and matches the recorded
# value while the real base goes unexamined. Measured without this: a report
# with base "WRONG" and an empty head was AUTHORIZED.
# A control character becomes a SPACE rather than being DELETED. Deleting it
# would fuse a hostile value into a legitimate-looking one -- a base of
# "tr<TAB>unk" would scrub to "trunk" and match the recorded base. A space
# cannot appear in a git ref, so every comparison below fails CLOSED instead.
# Only the report side is scrubbed, so in principle a recorded base holding a
# SPACE could collide with a reported one holding a tab. Unreachable: that
# value must be a real git ref twice over (cmd_new fetches it, and the PR
# baseRefName must equal it), and git ref names admit neither.
# Unreachable through gh today, exactly as the sibling scrub in
# _resolve_lane_pr says of itself -- these three fields are a PR number, a
# ref name and a commit sha, none of which admit a control character. So
# this is defence in depth on an AUTHORIZATION path (#537), not a live
# bypass. Said at BOTH sites deliberately: one candid copy beside one silent
# copy of the same fix reads as the silent one knowing something.
# NB: no apostrophes in this block -- it lives inside python3 -c SINGLE
# quotes, so one would terminate the string and break the extraction.
return "".join(" " if ch < "\x20" or ch == "\x7f" else ch for ch in str(v))
print("\t".join(("true" if d.get("mergeable") is True else "false", f(d.get("pr") or ""), f(d.get("base") or ""), f(d.get("head") or ""))))
')"
[[ "$mergeable" == "true" ]] \
|| _die "PR #$pr is not green, review-clean, and merge-ready; run pr-watch to convergence first"
[[ "$validated_pr" == "$pr" ]] \
|| _die "pr-watch validated PR #$validated_pr, not resolved PR #$pr"
[[ "$validated_base" == "$base" ]] \
|| _die "validated PR #$pr targets '$validated_base', not recorded base '$base'"
[[ -n "$validated_head" ]] || _die "pr-watch returned no validated head for PR #$pr"
[[ "$validated_head" == "$listed_head" ]] \
|| _die "PR #$pr head changed during validation; retry against the current head"
(cd "$REPO_ROOT" && GH_REPO="$repo_nwo" gh pr merge --repo "$repo_nwo" "$pr" --squash --delete-branch \
--match-head-commit "$validated_head") \
|| _die "GitHub merge failed for PR #$pr"
}
cmd_rm() {
local scope="" force=0 keep_branch=0
while [[ $# -gt 0 ]]; do
case "$1" in
--force) force=1; shift ;;
--keep-branch) keep_branch=1; shift ;;
-*) _die "unknown flag: $1" ;;
*) [[ -z "$scope" ]] && scope="$1" && shift || _die "unexpected arg: $1" ;;
esac
done
[[ -n "$scope" ]] || _die "usage: dev_session.sh rm <scope> [--force] [--keep-branch]"
_slug_ok "$scope" || _die "scope must be a lowercase slug ([a-z0-9-]): got '$scope'"
local session_dir="$SESSIONS_DIR/$scope"
local worktree="$session_dir/wt"
[[ -d "$worktree" ]] || _die "no session '$scope' at $worktree"
# Resolve the session's OWN base first (recorded by `new`; configured default) so the
# protected-branch guard below knows the real integration ref.
local expected_branch base dirty
base="$DEFAULT_BASE"
[[ -s "$session_dir/base" ]] && base="$(cat "$session_dir/base")"
# Resolve the branch THIS session OWNS — the name `new` recorded, else the
# default-namespace reconstruction `<prefix>/<scope>`. We NEVER read the
# worktree's live HEAD: a HEAD that wandered onto another branch (main after a
# post-merge checkout, or any unrelated branch parked here) must never become the
# delete target. A pre-metadata session created with a custom --prefix/--branch
# may therefore orphan its branch here (reconstruction can't know the custom
# name) — strictly safer than mis-deleting a wandered HEAD.
expected_branch=""
[[ -s "$session_dir/branch" ]] && expected_branch="$(cat "$session_dir/branch")"
[[ -z "${expected_branch//[[:space:]]/}" ]] && expected_branch="${DEFAULT_PREFIX}/${scope}"
# Determine dirtiness, distinguishing "clean" from "couldn't tell". Under
# `set -euo pipefail` a broken worktree (a dangling gitlink) makes `git status`
# non-zero; capturing it in an `if` condition keeps set -e from aborting, and we
# mark it "?" (undeterminable) so it's treated as POSSIBLY-dirty — requiring
# --force rather than silently discarding work or aborting opaquely.
if ! dirty="$(git -C "$worktree" status --porcelain 2>/dev/null | wc -l | tr -d ' ')"; then
dirty="?"
fi
if [[ "$dirty" != "0" && "$force" -eq 0 ]]; then
_die "worktree has uncommitted or undeterminable changes ($dirty) — commit/push first, or use --force to discard"
fi
echo "[dev-session] removing worktree $worktree"
if [[ "$force" -eq 1 ]]; then
git -C "$REPO_ROOT" worktree remove --force "$worktree" \
|| _die "forced worktree removal failed; session preserved at $session_dir"
else
# Git repeats the cleanliness check at removal time. Do not add --force
# here or in a fallback: a file can arrive after the status probe above,
# and the remove command is the last guard against discarding it.
git -C "$REPO_ROOT" worktree remove "$worktree" \
|| _die "worktree changed or could not be removed; session preserved (retry, or use --force to discard)"
fi