Repository navigation
Expand file tree
/
Copy pathworktree-create.sh
More file actions
executable file
·1410 lines (1328 loc) · 66.5 KB
/
Copy pathworktree-create.sh
File metadata and controls
executable file
·1410 lines (1328 loc) · 66.5 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
# worktree-create.sh — shared worktree-creation helper (Phase A).
#
# Single owner of worktree creation for this plugin: external-root path
# computation `<root>/<owner>-<repo>-<slug>`, slug sanitization, the branch name
# (worktree_branch_naming), base-ref resolution (`worktree.baseRef` fresh|head), `git worktree add`, arming the
# `git worktree lock` liveness guard (#2257) with an optional --session-id
# claim token, the `.worktreeinclude` local-file copy, and `npm ci` when the
# new tree has a package-lock.json. The `.worktreeinclude` copy Claude Code
# performs for its
# native worktrees (EnterWorktree / --worktree) is bypassed when a worktree is
# created with `git worktree add` directly, so this helper reimplements it.
#
# Consumers:
# - Phase A (now): the `/worktree create` skill routes through this helper,
# then calls EnterWorktree(path:) on the printed path to enter the worktree.
# - Phase B (gated on two upstream Claude Code behaviors still being verified):
# the `WorktreeCreate` hook becomes a thin stdin adapter (parse `.name`) that
# calls this same helper.
# The flag CLI is the stable seam both consumers share.
#
# Root-resolution contract, most specific first (#2610/#2612):
# 1. an explicit --root/--root-file — a per-invocation caller decision;
# 2. `worktreeroot.path`, read from the
# TARGET repository with includes on, so git's own includeIf machinery
# supplies per-identity and per-repository answers
# (reference/worktree-root-convention.md is the convention's owner doc);
# 3. --fallback-root/--fallback-root-file — the machine-global worktree_root
# plugin option, which only this plugin can read and therefore ranks below
# the key every consumer can read;
# 4. the plugin data directory supplied via --data-root-file, yielding
# <data-dir>/worktrees;
# 5. absent all of those, the helper refuses (exit 3).
# It never falls back to Claude Code's in-repo `.claude/worktrees/`, whose nested
# placement is what the nesting invariant forbids. That claim is owned, measured
# and dated in exactly one place and is not restated here:
# skills/worktree/reference/nesting-invariant.md § "The nesting invariant, dated measurement". The data dir is
# never read from the environment — see the resolution block.
#
# Output contract: on success the created worktree path is the SOLE stdout line
# (machine-parseable); all diagnostics go to stderr.
#
# Exit codes:
# 0 success — worktree created, or an existing one this session may claim
# reused (see "Reuse" below); path on stdout. A failed, skipped or timed-out
# dependency install still exits 0 and names the failure on stderr
# 2 usage error — unknown/missing flag, or a --name git rejects as a branch
# 3 refuse — no usable external root, root inside a repository, or a
# cross-drive root on Windows at any resolution rung including the
# unconfigured plugin-data-dir default (guidance on stderr); nothing created
# 4 environment error: not a git repo, the target path or the branch is held
# by another worktree or session, `git worktree add` failed, or the tree
# was created and then left incomplete because a `.worktreeinclude` file
# failed to copy. That last case shares exit 5's shape, a tree on disk that
# is not what the caller asked for, so a caller treating 4 as "nothing was
# created" is wrong for it
# 5 worktree created, but `git worktree lock` failed: the path is still the
# sole stdout line and the tree exists, yet it carries no claim for a
# cleanup sweep to read (a warning names it on stderr)
set -uo pipefail
# shellcheck source=lib/worktree-facts.sh
source "${BASH_SOURCE[0]%/*}/lib/worktree-facts.sh" || { echo "error: cannot load lib/worktree-facts.sh" >&2; exit 4; }
PROG=${0##*/}
# shellcheck source=worktree-root-resolve.sh
source "${BASH_SOURCE[0]%/*}/worktree-root-resolve.sh" || { echo "error: cannot load worktree-root-resolve.sh" >&2; exit 4; }
# Lexical path collapse, shared inside this plugin with the worktree gates and
# the claim helper. Sourced for worktree_path_normalize alone: the file defines
# functions only and pulls in no library of its own.
# shellcheck source=../hooks/worktree-path-lib.sh
source "${BASH_SOURCE[0]%/*}/../hooks/worktree-path-lib.sh" || { echo "error: cannot load hooks/worktree-path-lib.sh" >&2; exit 4; }
# --- same-drive helpers (begin) — sourced by worktree-create.test.sh for unit tests ---
# windows_drive_letter <path> — echo the drive letter (A–Z) when <path> is
# drive-anchored; otherwise return non-zero. Recognized shapes (#2764):
# - `X:/...` — git / Windows absolute
# - `/cygdrive/x/...` — Cygwin (unambiguous on every host)
# - `/x/...` — MSYS/Git Bash single-letter drive form, only when uname is
# MINGW*/MSYS*/CYGWIN* (same gate as landed-work.sh path_key). On POSIX a
# `/d/...` path is an ordinary directory and must stay inert so `/usr` is
# never mistaken for drive U:.
windows_drive_letter() {
local path="$1"
if [[ "$path" =~ ^([A-Za-z]):(/|$) ]] || [[ "$path" =~ ^/cygdrive/([A-Za-z])(/|$) ]]; then
printf '%s' "${BASH_REMATCH[1]^^}"
return 0
fi
case "$(uname -s 2>/dev/null || true)" in
MINGW* | MSYS* | CYGWIN*)
if [[ "$path" =~ ^/([A-Za-z])(/|$) ]]; then
printf '%s' "${BASH_REMATCH[1]^^}"
return 0
fi
;;
*) ;;
esac
return 1
}
# check_same_drive <repo-toplevel> <worktree-path> — enforce the
# same-drive-on-Windows invariant for worktree placement (#2764, #2806).
#
# `git worktree move` is `rename()` and cannot cross a volume boundary on
# Windows (EXDEV / "Invalid cross-device link" / "Improper link"). Every
# resolution rung refuses (return 3), including rung 4 — the unconfigured
# plugin-data-dir default. Warn-and-proceed at rung 4 left unconfigured
# cross-drive machines creating worktrees that `git worktree move` cannot
# relocate; a non-zero exit is also the only channel that surfaces on the
# WorktreeCreate hook path (exit-0 stderr is dropped to the debug log).
# Inert when either path lacks a drive letter.
#
# Returns 0 to proceed, 3 to refuse. Caller exits on non-zero.
check_same_drive() {
local repo_path="$1" wt_path="$2" repo_drive wt_drive
repo_drive=$(windows_drive_letter "$repo_path") || return 0
wt_drive=$(windows_drive_letter "$wt_path") || return 0
[[ "$repo_drive" == "$wt_drive" ]] && return 0
cat >&2 <<EOF
$PROG: set \`worktreeroot.path\` (or the plugin's \`worktree_root\` option) to a directory on drive ${repo_drive}: — refusing a cross-drive root.
repository: $repo_path (drive ${repo_drive}:)
worktree: $wt_path (drive ${wt_drive}:)
git worktree move uses rename(), which cannot cross volumes on Windows
(EXDEV / Improper link). The includeIf-capable \`worktreeroot.path\` key
is the per-repository remedy:
git config worktreeroot.path <same-drive-root>
EOF
return 3
}
# --- same-drive helpers (end) ---
# run_capped <seconds> <command...> — run <command> in the background and stop
# waiting after <seconds>: return its status, or kill it and return 124 at the
# cap. Polls with `kill -0` because `timeout` is not on macOS by default. `set -m`
# starts the command in its own process group, so the cap kills the whole group
# (npm's lifecycle scripts included), not just the top pid; setsid is not on macOS.
run_capped() {
local cap="$1" pid ticks=0
shift
set -m
"$@" &
pid=$!
set +m
while kill -0 "$pid" 2>/dev/null; do
if ((ticks >= cap * 10)); then
kill -- -"$pid" 2>/dev/null
wait "$pid" 2>/dev/null
return 124
fi
sleep 0.1
ticks=$((ticks + 1))
done
wait "$pid"
}
usage() {
cat >&2 <<EOF
$PROG — shared worktree-creation helper.
Usage:
$PROG --name <name> [--root <dir> | --root-file <path>]
[--fallback-root <dir> | --fallback-root-file <path>]
[--data-root-file <path>] [--base-ref fresh|head] [--repo-dir <dir>]
[--session-id <id>] [--remove-input-files]
Root resolution, most specific first:
--root/--root-file (explicit, per invocation), then worktreeroot.path
read from the target repository (includes on, --type=path, last value
wins — includeIf supplies per-identity/per-repo answers), then
--fallback-root/--fallback-root-file (the machine-global plugin option), then
--data-root-file (<data-dir>/worktrees). Absent all: refuse (exit 3).
Options:
--name <name> Branch/worktree name (e.g. feat/my-feature). Required.
Max 64 chars; each /-separated segment holds only letters,
digits, dots, underscores, and dashes. Also checked against
git's own branch-name grammar, so a name that satisfies the
character rules but is an illegal ref (feat/foo..bar,
foo.lock, HEAD) is refused (exit 2), not left to git later.
That grammar check runs after the repository is resolved,
so exits 3 and 4 can precede it. The branch is the name
unless the repository's tracked
docs/conventions/source-control.yaml sets
worktree_branch_naming: conventional-commits, which
derives <type>/<description> from it (the stderr note
names the branch); the grammar check then applies to the
derived branch. The directory slug always comes from the
name.
--root <dir> External worktree root, passed directly as a process
argument (e.g. from a hook or CLI caller — no shell
re-quoting of the value happens on that path). Wins over
every configured source: an explicit per-invocation choice
outranks per-repo config. An empty value or an unexpanded
\${user_config.*} token falls through to the config key /
fallback / data-root rungs — never to the in-repo
.claude/worktrees/ default, whose nested placement the
nesting invariant forbids (skills/worktree/reference/nesting-invariant.md).
Mutually exclusive with --root-file.
--fallback-root <dir>
The machine-global worktree_root plugin option, consulted
only when neither an explicit --root/--root-file nor
worktreeroot.path yields
a value. Ranks
below the key deliberately: the key is per-repo/per-identity
capable and readable by every consumer, while the plugin
option is machine-wide and plugin-only (#2612). Same
unset/empty/unexpanded-token handling as --root. Mutually
exclusive with --fallback-root-file.
--fallback-root-file <path>
Read the fallback root from <path> — the same byte-verbatim
file channel as --root-file, for a caller that cannot place
the raw-substituted \${user_config.worktree_root} value in
shell source safely. Mutually exclusive with --fallback-root.
--data-root-file <path>
Read the plugin's data directory from <path>, used as the
root only when no --root/--root-file value is configured
(the resolved root is then <data-dir>/worktrees). Same
byte-verbatim file channel as --root-file, and combinable
with it: a configured root always wins. The caller obtains
the value by substituting \${CLAUDE_PLUGIN_DATA} into its
own SKILL.md body — never from the environment, which is
not per-plugin in a Bash-tool subprocess. A file still
holding the literal token is treated as absent.
--root-file <path> Read the external worktree root from <path> instead of a
--root argument. For a caller that cannot place the value
in shell source safely — e.g. a skill rendering
\${user_config.worktree_root} into markdown, which is raw
text substitution, not shell-escaped — write the value to
a temp file through a non-shell channel (the Write tool's
JSON content parameter), never a quoted literal or a
heredoc body: a value containing the heredoc delimiter
line ends the heredoc early and the remainder is parsed
as commands. The file's bytes are the root, verbatim and
unterminated — a newline anywhere in it, trailing
included, is a usage error (exit 2), never trimmed, and so
is a NUL byte. The same unset/empty/unexpanded-token
refuse (exit 3) applies to the file's content. Mutually
exclusive with --root: supplying both is a usage error
even when one of the two values is empty.
--base-ref <ref> fresh (default) branches from the default remote's default
branch; head branches from the repo's current HEAD. Omitted
defaults to fresh; the caller passes the effective Claude
worktree.baseRef setting (a settings.json key, not git config).
fresh picks the remote generically — the current branch's
configured remote, else origin, else the sole remote — so a
clone made with 'git clone -o upstream' resolves upstream's
default branch. fresh first fetches that branch on every
run (capped at 5s, prompts off); a failed or timed-out
fetch warns, keeps the cached ref, and reports the base
as <remote>/<branch>@<sha>, not refreshed. With no
resolvable remote, or an uncached <remote>/HEAD, it
warns and branches from local HEAD.
--repo-dir <dir> Source repository directory. Default: current directory.
--session-id <id> Session id recorded in the git worktree lock reason as
\`session <id> since\`, the token worktree-claim.sh
check-enter matches (exit 0 for this id, exit 4 for any
other). The id must match ^[A-Za-z0-9._:-]{1,128}$; any
other value is a usage error (exit 2) and creates nothing.
Omitted or empty: the reason names the helper, host, and
start time only and carries no session token, so
check-enter reports a foreign claim for every session id.
This flag is the only session source. An omitted id is
never filled in from the host name or the environment, and
is not reported as any session's claim.
--remove-input-files
On exit, whatever the exit code, delete the files handed
to --root-file, --fallback-root-file and --data-root-file,
then rmdir each one's directory (left in place when it is
not empty). Armed when the flag is parsed: a usage error
before it, or a missing library, leaves the files. For a
caller that wrote those files into a temp directory and
would otherwise need its own rm.
-h, --help Show this help.
Dependencies: when the new worktree has a package-lock.json, the helper runs
npm ci in it (output on stderr), capped at WORKTREE_CREATE_DEPS_CAP_SECONDS
(default 45). A missing npm, a failed install or the cap only warns on stderr;
the exit code is unchanged.
Reuse: a worktree already at the target path, on the branch this run would use,
is printed as it is (no copy, no npm ci) when its lock names --session-id, when
it is unlocked (claimed first), or when worktree-claim.sh stale proves its
session's claim stale (handed over). Anything else there, a live or
session-less claim, or no --session-id, exits 4. An existing branch checked out
nowhere is checked out without -b and --base-ref does not apply; one checked out
in another worktree exits 4, naming it.
On success the worktree path is printed as the sole stdout line, for the
caller to feed to EnterWorktree(path:).
Exit codes: 0 success · 2 usage · 3 refuse (no usable root) · 4 environment ·
5 created but not locked.
EOF
}
name=""
root=""
root_given=0
root_file=""
root_file_given=0
fallback_root=""
fallback_root_given=0
fallback_root_file=""
fallback_root_file_given=0
data_root_file=""
data_root_file_given=0
base_ref=""
existing_branch=0
repo_dir="."
session_id=""
# remove_input_files_on_exit — the EXIT trap behind --remove-input-files, armed
# when the flag is parsed so a later usage error still cleans up. Reads the path
# variables at exit time. rm -f
# and rmdir only: a directory holding anything else is left alone.
remove_input_files_on_exit() {
local file
for file in "$root_file" "$fallback_root_file" "$data_root_file"; do
[[ -n "$file" ]] || continue
rm -f -- "$file"
rmdir -- "$(dirname -- "$file")" 2>/dev/null || true
done
}
# need_value <flag> — guard against a value-taking flag given as the last token
# with no argument. Without this, `shift 2` on a single remaining positional
# fails and leaves $# unchanged, spinning the loop forever.
need_value() {
if [[ $# -lt 2 ]]; then
printf '%s: %s requires a value\n' "$PROG" "$1" >&2
exit 2
fi
}
while [[ $# -gt 0 ]]; do
case "$1" in
--name)
need_value "$@"
name="$2"
shift 2
;;
--root)
need_value "$@"
root="$2"
root_given=1
shift 2
;;
--root-file)
need_value "$@"
root_file="$2"
root_file_given=1
shift 2
;;
--fallback-root)
need_value "$@"
fallback_root="$2"
fallback_root_given=1
shift 2
;;
--fallback-root-file)
need_value "$@"
fallback_root_file="$2"
fallback_root_file_given=1
shift 2
;;
--data-root-file)
need_value "$@"
data_root_file="$2"
data_root_file_given=1
shift 2
;;
--base-ref)
need_value "$@"
base_ref="$2"
shift 2
;;
--existing-branch)
existing_branch=1
shift
;;
--repo-dir)
need_value "$@"
repo_dir="$2"
shift 2
;;
--session-id)
need_value "$@"
session_id="$2"
shift 2
;;
--remove-input-files)
trap remove_input_files_on_exit EXIT
shift
;;
-h | --help)
usage
exit 0
;;
*)
printf '%s: unknown argument: %s\n' "$PROG" "$1" >&2
usage
exit 2
;;
esac
done
if [[ -z "$name" ]]; then
printf '%s: --name is required\n' "$PROG" >&2
exit 2
fi
# Mutual exclusion keys off whether each flag APPEARED, not whether its value is
# non-empty: `--root '' --root-file f` is still a caller naming two sources, and
# treating the empty one as absent would silently pick the other.
if ((root_given && root_file_given)); then
printf '%s: --root and --root-file are mutually exclusive\n' "$PROG" >&2
exit 2
fi
if ((fallback_root_given && fallback_root_file_given)); then
printf '%s: --fallback-root and --fallback-root-file are mutually exclusive\n' "$PROG" >&2
exit 2
fi
# --root-file: read the root from the file rather than a process argument. This
# is the out-of-band handoff a skill uses when it cannot place the
# raw-substituted ${user_config.worktree_root} value in shell source safely (see
# the --root-file usage text above) — the file's bytes are the root (or, when
# unset, the literal unexpanded ${user_config...} token), placed there through a
# non-shell channel so no expansion, quote-processing, or heredoc-delimiter
# matching touches it before it lands here.
#
# The whole file is the value, byte for byte: a single quote, `$`, or a backtick
# passes through unchanged, and no line terminator is assumed or stripped. A
# newline anywhere — trailing included — is therefore a rejection, not a trim.
# Reading a "first line" instead would silently proceed with a root the caller
# never asked for, and a trailing newline is indistinguishable from a root whose
# own last byte is a newline, so neither can be forgiven without guessing.
# read_path_file <flag-name> <path> — read a path a caller handed over out-of-band
# through a file, with every byte intact, into the global PATH_FILE_VALUE. Shared
# by --root-file and --data-root-file so the second channel cannot drift from the
# first's guards. Exits 2 on anything that is not a usable single-line path.
#
# Assigns to a global rather than echoing: the guards below must terminate the
# SCRIPT, and an `exit` inside a `$( )` capture kills only the subshell — the
# caller would sail on with an empty root. Verified, not assumed.
read_path_file() {
local flag="$1" file="$2" value
PATH_FILE_VALUE=""
if [[ ! -f "$file" ]]; then
printf '%s: %s not found: %s\n' "$PROG" "$flag" "$file" >&2
exit 2
fi
# A NUL byte has to be caught BEFORE the value reaches a shell variable: command
# substitution drops NULs (with a warning on stderr the caller may never see),
# which would turn `/root-<NUL>suffix` into `/root-suffix` and create a worktree
# at a path nobody supplied. Compare the byte count with and without NULs rather
# than matching on one, since the variable can never hold it.
if (($(wc -c <"$file") != $(tr -d '\000' <"$file" | wc -c))); then
printf '%s: %s %s contains a NUL byte; the file holds the path verbatim and no pathname can contain NUL\n' \
"$PROG" "$flag" "$file" >&2
exit 2
fi
value=$(
cat "$file"
printf x
) # printf x defends the value's own trailing bytes from $( ) stripping
value=${value%x}
if [[ "$value" == *$'\n'* ]]; then
printf '%s: %s %s contains a newline byte; the file holds the path verbatim and a path with a newline in it is malformed configuration, not a value to trim\n' \
"$PROG" "$flag" "$file" >&2
exit 2
fi
PATH_FILE_VALUE="$value"
}
if ((root_file_given)); then
read_path_file --root-file "$root_file"
root="$PATH_FILE_VALUE"
fi
if ((fallback_root_file_given)); then
read_path_file --fallback-root-file "$fallback_root_file"
fallback_root="$PATH_FILE_VALUE"
fi
# Validate the name up front against the EnterWorktree schema: max 64 chars, and
# each '/'-separated segment contains only letters, digits, dots, underscores,
# and dashes. Reject invalid names loudly (exit 2) here rather than let
# `git worktree add` fail opaquely downstream. The directory slug always comes
# from the name; the branch is the name unless worktree_branch_naming derives
# one (see "Branch naming" below).
if ((${#name} > 64)); then
printf '%s: --name %q exceeds 64 characters\n' "$PROG" "$name" >&2
exit 2
fi
if [[ ! "$name" =~ ^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*$ ]]; then
printf '%s: --name %q is not a valid worktree/branch name (each /-separated segment: letters, digits, dots, underscores, dashes only)\n' "$PROG" "$name" >&2
exit 2
fi
# Same grammar as worktree-claim.sh valid_session_id. Empty is omitted, not
# invalid: the lock reason then carries no session token (see usage). A value
# outside this class could break the `session <id> since` match, so refuse
# before creating anything.
if [[ -n "$session_id" ]] && [[ ! "$session_id" =~ ^[A-Za-z0-9._:-]{1,128}$ ]]; then
printf '%s: --session-id must match ^[A-Za-z0-9._:-]{1,128}$\n' "$PROG" >&2
exit 2
fi
# The remaining name check — git's own ref grammar — needs a healthy repository
# to run in, so it waits until $toplevel is resolved below.
# root_is_unset <value> — an empty value or an unexpanded ${user_config.*}
# token (what Claude Code leaves when the key is unset) counts as unset. Shared
# by the explicit root and the fallback root so the two channels cannot drift.
#
# SC2016: the single-quoted ${user_config token is matched literally on purpose —
# we are detecting the UNexpanded placeholder, so expansion here would be a bug.
# shellcheck disable=SC2016
root_is_unset() {
[[ -z "$1" || "$1" == *'${user_config'* ]]
}
# canonicalize_root <value> <source-label> — apply the two Windows-path guards
# every root source must pass through, whichever rung supplied it, into the
# global CANONICAL_ROOT. A global, not an echo: the drive-relative refusal must
# terminate the SCRIPT, and an exit inside a $( ) capture kills only the subshell.
#
# 1. Canonicalize a Windows backslash root to the forward-slash grammar git
# emits. On a Windows shell `\` is a path separator `git worktree add`
# resolves, but the containment guard below cannot: the ancestor walk splits
# on `/`, so an all-backslash `${probe%/*}` never changes (parent == probe),
# the loop breaks on its first iteration, and the whole guard block is
# skipped — a backslash root then sails through and git lands the checkout
# inside the repo/.git. Swapping `\`→`/` up front routes a backslash root
# through the SAME anchor + worktree_path_normalize + walk as a fwd-slash root
# (one code path, not a parallel one). Gated to Windows shells via $OSTYPE —
# off-Windows `\` is a legal filename byte and must be left untouched.
# (cygpath is intentionally avoided: it resolves relative paths against the
# CWD, not $toplevel, and rewrites MSYS `/tmp` paths — both diverge from this
# helper's contract; a pure separator swap defers all resolution to the
# existing machinery.)
# 2. Reject drive-relative roots (`C:foo` with no separator after the colon).
# Git for Windows resolves them against the drive's per-directory CWD, which
# bypasses the containment ancestor walk (#962).
canonicalize_root() {
local value="$1" source="$2"
if [[ "$value" == *\\* && ("$OSTYPE" == msys || "$OSTYPE" == cygwin) ]]; then
local bslash="\\" fwd="/"
value="${value//"$bslash"/"$fwd"}"
fi
if [[ "$value" =~ ^[A-Za-z]:[^/] ]]; then
printf '%s: %s %q is drive-relative; use an absolute path (e.g. C:/worktrees)\n' \
"$PROG" "$source" "$value" >&2
exit 2
fi
CANONICAL_ROOT="$value"
}
# Unconfigured root: detected here, resolved after the repository is known below
# (the worktreeroot.path rung needs the repository, and the data-dir rung
# stays last).
root_unset=0
if root_is_unset "$root"; then
root_unset=1
else
canonicalize_root "$root" --root
root="$CANONICAL_ROOT"
fi
# Resolve the source repository top level.
if ! toplevel=$(git -C "$repo_dir" rev-parse --show-toplevel 2>/dev/null); then
# Remedy first: this line is surfaced verbatim to a user whose worktree
# creation just failed, and a bare diagnosis leaves them nothing to do. There
# is no worktree to create outside a repository, so the actionable answer is
# the harness-side stand-down, not a flag of this script's.
printf '%s: run this from inside a git repository, or pass --repo-dir pointing at one; for a Claude Code background session at a non-repository directory, set worktree.bgIsolation to "none" in settings so it edits in place; --worktree and subagent isolation need a repository\n' "$PROG" >&2
printf '%s: --repo-dir is not inside a git repository: %s\n' "$PROG" "$repo_dir" >&2
exit 4
fi
# Rung 2 (#2610): worktreeroot.path — the machine truth for worktree
# placement, readable by anything that can run `git config --get`, and the
# layer where git's own includeIf machinery supplies per-identity and
# per-repository answers (#2612). Owner doc:
# reference/worktree-root-convention.md. Resolution lives in
# worktree-root-resolve.sh so every consumer shares last-wins and empty-last
# fallthrough.
#
# Three reading rules, each load-bearing:
# * Read from $toplevel — the TARGET repository — so an includeIf condition
# evaluates against that repository's gitdir, never this process's CWD.
# * NO scope flag. git-config(1): includes default OFF "when a specific file
# is given (e.g., using --file, --global, etc)" and ON when searching all
# files. A scoped read silently skips every includeIf, which is the
# per-identity layer working by accident or not at all.
# * The dubious-ownership gate is the successful `rev-parse --show-toplevel`
# above: under dubious ownership (safe.directory) that resolution FAILS
# (exit 4 above), so this read can never mistake the global default for the
# repository's answer — the silent rc=0 fallback the convention doc warns
# about.
if ((root_unset)); then
worktree_root_resolve "$toplevel" || true
if [[ -n "${WORKTREE_ROOT_VALUE:-}" ]]; then
canonicalize_root "$WORKTREE_ROOT_VALUE" "$WORKTREE_ROOT_KEY_USED"
root="$CANONICAL_ROOT"
root_unset=0
printf '%s: worktree root resolved from the %s git config key\n' \
"$PROG" "$WORKTREE_ROOT_KEY_USED" >&2
fi
fi
# Rung 3: the machine-global plugin option, handed over as --fallback-root or
# --fallback-root-file. Below the git key on purpose: the key is per-repo capable
# and readable by every consumer; the option is machine-wide and plugin-only.
if ((root_unset)) && ! root_is_unset "$fallback_root"; then
canonicalize_root "$fallback_root" --fallback-root
root="$CANONICAL_ROOT"
root_unset=0
fi
# Rung 4: the plugin's own data directory, delivered by the caller through
# --data-root-file.
#
# The value cannot be read from the environment here. In a general Bash-tool
# subprocess — which is what every caller of this helper runs in — CLAUDE_PLUGIN_DATA
# is not scoped to the invoking plugin; the repository's probe recorded it naming an
# unrelated installed plugin's data directory (docs/extensibility-contract-smoke-tests.md,
# Test B). It IS reliable inside a plugin's own declared command, so a future
# WorktreeCreate hook passes it as a --root process argument instead.
#
# What the skill CAN do is substitute ${CLAUDE_PLUGIN_DATA} into its own SKILL.md
# body, where it renders per-plugin (same probe, Test D), and hand the rendered
# value over through the existing non-shell file channel. That is this flag.
#
# A repository-derived default was considered and rejected: a sibling of the
# checkout lands inside a repository-discovery tree under a layout like
# <root>/github.com/<owner>/<repo>, where `ghq list` then enumerates each worktree
# as a repository of its own (a leading dot does not hide it) — the very pollution
# the worktree skill tells users to keep their configured root clear of.
#
# Fail-closed by construction: if substitution ever regresses, the file carries the
# literal token, which is detected below and refused rather than turned into a
# relative path inside the repository. The containment guard further down still
# validates whatever root wins.
if ((root_unset)); then
data_root=""
if ((data_root_file_given)); then
read_path_file --data-root-file "$data_root_file"
data_root="$PATH_FILE_VALUE"
# A caller whose substitution did not fire hands over the literal token. That
# is not a directory, and treating it as one would create `${CLAUDE_PLUGIN_DATA}`
# as a relative path in the repository — the nesting this helper exists to
# prevent. Detect it and fall through to the refusal below.
# shellcheck disable=SC2016
[[ "$data_root" == *'${CLAUDE_PLUGIN_DATA'* ]] && data_root=""
fi
if [[ -z "$data_root" ]]; then
cat >&2 <<EOF
$PROG: no worktree root available — refusing to create a worktree.
Set the \`worktreeroot.path\` git config key to an external root (a path
OUTSIDE every repository), then retry:
git config --global worktreeroot.path <root>
Any tool that can run \`git config --get\` can honor that key; the
source-control plugin's \`worktree_root\` option (via \`/plugin\`) also works but
only this plugin can read it. Convention and per-identity layering:
reference/worktree-root-convention.md.
Not falling back to the in-repo .claude/worktrees/ default: a worktree nested
inside a checkout can pick up that checkout's path-scoped rules as well as its
own. Measurement, disputed arms and expiry:
skills/worktree/reference/nesting-invariant.md "The nesting invariant, dated measurement".
EOF
exit 3
fi
root="${data_root%/}/worktrees"
printf '%s: worktree_root is not configured; defaulting to %s\n' "$PROG" "$root" >&2
# SC2016: the backticks are literal markdown in guidance text, not a command
# substitution — expansion is exactly what must NOT happen here.
# shellcheck disable=SC2016
printf '%s: set the plugin'\''s `worktree_root` directory key to place worktrees elsewhere.\n' "$PROG" >&2
fi
# --- Branch naming ---------------------------------------------------------------
# worktree_branch_naming in the repository's tracked
# docs/conventions/source-control.yaml picks how the new branch is named from
# --name; reference/config-resolution.md "YAML keys" owns the values:
# verbatim (default) the branch is --name itself;
# conventional-commits <type>/<description>. Only a `/` marks a type: the first
# segment, matched in any case, is a Conventional Commits
# type, an alias of one, or an entry of
# worktree_branch_extra_prefixes, and the rest is the
# description. Any other name goes whole under
# worktree_branch_default_type (default chore).
# A value the helper cannot use, an untracked file, or a YAML the parser rejects
# keeps the name verbatim with a note on stderr, and so does a name that
# sanitizes to nothing. A configuration error never refuses a worktree: the
# WorktreeCreate hook has no fallback, so a refusal would fail every isolated
# spawn in the repository. The derivation is many-to-one (feat/x and feature/x),
# so a second name can meet its branch checked out elsewhere; "Reuse" below
# refuses that, naming the holder. --existing-branch names a branch that already
# exists, so it is never derived.
CONVENTION_YAML_REL="docs/conventions/source-control.yaml"
branch_naming="verbatim"
branch_default_type="chore"
branch_extra_prefixes=()
# branch_type_is_valid <value> — one lowercase segment, safe as a ref component.
branch_type_is_valid() { [[ "$1" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]]; }
# read_branch_naming — fill the three branch_* globals from the team YAML under
# $toplevel. Loads the reader only when the file exists, so a repository without
# one pays no process for this.
read_branch_naming() {
local records key value naming="" default_type=""
[[ -f "$toplevel/$CONVENTION_YAML_REL" ]] || return 0
# shellcheck source=../lib/convention-key.sh
source "${BASH_SOURCE[0]%/*}/../lib/convention-key.sh" || {
printf '%s: cannot load lib/convention-key.sh; keeping the branch name verbatim\n' "$PROG" >&2
return 0
}
convention_key_tracked "$toplevel" "$CONVENTION_YAML_REL" || return 0
if ! records="$(convention_key_records "$toplevel")"; then
printf '%s: the YAML parser rejected %s; keeping the branch name verbatim\n' "$PROG" "$CONVENTION_YAML_REL" >&2
return 0
fi
while IFS=$'\t' read -r key value; do
case "$key" in
worktree_branch_naming) naming="$value" ;;
worktree_branch_default_type) default_type="$value" ;;
worktree_branch_extra_prefixes.[0-9]*)
if branch_type_is_valid "$value"; then
branch_extra_prefixes+=("$value")
else
printf '%s: worktree_branch_extra_prefixes entry %q is not one lowercase segment; skipping it\n' "$PROG" "$value" >&2
fi
;;
*) ;;
esac
done <<<"$records"
case "$naming" in
"" | verbatim) ;;
conventional-commits) branch_naming="$naming" ;;
*) printf '%s: worktree_branch_naming %q in %s is not verbatim or conventional-commits; keeping the branch name verbatim\n' \
"$PROG" "$naming" "$CONVENTION_YAML_REL" >&2 ;;
esac
if [[ -n "$default_type" ]]; then
if branch_type_is_valid "$default_type"; then
branch_default_type="$default_type"
else
printf '%s: worktree_branch_default_type %q in %s is not one lowercase segment; using chore\n' \
"$PROG" "$default_type" "$CONVENTION_YAML_REL" >&2
fi
fi
}
# branch_ref_segment <text> — <text> as one ref-safe segment, into the global
# BRANCH_SEGMENT (a global, so no subshell is forked): every character outside
# [A-Za-z0-9._-], `/` included, becomes `-`; runs of `.` and of `-` collapse;
# leading and trailing `-`, `.` and `_` go; then a trailing `.lock` goes.
branch_ref_segment() {
local s="${1//[^A-Za-z0-9._-]/-}"
while [[ "$s" == *..* ]]; do s="${s//../.}"; done
while [[ "$s" == *--* ]]; do s="${s//--/-}"; done
while [[ "$s" == [-._]* ]]; do s="${s#?}"; done
while [[ "$s" == *[-._] ]]; do s="${s%?}"; done
BRANCH_SEGMENT="${s%.lock}"
}
# derive_conventional_branch <name> — the conventional-commits branch for
# <name>, into the global `branch`.
derive_conventional_branch() {
local name="$1" type canonical="" prefix
if [[ "$name" == */* ]]; then
type="${name%%/*}"
type="${type,,}"
case "$type" in
feat | feature) canonical="feat" ;;
fix | bugfix | hotfix) canonical="fix" ;;
docs | documentation | doc) canonical="docs" ;;
test | tests) canonical="test" ;;
perf | performance) canonical="perf" ;;
build | chore | ci | refactor | revert | style) canonical="$type" ;;
*)
for prefix in ${branch_extra_prefixes[@]+"${branch_extra_prefixes[@]}"}; do
if [[ "$type" == "$prefix" ]]; then
canonical="$prefix"
break
fi
done
;;
esac
if [[ -n "$canonical" ]]; then
branch_ref_segment "${name#*/}"
if [[ -n "$BRANCH_SEGMENT" ]]; then
branch="$canonical/$BRANCH_SEGMENT"
return 0
fi
printf '%s: name %q has type %s but no description; using %s/ (pass %s/<description> to keep the type)\n' \
"$PROG" "$name" "$canonical" "$branch_default_type" "$canonical" >&2
fi
fi
branch_ref_segment "$name"
if [[ -z "$BRANCH_SEGMENT" ]]; then
printf '%s: name %q sanitizes to an empty description; keeping the branch name verbatim\n' "$PROG" "$name" >&2
branch="$name"
return 0
fi
branch="$branch_default_type/$BRANCH_SEGMENT"
}
branch="$name"
if ((!existing_branch)); then
read_branch_naming
if [[ "$branch_naming" == conventional-commits ]]; then
derive_conventional_branch "$name"
printf '%s: branch %s derived from name %s (worktree_branch_naming: conventional-commits)\n' \
"$PROG" "$branch" "$name" >&2
fi
fi
# Second half of name validation: the character class checked above is NOT a
# subset of git's ref grammar, so it alone cannot uphold the exit-2-for-an-
# invalid-name contract. `feat/foo..bar` (`..`), `.foo` and `feat/.` (component
# starting/ending with `.`), `foo.lock` (reserved suffix), `HEAD`, and `-lead`
# all sit inside the class yet are illegal refs, and would otherwise fail inside
# `git worktree add` as environment exit 4 — which a caller cannot tell from a
# genuinely broken environment. Ask git rather than reimplementing its rules.
#
# Runs HERE, not beside the character check, and scoped with `-C "$toplevel"`:
# `--branch` takes a branchname-shorthand and so performs repository discovery,
# which fails outright when the process's CWD is a stale checkout (a `.git` file
# naming a gitdir that no longer exists — precisely what this plugin's own
# worktree cleanup deals with). Inheriting that CWD would turn a perfectly valid
# name into a false exit 2, and the documented invocation omits `--repo-dir`, so
# the CWD is the default. Deferring past the exit-4 repository probe guarantees a
# healthy repo to run in and makes a non-zero exit mean the NAME, nothing else.
# Both streams are discarded: on success `--branch` echoes the name to stdout,
# which would corrupt the sole-stdout-line output contract, and on failure git's
# message is superseded by ours. An option-shaped name is read as a ref because
# git parses no further options after `--branch`. A derived branch is checked
# instead of the name, since it is the one git will create.
if ! git -C "$toplevel" check-ref-format --branch "$branch" >/dev/null 2>&1; then
if [[ "$branch" == "$name" ]]; then
printf '%s: --name %q is not a valid git branch name (see: git help check-ref-format)\n' "$PROG" "$name" >&2
else
printf '%s: branch %q derived from --name %q is not a valid git branch name (see: git help check-ref-format)\n' \
"$PROG" "$branch" "$name" >&2
fi
exit 2
fi
# parse_owner_repo <url> — derive an `owner<TAB>repo` pair from a remote URL for
# the directory name. Sets globals `owner` and `repo`. Handles the shapes we see:
# git@host:owner/repo.git · https://host/owner/repo.git · ssh://git@host/owner/repo
# GitLab subgroups (group/subgroup/repo → owner=subgroup)
# Azure DevOps (…/org/project/_git/repo and v3/org/project/repo → owner=project)
# It never fails: with fewer than two usable path segments, owner is left empty
# and the caller falls back to the repo-dir name.
parse_owner_repo() {
local url="$1" path
owner=""
repo=""
# Reduce to the path portion. Scheme URLs (scheme://host/path) and scp syntax
# (git@host:path) delimit the host differently, so branch on which is present.
path="$url"
if [[ "$path" == *"://"* ]]; then
path="${path#*://}" # strip scheme://
path="${path#*/}" # strip host[:port] up to the first '/'
elif [[ "$path" == *:* ]]; then
path="${path#*:}" # scp-like git@host:owner/repo -> owner/repo
fi
path="${path%.git}"
path="${path%/}"
# Split into non-empty segments, dropping Azure's `_git` marker and a leading
# `v3` (Azure SSH) so the meaningful org/project/repo tail remains.
local -a seg=() parts
IFS='/' read -r -a parts <<<"$path"
local p
for p in "${parts[@]}"; do
[[ -z "$p" || "$p" == "_git" || "$p" == "v3" ]] && continue
seg+=("$p")
done
local n=${#seg[@]}
if ((n >= 2)); then
repo="${seg[n - 1]}"
owner="${seg[n - 2]}"
elif ((n == 1)); then
repo="${seg[0]}"
fi
}
# owner/repo from the origin remote when present; otherwise fall back to the
# repository directory name (owner omitted).
owner=""
repo=""
if origin_url=$(git -C "$toplevel" remote get-url origin 2>/dev/null); then
parse_owner_repo "$origin_url"
fi
[[ -n "$repo" ]] || repo="${toplevel##*/}"
# Sanitize the name into a filesystem-safe slug: '/' and any character outside
# [A-Za-z0-9._-] become '-', runs of '-' collapse, leading/trailing '-' trim.
slug="$name"
slug="${slug//[^A-Za-z0-9._-]/-}"
while [[ "$slug" == *--* ]]; do slug="${slug//--/-}"; done
slug="${slug#-}"
slug="${slug%-}"
if [[ -z "$slug" ]]; then
printf '%s: --name %q sanitizes to an empty slug\n' "$PROG" "$name" >&2
exit 2
fi
if [[ -n "$owner" ]]; then
dirname="${owner}-${repo}-${slug}"
else
dirname="${repo}-${slug}"
fi
worktree_path="${root%/}/${dirname}"
# `git -C "$toplevel" worktree add` resolves a relative target against the repo
# top level, so a relative root (e.g. `worktrees`) always lands inside the repo.
# Anchor it to $toplevel up front so the containment check below sees the real
# target rather than an unrooted string whose ancestor walk never reaches the repo.
# A drive-letter path counts as absolute only when the colon is followed by a
# separator (`C:/foo`); `C:foo` is drive-relative and is refused above (#962).
[[ "$worktree_path" != /* && ! "$worktree_path" =~ ^[A-Za-z]:/ ]] && worktree_path="$toplevel/$worktree_path"
# Collapse `.`/`..` before the containment walk. A root with `..` after a
# nonexistent component (e.g. `<root>/missing/../<repo>/.claude/worktrees`) would
# otherwise defeat the walk: it stops at the nonexistent `missing` string and
# never probes the real `<repo>` ancestor, so the guard passes and `git worktree
# add` creates `missing`, resolves `..`, and lands the checkout inside the repo.
# Normalizing first makes the walk see the true landing path.
worktree_path=$(worktree_path_normalize "$worktree_path")
# Reject placement inside any git repository — a working tree, a normal repo's
# .git directory, or a bare clone. Keeping worktrees OUT of every repository is
# the helper's core purpose — see skills/worktree/reference/nesting-invariant.md § "The nesting
# invariant, dated measurement" for the measured claim, and note that a worktree dropped
# inside a .git or bare directory additionally mixes the checkout into git
# metadata, which is a separate and undisputed reason to refuse. The root
# resolution above does not catch a root explicitly pointed inside a repository
# (e.g. the old .claude/worktrees/ path, a root under a sibling clone, or a path
# beneath a .git directory), so ask git about the target's location: walk up
# from the target's parent to the nearest existing ancestor. Probing the parent,
# never the target itself, keeps an already-created worktree at $worktree_path
# from matching its own top level — that case is the "already exists" error
# below. `--show-toplevel` catches work-tree ancestors (and by top-level
# equality tells the source repo from a foreign clone);
# `--is-inside-git-dir` catches .git and bare-repo ancestors, which have no work
# tree and so report no top level. Both come from `rev-parse`, so the check is
# immune to path-format differences (drive-letter spelling, symlinks) that defeat
# a raw string prefix test.
probe="${worktree_path%/*}"
while [[ ! -e "$probe" ]]; do
parent="${probe%/*}"
[[ "$parent" == "$probe" ]] && break
probe="$parent"
done
if [[ -e "$probe" ]]; then
location=""
detail=""
if target_top=$(git -C "$probe" rev-parse --show-toplevel 2>/dev/null) && [[ -n "$target_top" ]]; then
if [[ "$target_top" == "$toplevel" ]]; then
location="inside the repository"
else
location="inside another git working tree"
fi
detail=" checkout: $target_top"
elif [[ "$(git -C "$probe" rev-parse --is-inside-git-dir 2>/dev/null)" == "true" ]]; then
location="inside a git directory"
detail=" git dir: $(git -C "$probe" rev-parse --absolute-git-dir 2>/dev/null)"
fi
if [[ -n "$location" ]]; then
cat >&2 <<EOF
$PROG: worktree target is $location — refusing to create a worktree.
target: $worktree_path
$detail
Point the \`worktreeroot.path\` git config key (or the plugin's
\`worktree_root\` option) at an external root — a path OUTSIDE every repository,
on the same drive as the repo on Windows — then retry.
Not creating inside a checkout or a git directory: from there a worktree can
pick up the enclosing checkout's path-scoped rules as well as its own, and a
git-directory placement mixes the worktree into git metadata. Measurement and