diff --git a/docs/agent-usage.md b/docs/agent-usage.md index 19b1b3f..6047c2b 100644 --- a/docs/agent-usage.md +++ b/docs/agent-usage.md @@ -64,6 +64,12 @@ applies without it: `.gtrconfig` hooks the user has not approved never run. report its branch, changes, and validation results. 5. Remove the worktree only when the user explicitly asks for cleanup. +List output uses `(detached)` as a display label for detached HEAD; it can also +be a real branch name. Use `git gtr list --ids` and pass the first field's escaped +`path:` identity to target an exact checkout, including detached or duplicate +branch worktrees. Removing a detached checkout never deletes a branch; `mv` +requires an attached branch. + Agents should not run `git gtr trust`. Trusting committed `.gtrconfig` commands authorizes code execution and requires human review. Agents should also avoid `git gtr rm --force`, `--delete-branch`, and `git gtr clean` unless the user has diff --git a/docs/configuration.md b/docs/configuration.md index 06a00e8..975a2f8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -472,6 +472,11 @@ git gtr config add gtr.hook.postCd "source ./vars.sh" - `WORKTREE_PATH` - Worktree path - `BRANCH` - Branch name +For `rm` hooks and `ai` postCd hooks, `BRANCH` is empty when the target has +detached HEAD. The `(detached)` label shown by `list` is display text, not a +branch identity. Shell integration's `gtr cd` hooks retain Git's `HEAD` label +for detached HEAD. + **Examples for different build tools:** ```bash diff --git a/lib/commands/ai.sh b/lib/commands/ai.sh index 0f7caa9..4d46621 100644 --- a/lib/commands/ai.sh +++ b/lib/commands/ai.sh @@ -35,9 +35,9 @@ cmd_ai() { worktree_path="$_ctx_worktree_path" branch="$_ctx_branch" - log_step "Starting $ai_tool for: $branch" + log_step "Starting $ai_tool for: ${branch:-(detached)}" log_info "Directory: $worktree_path" - log_info "Branch: $branch" + log_info "Branch: ${branch:-(detached)}" # Run postCd hooks + AI in a subshell so hook env vars propagate to AI ( @@ -48,4 +48,4 @@ cmd_ai() { BRANCH="$branch" ai_start "$worktree_path" "${ai_args[@]}" ) -} \ No newline at end of file +} diff --git a/lib/commands/clean.sh b/lib/commands/clean.sh index d11ecfd..08fc2b8 100644 --- a/lib/commands/clean.sh +++ b/lib/commands/clean.sh @@ -46,7 +46,7 @@ _clean_should_skip() { return 0 fi - if [ -z "$branch" ] || [ "$branch" = "(detached)" ]; then + if [ -z "$branch" ]; then log_warn "Skipping $dir (detached HEAD)" return 0 fi @@ -228,7 +228,10 @@ _clean_prs() { local removed=0 skipped=0 local main_branch - main_branch=$(current_branch "$repo_root") + # Older Git cannot resolve an unborn HEAD. This optional skip hint must not + # prevent cleanup of linked worktrees, or retain output from a failed lookup. + main_branch=$(get_current_branch "$repo_root") || main_branch="" + [ "$main_branch" = "HEAD" ] && main_branch="" local records records=$(list_worktree_records "$repo_root") @@ -238,7 +241,7 @@ _clean_prs() { "") if [ -n "$dir" ] && [ "$is_main" != "1" ]; then # Skip main repo branch silently (not counted) - [ "$branch" = "$main_branch" ] && continue + [ -n "$main_branch" ] && [ "$branch" = "$main_branch" ] && continue if _clean_should_skip "$dir" "$branch" "$force" "$active_worktree_path"; then skipped=$((skipped + 1)) diff --git a/lib/commands/copy.sh b/lib/commands/copy.sh index 687a0f6..bee1fe7 100644 --- a/lib/commands/copy.sh +++ b/lib/commands/copy.sh @@ -97,7 +97,7 @@ cmd_copy() { local dst_path dst_branch resolve_worktree "$target_id" "$repo_root" "$base_dir" "$prefix" || continue - dst_path="$_ctx_worktree_path" dst_branch="$_ctx_branch" + dst_path="$_ctx_worktree_path" dst_branch="${_ctx_branch:-(detached)}" # Count resolved non-main targets before excluding the source so a # source-only --all remains a valid no-op. diff --git a/lib/commands/go.sh b/lib/commands/go.sh index 3910598..2a1f4de 100644 --- a/lib/commands/go.sh +++ b/lib/commands/go.sh @@ -15,7 +15,7 @@ cmd_go() { local is_main worktree_path branch resolve_worktree "$identifier" "$repo_root" "$base_dir" "$prefix" || exit 1 - is_main="$_ctx_is_main" worktree_path="$_ctx_worktree_path" branch="$_ctx_branch" + is_main="$_ctx_is_main" worktree_path="$_ctx_worktree_path" branch="${_ctx_branch:-(detached)}" # Human messages to stderr so stdout can be used in command substitution if [ "$is_main" = "1" ]; then @@ -27,4 +27,4 @@ cmd_go() { # Print path to stdout for shell integration: cd "$(gtr go my-feature)" printf "%s\n" "$worktree_path" -} \ No newline at end of file +} diff --git a/lib/commands/list.sh b/lib/commands/list.sh index 886c4fd..5cc6705 100644 --- a/lib/commands/list.sh +++ b/lib/commands/list.sh @@ -47,6 +47,8 @@ cmd_list() { ;; "branch "*) branch=$(_tsv_unescape_field "${line#branch }") + # Preserve the public list format; this label is never an identity. + branch="${branch:-(detached)}" ;; "status "*) status="${line#status }" @@ -113,6 +115,7 @@ EOF ;; "branch "*) branch=$(_tsv_unescape_field "${line#branch }") + branch="${branch:-(detached)}" ;; "status "*) status="${line#status }" diff --git a/lib/commands/remove.sh b/lib/commands/remove.sh index 776086e..f5b2bc6 100644 --- a/lib/commands/remove.sh +++ b/lib/commands/remove.sh @@ -45,7 +45,7 @@ cmd_remove() { WORKTREE_PATH="$worktree_path" \ BRANCH="$branch_name"; then if [ "$force" -eq 0 ]; then - log_error "Pre-remove hook failed for $branch_name. Use --force to skip hooks." + log_error "Pre-remove hook failed for ${branch_name:-(detached)}. Use --force to skip hooks." had_failure=1 continue else @@ -59,7 +59,7 @@ cmd_remove() { continue fi - # Handle branch deletion + # Detached targets have no branch identity; never delete a display label. if [ -n "$branch_name" ]; then if [ "$delete_branch" -eq 1 ]; then if [ "$yes_mode" -eq 1 ] || prompt_yes_no "Also delete branch '$branch_name'?"; then @@ -77,7 +77,7 @@ cmd_remove() { REPO_ROOT="$repo_root" \ WORKTREE_PATH="$worktree_path" \ BRANCH="$branch_name"; then - log_warn "Post-remove hook failed for $branch_name" + log_warn "Post-remove hook failed for ${branch_name:-(detached)}" fi done diff --git a/lib/commands/rename.sh b/lib/commands/rename.sh index 1f6e4dd..c621d70 100644 --- a/lib/commands/rename.sh +++ b/lib/commands/rename.sh @@ -31,6 +31,11 @@ cmd_rename() { exit 1 fi + if [ "$_ctx_detached" -eq 1 ]; then + log_error "Cannot rename a detached worktree; check out a branch first" + exit 1 + fi + # Sanitize new name and construct new path local new_sanitized new_path new_sanitized=$(sanitize_branch_name "$new_name") diff --git a/lib/commands/run.sh b/lib/commands/run.sh index ed45146..988c3b7 100644 --- a/lib/commands/run.sh +++ b/lib/commands/run.sh @@ -61,7 +61,7 @@ cmd_run() { local is_main worktree_path branch resolve_worktree "$identifier" "$repo_root" "$base_dir" "$prefix" || exit 1 - is_main="$_ctx_is_main" worktree_path="$_ctx_worktree_path" branch="$_ctx_branch" + is_main="$_ctx_is_main" worktree_path="$_ctx_worktree_path" branch="${_ctx_branch:-(detached)}" # Human messages to stderr (like cmd_go) if [ "$is_main" = "1" ]; then @@ -74,4 +74,4 @@ cmd_run() { # Execute command in worktree directory (exit code propagates) (cd "$worktree_path" && "${run_args[@]}") -} \ No newline at end of file +} diff --git a/lib/core.sh b/lib/core.sh index 7287cb9..e53e95b 100644 --- a/lib/core.sh +++ b/lib/core.sh @@ -6,9 +6,9 @@ # Callers should copy into locals immediately after calling the resolver. # # resolve_repo_context() -> _ctx_repo_root _ctx_base_dir _ctx_prefix -# resolve_worktree() -> _ctx_is_main _ctx_worktree_path _ctx_branch +# resolve_worktree() -> _ctx_is_main _ctx_worktree_path _ctx_branch _ctx_detached declare _ctx_repo_root _ctx_base_dir _ctx_prefix -declare _ctx_is_main _ctx_worktree_path _ctx_branch +declare _ctx_is_main _ctx_worktree_path _ctx_branch _ctx_detached # Discover the root of the main git repository # Works correctly from both the main repo and from inside worktrees. @@ -191,7 +191,7 @@ get_current_branch() { fi } -# Get the current branch of a worktree (with detached HEAD normalization) +# Get the current branch label for display only (never use as branch identity). # Usage: current_branch worktree_path current_branch() { local worktree_path="$1" @@ -240,7 +240,8 @@ _emit_worktree_record() { if [ "$wt_path" = "$repo_root" ] || [ "$wt_path_canonical" = "$repo_root" ]; then is_main=1 fi - [ -z "$branch" ] && branch="(detached)" + # An empty branch means no attached branch, even when status is locked or + # prunable. Display labels such as '(detached)' are valid Git branch names. status=$(_worktree_record_status "$wt_detached" "$wt_locked" "$wt_prunable") printf "is_main %s\n" "$is_main" @@ -298,7 +299,8 @@ _parse_worktree_records() { # List registered git worktrees for a repository. # Usage: list_worktree_records repo_root -# Output: blank-line-delimited records with is_main/path/branch/status fields +# Output: blank-line-delimited records with is_main/path/branch/status fields. +# The branch field is empty for detached worktrees; status may also be locked. list_worktree_records() { local repo_root="$1" local repo_root_canonical @@ -480,6 +482,7 @@ EOF # Resolve a registered path identity, branch, literal folder alias, or main ID '1'. # Usage: resolve_target identifier repo_root base_dir prefix # Returns: tab-separated "is_main\tpath\tbranch" with escaped fields on success (is_main: 1 for main repo, 0 for worktrees) +# An empty final field represents detached HEAD, never a display label. # Exit code: 0 on success, 1 if not found resolve_target() { local identifier="$1" @@ -509,6 +512,8 @@ resolve_target() { # Special case: ID 1 is always the repo root if [ "$identifier" = "1" ]; then branch=$(get_current_branch "$repo_root") || return 1 + # Older Git's rev-parse fallback reports HEAD instead of an empty branch. + [ "$branch" = "HEAD" ] && branch="" _print_resolved_target "1" "$repo_root" "$branch" return 0 fi @@ -582,7 +587,7 @@ EOF } # Unpack TSV output from resolve_target into globals. -# Sets: _ctx_is_main, _ctx_worktree_path, _ctx_branch +# Sets: _ctx_is_main, _ctx_worktree_path, _ctx_branch, _ctx_detached (0 or 1) # Usage: unpack_target "$target_string" unpack_target() { local escaped_path escaped_branch @@ -592,11 +597,15 @@ unpack_target() { _ctx_worktree_path=$(_tsv_unescape_field "$escaped_path" && printf '.') || return 1 _ctx_worktree_path="${_ctx_worktree_path%.}" _ctx_branch=$(_tsv_unescape_field "$escaped_branch") + _ctx_detached=0 + if [ -z "$_ctx_branch" ]; then + _ctx_detached=1 + fi } # Resolve an identifier to a worktree and set _ctx_* variables in one step # Usage: resolve_worktree -# Sets: _ctx_is_main, _ctx_worktree_path, _ctx_branch +# Sets: _ctx_is_main, _ctx_worktree_path, _ctx_branch, _ctx_detached resolve_worktree() { local target # Guard the subshell too: a handled miss must not fire Bash 3.2's ERR trap. @@ -1111,7 +1120,7 @@ list_worktree_branches() { while IFS= read -r line; do case "$line" in "") - if [ "$is_main" != "1" ] && [ -n "$branch" ] && [ "$branch" != "(detached)" ]; then + if [ "$is_main" != "1" ] && [ -n "$branch" ]; then printf "%s\n" "$branch" fi is_main="" @@ -1133,7 +1142,7 @@ list_worktree_branches() { $records EOF - if [ "$is_main" != "1" ] && [ -n "$branch" ] && [ "$branch" != "(detached)" ]; then + if [ "$is_main" != "1" ] && [ -n "$branch" ]; then printf "%s\n" "$branch" fi } diff --git a/tests/cmd_clean.bats b/tests/cmd_clean.bats index 24ff163..7a998fe 100644 --- a/tests/cmd_clean.bats +++ b/tests/cmd_clean.bats @@ -46,9 +46,10 @@ teardown() { # ── _clean_should_skip ────────────────────────────────────────────────────── -@test "_clean_should_skip skips detached HEAD" { - run _clean_should_skip "/some/dir" "(detached)" - [ "$status" -eq 0 ] +@test "_clean_should_skip accepts a real branch named detached" { + create_test_worktree '(detached)' + run _clean_should_skip "$TEST_WT_PATH" '(detached)' + [ "$status" -eq 1 ] } @test "_clean_should_skip skips empty branch" { @@ -92,9 +93,10 @@ teardown() { [ "$status" -eq 1 ] # 1 = don't skip } -@test "_clean_should_skip with force=1 still skips detached HEAD" { - run _clean_should_skip "/some/dir" "(detached)" 1 - [ "$status" -eq 0 ] # 0 = skip (protection maintained) +@test "_clean_should_skip with force=1 accepts a real branch named detached" { + create_test_worktree '(detached)' + run _clean_should_skip "$TEST_WT_PATH" '(detached)' 1 + [ "$status" -eq 1 ] } @test "_clean_should_skip with force=1 still skips empty branch" { diff --git a/tests/core_resolve_target.bats b/tests/core_resolve_target.bats index 2e4b610..9f2fa28 100644 --- a/tests/core_resolve_target.bats +++ b/tests/core_resolve_target.bats @@ -114,7 +114,8 @@ teardown() { resolve_worktree "review" "$TEST_REPO" "$TEST_WORKTREES_DIR" "" [ "$_ctx_worktree_path" = "$TEST_WORKTREES_DIR/review" ] - [ "$_ctx_branch" = "(detached)" ] + [ -z "$_ctx_branch" ] + [ "$_ctx_detached" -eq 1 ] } @test "resolve_target rejects stray directories and dot targets" { @@ -376,7 +377,7 @@ teardown() { [[ "$records" == *"is_main 1"$'\n'"path $repo_root"$'\n'*"status ok"* ]] [[ "$records" == *"is_main 0"$'\n'"path $normal_path"$'\n'"branch records-normal"$'\n'"status ok"* ]] - [[ "$records" == *"is_main 0"$'\n'"path $detached_path"$'\n'"branch (detached)"$'\n'"status detached"* ]] + [[ "$records" == *"is_main 0"$'\n'"path $detached_path"$'\n'"branch "$'\n'"status detached"* ]] [[ "$records" == *"is_main 0"$'\n'"path $locked_path"$'\n'"branch records-locked"$'\n'"status locked"* ]] git -C "$TEST_REPO" worktree unlock "$TEST_WORKTREES_DIR/records-locked" @@ -510,6 +511,7 @@ teardown() { } resolve_worktree "path:$(_tsv_escape_field "$path")" "$TEST_REPO" "$TEST_WORKTREES_DIR" "" [ "$_ctx_worktree_path" = "$path" ] - [ "$_ctx_branch" = '(detached)' ] + [ -z "$_ctx_branch" ] + [ "$_ctx_detached" -eq 1 ] [ ! -e should-not-exist ] } diff --git a/tests/integration_detached_identity.bats b/tests/integration_detached_identity.bats new file mode 100644 index 0000000..958c319 --- /dev/null +++ b/tests/integration_detached_identity.bats @@ -0,0 +1,326 @@ +#!/usr/bin/env bats +# Detached HEAD must never impersonate the legal branch name '(detached)'. + +load test_helper + +setup() { + setup_integration_repo + source_gtr_commands + git branch '(detached)' + git worktree add --detach "$TEST_WORKTREES_DIR/loose" HEAD >/dev/null + ORIGINAL_REFS=$(git show-ref --heads) + ORIGINAL_TIP=$(git rev-parse HEAD) +} + +teardown() { + teardown_integration_repo +} + +attach_named_branch() { + git worktree add "$TEST_WORKTREES_DIR/real-branch" '(detached)' >/dev/null +} + +assert_loose_detached() { + [ -f "$TEST_WORKTREES_DIR/loose/.git" ] + [ "$(git -C "$TEST_WORKTREES_DIR/loose" rev-parse HEAD)" = "$ORIGINAL_TIP" ] + ! git -C "$TEST_WORKTREES_DIR/loose" symbolic-ref --quiet HEAD + git worktree list --porcelain | grep -Fx "worktree $TEST_WORKTREES_DIR/loose" +} + +@test "removing detached worktree with branch deletion preserves every real ref" { + git config gtr.hook.preRemove 'printf "pre:<%s>\n" "$BRANCH" >> "$REPO_ROOT/hook-branches"' + git config gtr.hook.postRemove 'printf "post:<%s>\n" "$BRANCH" >> "$REPO_ROOT/hook-branches"' + + run "$PROJECT_ROOT/bin/gtr" rm loose --delete-branch --yes + + [ "$status" -eq 0 ] + [ ! -e "$TEST_WORKTREES_DIR/loose" ] + ! git worktree list --porcelain | grep -Fx "worktree $TEST_WORKTREES_DIR/loose" + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] + [ "$(cat "$TEST_REPO/hook-branches")" = $'pre:<>\npost:<>' ] +} + +@test "both rename aliases reject detached worktrees before changing refs or paths" { + local rename_command + for rename_command in mv rename; do + run "$PROJECT_ROOT/bin/gtr" "$rename_command" loose renamed --force --yes + + [ "$status" -eq 1 ] + [[ "$output" == *"Cannot rename a detached worktree"* ]] + assert_loose_detached + [ ! -e "$TEST_WORKTREES_DIR/renamed" ] + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] + done +} + +@test "real detached-named branch resolves to its attached checkout and can be deleted" { + attach_named_branch + git config gtr.hook.preRemove 'printf "<%s>\n" "$BRANCH" > "$REPO_ROOT/hook-branch"' + + resolve_worktree '(detached)' "$TEST_REPO" "$TEST_WORKTREES_DIR" "" + [ "$_ctx_worktree_path" = "$TEST_WORKTREES_DIR/real-branch" ] + [ "$_ctx_branch" = '(detached)' ] + [ "$_ctx_detached" -eq 0 ] + [ "$(_worktree_path_for_ref '(detached)')" = "$TEST_WORKTREES_DIR/real-branch" ] + + run "$PROJECT_ROOT/bin/gtr" rm '(detached)' --delete-branch --yes + [ "$status" -eq 0 ] + [ ! -e "$TEST_WORKTREES_DIR/real-branch" ] + ! git show-ref --verify --quiet 'refs/heads/(detached)' + assert_loose_detached + [ "$(cat "$TEST_REPO/hook-branch")" = '<(detached)>' ] +} + +@test "real detached-named branch can be renamed without touching detached checkout" { + attach_named_branch + + run "$PROJECT_ROOT/bin/gtr" mv '(detached)' renamed --yes + + [ "$status" -eq 0 ] + [ ! -e "$TEST_WORKTREES_DIR/real-branch" ] + [ -f "$TEST_WORKTREES_DIR/renamed/.git" ] + [ "$(git -C "$TEST_WORKTREES_DIR/renamed" symbolic-ref HEAD)" = refs/heads/renamed ] + [ "$(git rev-parse refs/heads/renamed)" = "$ORIGINAL_TIP" ] + ! git show-ref --verify --quiet 'refs/heads/(detached)' + assert_loose_detached +} + +@test "detached checkout is not a branch-name match for an unchecked-out real branch" { + run resolve_worktree '(detached)' "$TEST_REPO" "$TEST_WORKTREES_DIR" "" + [ "$status" -eq 1 ] + [ -z "$(_worktree_path_for_ref '(detached)')" ] + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] + assert_loose_detached +} + +@test "detached state survives locked status path resolution and old Git parsing" { + attach_named_branch + git worktree lock "$TEST_WORKTREES_DIR/loose" + git() { + case "$*" in *"worktree list --porcelain -z") return 1 ;; esac + command git "$@" + } + # Git 2.17 can lock a worktree but does not expose locked in porcelain. + if command git worktree list --porcelain | grep -Fxq locked; then + [ "$(worktree_status "$TEST_WORKTREES_DIR/loose")" = locked ] + else + [ "$(worktree_status "$TEST_WORKTREES_DIR/loose")" = detached ] + fi + resolve_worktree "path:$TEST_WORKTREES_DIR/loose" "$TEST_REPO" "$TEST_WORKTREES_DIR" "" + [ "$_ctx_worktree_path" = "$TEST_WORKTREES_DIR/loose" ] + [ -z "$_ctx_branch" ] + [ "$_ctx_detached" -eq 1 ] + resolve_worktree '(detached)' "$TEST_REPO" "$TEST_WORKTREES_DIR" "" + [ "$_ctx_branch" = '(detached)' ] + [ "$_ctx_detached" -eq 0 ] + [ "$(list_worktree_branches "$TEST_WORKTREES_DIR" "" "$TEST_REPO")" = '(detached)' ] + command git worktree unlock "$TEST_WORKTREES_DIR/loose" +} + +@test "main ID and path identity agree on detached state including old Git fallback" { + git checkout --quiet --detach HEAD + local identity + for identity in 1 "path:$TEST_REPO"; do + resolve_worktree "$identity" "$TEST_REPO" "$TEST_WORKTREES_DIR" "" + [ "$_ctx_is_main" -eq 1 ] + [ -z "$_ctx_branch" ] + [ "$_ctx_detached" -eq 1 ] + done + git() { + case "$*" in *"branch --show-current") return 1 ;; esac + command git "$@" + } + resolve_worktree 1 "$TEST_REPO" "$TEST_WORKTREES_DIR" "" + [ -z "$_ctx_branch" ] + [ "$_ctx_detached" -eq 1 ] +} + +@test "main checkout on real detached-named branch keeps attached identity" { + git checkout --quiet '(detached)' + local identity + for identity in 1 "path:$TEST_REPO" '(detached)'; do + resolve_worktree "$identity" "$TEST_REPO" "$TEST_WORKTREES_DIR" "" + [ "$_ctx_is_main" -eq 1 ] + [ "$_ctx_worktree_path" = "$TEST_REPO" ] + [ "$_ctx_branch" = '(detached)' ] + [ "$_ctx_detached" -eq 0 ] + done +} + +@test "detached path identity preserves trailing newlines during rename and removal" { + git worktree list --porcelain -z >/dev/null 2>&1 || skip "NUL worktree listing is unavailable" + local path="$TEST_WORKTREES_DIR/loose"$'\n\n' identity + git worktree move "$TEST_WORKTREES_DIR/loose" "$path" + mkdir "$TEST_WORKTREES_DIR/loose" + printf 'keep\n' > "$TEST_WORKTREES_DIR/loose/marker" + identity="path:$(_tsv_escape_field "$path")" + resolve_worktree "$identity" "$TEST_REPO" "$TEST_WORKTREES_DIR" "" + [ "$_ctx_worktree_path" = "$path" ] + [ -z "$_ctx_branch" ] + [ "$_ctx_detached" -eq 1 ] + + run "$PROJECT_ROOT/bin/gtr" mv "$identity" renamed --yes + [ "$status" -eq 1 ] + [ -f "$path/.git" ] + [ ! -e "$TEST_WORKTREES_DIR/renamed" ] + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] + + run "$PROJECT_ROOT/bin/gtr" rm "$identity" --delete-branch --yes + [ "$status" -eq 0 ] + [ ! -e "$path" ] + [ "$(cat "$TEST_WORKTREES_DIR/loose/marker")" = keep ] + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] + [ "$(git worktree list --porcelain | grep -c '^worktree ')" -eq 1 ] +} + +# Stub only the external provider boundary. Cleanup, tip checks, hooks, Git +# removal and branch retention all run through the real CLI in a disposable repo. +setup_cleanup_provider() { + git config gtr.provider github + export DETACHED_TEST_CALLS="$TEST_REPO/provider-calls" + mkdir "$TEST_REPO/mock-bin" + cat > "$TEST_REPO/mock-bin/gh" <<'SH' +#!/usr/bin/env bash +if [ "$1 $2" = 'repo view' ]; then exit 0; fi +printf '%s\n' "$*" >> "$DETACHED_TEST_CALLS" +# gh --jq returns the count of matching PRs, not the raw commit. +printf '1\n' +SH + chmod +x "$TEST_REPO/mock-bin/gh" + export PATH="$TEST_REPO/mock-bin:$PATH" +} + +assert_cleanup_identity() { + local mode="$1" legacy_lookup="${2:-0}" + attach_named_branch + setup_cleanup_provider + + if [ "$legacy_lookup" -eq 1 ]; then + # Exercise the real rev-parse fallback on current Git as well as Git 2.17. + export DETACHED_TEST_REAL_GIT + DETACHED_TEST_REAL_GIT=$(command -v git) + cat > "$TEST_REPO/mock-bin/git" <<'SH' +#!/usr/bin/env bash +if [ "${1:-}" = -C ] && [ "${3:-}" = branch ] && [ "${4:-}" = --show-current ]; then + exit 129 +fi +exec "$DETACHED_TEST_REAL_GIT" "$@" +SH + chmod +x "$TEST_REPO/mock-bin/git" + run get_current_branch "$TEST_REPO" + [ "$status" -ne 0 ] + fi + + run "$PROJECT_ROOT/bin/gtr" clean "$mode" --force --yes --dry-run + [ "$status" -eq 0 ] + [[ "$output" == *"Would remove: (detached)"* ]] + [[ "$output" == *"branch retained"* ]] + [ -f "$TEST_WORKTREES_DIR/real-branch/.git" ] + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] + assert_loose_detached + + run "$PROJECT_ROOT/bin/gtr" clean "$mode" --force --yes + printf '%s\n' "$output" + [ "$status" -eq 0 ] + [ ! -e "$TEST_WORKTREES_DIR/real-branch" ] + ! git worktree list --porcelain | grep -Fx "worktree $TEST_WORKTREES_DIR/real-branch" + [[ "$output" == *"Kept branch (detached)"* ]] + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] + assert_loose_detached + [ "$(wc -l < "$DETACHED_TEST_CALLS" | tr -d ' ')" -eq 2 ] + ! grep -vF -- '--head (detached)' "$DETACHED_TEST_CALLS" + ! grep -vF -- "$ORIGINAL_TIP" "$DETACHED_TEST_CALLS" +} + +@test "merged cleanup handles detached state separately from real branch identity" { + assert_cleanup_identity --merged +} + +@test "closed cleanup handles detached state separately from real branch identity" { + assert_cleanup_identity --closed +} + +@test "cleanup processes real detached-named branch when main is detached too" { + git checkout --quiet --detach HEAD + assert_cleanup_identity --merged +} + +assert_unborn_main_cleanup() { + local mode="$1" legacy_lookup="${2:-0}" + git checkout --quiet --orphan unborn-main + ! git rev-parse --verify HEAD + + assert_cleanup_identity "$mode" "$legacy_lookup" + + # Cleanup must leave the unborn main checkout and its original history alone. + [ -d "$TEST_REPO/.git" ] + [ "$(git symbolic-ref HEAD)" = refs/heads/unborn-main ] + ! git show-ref --verify --quiet refs/heads/unborn-main + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] +} + +@test "merged cleanup processes linked worktrees when main has an unborn branch" { + assert_unborn_main_cleanup --merged +} + +@test "merged cleanup tolerates failed legacy branch lookup on unborn main" { + assert_unborn_main_cleanup --merged 1 +} + +@test "closed cleanup tolerates failed legacy branch lookup on unborn main" { + assert_unborn_main_cleanup --closed 1 +} + +@test "cleanup never queries an unchecked-out branch through a detached worktree" { + setup_cleanup_provider + run "$PROJECT_ROOT/bin/gtr" clean --merged --closed --force --yes + [ "$status" -eq 0 ] + [ ! -e "$DETACHED_TEST_CALLS" ] + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] + assert_loose_detached +} + +@test "list preserves public labels and pickers select exact identities despite identical labels" { + attach_named_branch + local mode detached_row attached_row identity + for mode in --porcelain --ids; do + run "$PROJECT_ROOT/bin/gtr" list "$mode" + [ "$status" -eq 0 ] + detached_row="$TEST_WORKTREES_DIR/loose"$'\t(detached)\tdetached' + attached_row="$TEST_WORKTREES_DIR/real-branch"$'\t(detached)\tok' + [ "$mode" != --ids ] || detached_row="path:$detached_row" + [ "$mode" != --ids ] || attached_row="path:$attached_row" + [[ "$output" == *"$detached_row"* ]] + [[ "$output" == *"$attached_row"* ]] + done + identity="${detached_row%%$'\t'*}" + run "$PROJECT_ROOT/bin/gtr" rm "$identity" --delete-branch --yes + [ "$status" -eq 0 ] + [ ! -e "$TEST_WORKTREES_DIR/loose" ] + [ -f "$TEST_WORKTREES_DIR/real-branch/.git" ] + [ "$(git show-ref --heads)" = "$ORIGINAL_REFS" ] +} + +@test "copy targets real branch independently and --all still copies to detached checkout" { + attach_named_branch + printf 'payload\n' > "$TEST_REPO/payload" + run "$PROJECT_ROOT/bin/gtr" copy '(detached)' -- payload + [ "$status" -eq 0 ] + cmp "$TEST_REPO/payload" "$TEST_WORKTREES_DIR/real-branch/payload" + [ ! -e "$TEST_WORKTREES_DIR/loose/payload" ] + run "$PROJECT_ROOT/bin/gtr" copy --all -- payload + [ "$status" -eq 0 ] + cmp "$TEST_REPO/payload" "$TEST_WORKTREES_DIR/loose/payload" + cmp "$TEST_REPO/payload" "$TEST_WORKTREES_DIR/real-branch/payload" +} + +@test "AI hooks receive empty branch for detached targets and literal real branch identity" { + attach_named_branch + git config gtr.hook.postCd 'printf "<%s>\n" "$BRANCH" > "$WORKTREE_PATH/hook-branch"' + run "$PROJECT_ROOT/bin/gtr" ai loose --ai true + [ "$status" -eq 0 ] + [ "$(cat "$TEST_WORKTREES_DIR/loose/hook-branch")" = '<>' ] + run "$PROJECT_ROOT/bin/gtr" ai '(detached)' --ai true + [ "$status" -eq 0 ] + [ "$(cat "$TEST_WORKTREES_DIR/real-branch/hook-branch")" = '<(detached)>' ] +}