Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

nushell/modules/git.nu

Raw
# Native worktree lifecycle; Git's registry and canonical paths are authoritative.
use wt-config.nu
use wt-forge.nu

# Capture every external Git result: progress must never contaminate records.
def git-result [cwd: path, args: list<string>] {
    ^git --no-optional-locks -C $cwd ...$args | complete
}

def git-output [cwd: path, args: list<string>] {
    let result = (git-result $cwd $args)
    if $result.exit_code != 0 {
        error make {msg: $"git ($args | str join ' '): ($result.stderr | str trim)"}
    }
    $result.stdout
}

def git-text [cwd: path, args: list<string>] {
    git-output $cwd $args | str trim
}

def path-key [value: string] {
    let normalized = ($value | str replace --all '\' '/' | str trim --right --char '/')
    if $nu.os-info.name == 'windows' { $normalized | str lowercase } else { $normalized }
}

def same-path [left: string, right: string] { (path-key $left) == (path-key $right) }

def within [child: string, parent: string] {
    (path-key $child) | str starts-with $"(path-key $parent)/"
}

def canonical [value: path] { $value | path expand --strict }

# -z keeps literal newlines, quotes, and backslashes in registered paths intact.
def registry [cwd: path] {
    let raw = (git-output $cwd ['worktree' 'list' '--porcelain' '-z'])
    $raw | split row $"(char nul)(char nul)" | where {|group| not ($group | is-empty)} | each {|group|
        $group | split row (char nul) | reduce --fold {
            path: '', branch: null, head: null, bare: false, detached: false, locked: false, prunable: false
        } {|field, row|
            if ($field | str starts-with 'worktree ') { $row | upsert path ($field | str substring 9..) } else if ($field | str starts-with 'branch refs/heads/') {
                $row | upsert branch ($field | str substring 18..)
            } else if ($field | str starts-with 'HEAD ') { $row | upsert head ($field | str substring 5..) } else if $field == 'bare' {
                $row | upsert bare true
            } else if $field == 'detached' { $row | upsert detached true } else if ($field == 'locked') or ($field | str starts-with 'locked ') {
                $row | upsert locked true
            } else if ($field == 'prunable') or ($field | str starts-with 'prunable ') { $row | upsert prunable true } else { $row }
        }
    }
}

def repository [] {
    let common = (canonical (git-text $env.PWD ['rev-parse' '--path-format=absolute' '--git-common-dir']))
    let rows = (registry $env.PWD)
    let bare = ($rows | any {|row| $row.bare})
    let worktrees = ($rows | where {|row| not $row.bare} | each {|row|
        $row | update path (if ($row.path | path exists) { canonical $row.path } else { $row.path | path expand })
    })
    let bare_head = if $bare { git-result $common ['symbolic-ref' '--quiet' '--short' 'HEAD'] } else { null }
    let configured = if $bare { git-result $common ['config' '--get' 'wt.main-branch'] } else { null }
    let primary_branch = if $bare and $configured.exit_code == 0 and not ($configured.stdout | str trim | is-empty) {
        $configured.stdout | str trim | str replace --regex '^refs/heads/' ''
    } else if $bare and $bare_head.exit_code == 0 { $bare_head.stdout | str trim } else { $worktrees | get -o 0.branch }
    let primary = if $bare { $worktrees | where branch == $primary_branch | get -o 0 } else { $worktrees | get -o 0 }
    let root = if $bare { $common | path dirname } else { $primary.path }
    let current_result = (git-result $env.PWD ['rev-parse' '--show-toplevel'])
    let current = if $current_result.exit_code == 0 { canonical ($current_result.stdout | str trim) } else { null }
    {root: $root, common_dir: $common, path: $env.PWD, bare: $bare, current: $current, worktrees: $worktrees, primary: $primary, primary_branch: $primary_branch}
}

def context [repo: record, row: record, target?: record] {
    {root: $repo.root, common_dir: $repo.common_dir, path: $row.path, branch: ($row.branch | default 'HEAD'), target: ($target | get -o branch), target_path: ($target | get -o path)}
}

def branch-ref [branch: string] { $"refs/heads/($branch)" }

def tip [cwd: path, ref: string] {
    git-text $cwd ['rev-parse' '--verify' $"($ref)^{commit}"]
}

def default-branch [repo: record] {
    let configured = (git-result $repo.path ['config' '--get' 'wt.main-branch'])
    if $configured.exit_code == 0 and not ($configured.stdout | str trim | is-empty) {
        let branch = ($configured.stdout | str trim | str replace --regex '^refs/heads/' '')
        tip $repo.path (branch-ref $branch) | ignore
        return $branch
    }
    let heads = (git-text $repo.path ['for-each-ref' '--format=%(refname)%09%(symref)' 'refs/remotes/'] | lines)
    let defaults = ($heads | parse --regex '^refs/remotes/(?P<remote>.+)/HEAD\t(?P<target>refs/remotes/.+)$' | each {|row|
        let prefix = $"refs/remotes/($row.remote)/"
        let offset = ($prefix | str length)
        if ($row.target | str starts-with $prefix) {
            {remote: $row.remote, branch: ($row.target | str substring $offset..)}
        }
    } | compact | sort-by remote)
    let preferred = ($defaults | where remote == 'origin' | append ($defaults | where remote != 'origin'))
    for candidate in $preferred {
        if (git-result $repo.path ['show-ref' '--verify' '--quiet' (branch-ref $candidate.branch)]).exit_code == 0 { return $candidate.branch }
    }
    if $repo.primary_branch != null {
        tip $repo.path (branch-ref $repo.primary_branch) | ignore
        return $repo.primary_branch
    }
    error make {msg: 'cannot detect default branch; configure wt.main-branch'}
}

def current-row [repo: record] {
    let found = ($repo.worktrees | where {|row| $repo.current != null and (same-path $row.path $repo.current)})
    if ($found | length) != 1 { error make {msg: 'current directory is not a registered worktree'} }
    $found | first
}

def select-row [repo: record, selector: string] {
    let expanded = ($selector | path expand)
    let matches = ($repo.worktrees | where {|row| $row.branch == $selector or (same-path $row.path $expanded)})
    if ($matches | length) != 1 { error make {msg: $"worktree selector is unknown or ambiguous: ($selector)"} }
    $matches | first
}

# Verify both sides of Git's registration; never remove a guessed filesystem path.
def safe-row [repo: record, row: record] {
    if $row.locked { error make {msg: $"locked worktree: ($row.path)"} }
    if $row.prunable or not ($row.path | path exists) { error make {msg: $"unsafe missing/prunable worktree: ($row.path)"} }
    let actual = (canonical $row.path)
    let ordinary_primary = (not $repo.bare and $repo.primary != null and (same-path $actual $repo.primary.path))
    if (same-path $actual $repo.common_dir) or (within $actual $repo.common_dir) or ((within $repo.common_dir $actual) and not $ordinary_primary) {
        error make {msg: $"unsafe path contains Git common directory: ($actual)"}
    }
    let common = (canonical (git-text $actual ['rev-parse' '--path-format=absolute' '--git-common-dir']))
    let top = (canonical (git-text $actual ['rev-parse' '--show-toplevel']))
    if not (same-path $common $repo.common_dir) or not (same-path $top $actual) {
        error make {msg: $"unsafe worktree identity: ($actual)"}
    }
    for other in $repo.worktrees {
        if (within $other.path $actual) or (within $actual $other.path) {
            error make {msg: $"nested registered worktrees: ($actual), ($other.path)"}
        }
    }
    if $row.branch == null { error make {msg: $"detached worktree: ($actual)"} }
    let branch = (git-text $actual ['symbolic-ref' '--quiet' '--short' 'HEAD'])
    if $branch != $row.branch { error make {msg: $"worktree branch changed: ($actual)"} }
    let git_dir = (canonical (git-text $actual ['rev-parse' '--absolute-git-dir']))
    for marker in ['MERGE_HEAD' 'CHERRY_PICK_HEAD' 'REVERT_HEAD' 'REBASE_HEAD' 'rebase-merge' 'rebase-apply' 'sequencer' 'BISECT_LOG' 'index.lock'] {
        if ([$git_dir $marker] | path join | path exists) { error make {msg: $"in-progress Git operation: ($marker) in ($actual)"} }
    }
}

def dirty [row: record] {
    not (git-output $row.path ['-c' 'core.fsmonitor=false' '-c' 'core.untrackedCache=false' 'status' '--porcelain=v1' '-z' '--untracked-files=all' '--ignore-submodules=none'] | is-empty)
}

def clean-row [repo: record, row: record] {
    safe-row $repo $row
    if (dirty $row) { error make {msg: $"dirty worktree; commit or resolve changes explicitly: ($row.path)"} }
}

def removable [repo: record, row: record] {
    if $repo.primary != null and (same-path $repo.primary.path $row.path) {
        error make {msg: $"primary worktree cannot be removed: ($row.path)"}
    }
    if $nu.os-info.name == 'windows' {
        # Nu's logical cd does not release Windows' startup-directory handle.
        let held = (debug info | get process.cwd | path expand)
        if (same-path $held $row.path) or (within $held $row.path) {
            error make {msg: $"Windows holds Nu's startup cwd inside ($row.path); worktree retained. Start Nu outside this worktree, then switch back; or merge with --keep."}
        }
    }
    let marker = ([$row.path '.git'] | path join)
    if ($marker | path type) != 'file' { error make {msg: $"unsafe linked worktree metadata: ($row.path)"} }
}

def integrated [repo: record, branch: string, target: string] {
    let result = (git-result $repo.path ['merge-base' '--is-ancestor' (branch-ref $branch) (branch-ref $target)])
    if $result.exit_code != 0 { error make {msg: $"branch ($branch) is not proven integrated into ($target); use --keep-branch"} }
}

# Delete only the proven tip, independent of upstream config or caller HEAD.
def delete-integrated-branch [cwd: path, branch: string, target: string] {
    let ref = (branch-ref $branch)
    let expected = (tip $cwd $ref)
    if (git-result $cwd ['merge-base' '--is-ancestor' $expected (branch-ref $target)]).exit_code != 0 {
        error make {msg: $"branch changed or is not integrated into ($target); branch retained: ($branch)"}
    }
    if (registry $cwd | any {|row| $row.branch == $branch}) { error make {msg: $"branch is still checked out: ($branch)"} }
    let pattern = (['^branch\.' ($branch | str escape-regex) '\.'] | str join)
    let config = (git-result $cwd ['config' '--local' '--name-only' '--get-regexp' $pattern])
    if $config.exit_code not-in [0 1] { error make {msg: 'cannot inspect branch configuration; branch retained'} }
    git-output $cwd ['update-ref' '-d' $ref $expected] | ignore
    if $config.exit_code == 0 {
        try { git-output $cwd ['config' '--local' '--remove-section' $"branch.($branch)"] | ignore } catch {|err|
            error make {msg: $"branch deleted; branch configuration cleanup failed: ($err.msg)"}
        }
    }
}

# Refuse invalid mapping rather than sanitizing multiple names onto one path.
def destination [repo: record, branch: string] {
    let parts = ($branch | split row '/')
    for segment in $parts {
        if $segment in ['' '.' '..'] { error make {msg: $"path traversal refused: ($branch)"} }
        if ($segment | str contains '\') { error make {msg: $"path traversal/backslash refused: ($branch)"} }
        if $segment =~ '(?i)^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(\.|$)' {
            error make {msg: $"reserved Windows path name: ($segment)"}
        }
        if $segment =~ '[<>:"|?*\x00-\x1f]' or ($segment | str ends-with '.') or ($segment | str ends-with ' ') {
            error make {msg: $"unsafe path segment: ($segment)"}
        }
    }
    git-output $repo.path ['check-ref-format' '--branch' $branch] | ignore
    let base = if $repo.bare { $repo.common_dir | path dirname } else {
        let primary = $repo.primary.path
        [$primary '..' $"($primary | path basename).worktrees"] | path join | path expand
    }
    mut cursor = $base
    # Check every existing component case-insensitively, even on case-sensitive OSes.
    for part in $parts {
        if ($cursor | path exists) {
            if ($cursor | path type) != 'dir' { error make {msg: $"occupied worktree parent: ($cursor)"} }
            let siblings = (ls --all $cursor | get name | each {|name| $name | path basename})
            let collision = ($siblings | where {|name| ($name | str lowercase) == ($part | str lowercase) and $name != $part})
            if not ($collision | is-empty) { error make {msg: $"case collision at ($cursor): ($part)"} }
        }
        $cursor = ([$cursor $part] | path join)
        if ($cursor | path type) == 'symlink' { error make {msg: $"unsafe symlink destination: ($cursor)"} }
    }
    if ($cursor | path exists) { error make {msg: $"occupied destination: ($cursor)"} }
    let path = ($cursor | path expand)
    for row in $repo.worktrees {
        if (same-path $path $row.path) or (within $path $row.path) or (within $row.path $path) {
            error make {msg: $"occupied/nested registered destination: ($path)"}
        }
    }
    $path
}

def branches [repo: record] {
    let remotes = (git-output $repo.path ['remote'] | lines | sort --reverse)
    git-output $repo.path ['for-each-ref' '--format=%(refname)%09%(symref)' 'refs/heads/' 'refs/remotes/']
    | lines | parse --regex '^(?P<ref>[^\t]+)\t(?P<symbolic>.*)$'
    | where symbolic == '' | each {|row|
        if ($row.ref | str starts-with 'refs/heads/') {
            let name = ($row.ref | str substring 11..)
            {branch: $name, name: $name, ref: $row.ref, remote: false}
        } else {
            let qualified = ($row.ref | str substring 13..)
            let remote = ($remotes | where {|name| $qualified | str starts-with $"($name)/"} | get -o 0)
            let prefix = if $remote == null { null } else { ($remote | str length) + 1 }
            {branch: $qualified, name: (if $prefix == null { null } else { $qualified | str substring $prefix.. }), ref: $row.ref, remote: true}
        }
    }
}

# Completion values are literal Nu source, not display strings.
# Leave spans unset so Nu supplies the full-buffer replacement range.
def suggestion [value: string, description: string] {
    {value: ($value | to nuon), display_override: $value, description: $description}
}

def worktree-suggestions [rows: list] {
    $rows | each {|row|
        let values = [ (suggestion $row.path $"worktree: ($row.branch | default 'detached')") ]
        if $row.branch == null { $values } else { $values | append (suggestion $row.branch 'existing worktree') }
    } | flatten
}

def complete-base [] {
    try {
        branches (repository) | each {|row| suggestion $row.branch (if $row.remote { 'remote branch' } else { 'local branch' }) }
    } catch { [] }
}

def complete-selector [] {
    try {
        let repo = (repository)
        branches $repo | each {|row| suggestion $row.branch (if $row.remote { 'remote branch' } else { 'local branch' }) }
        | append (worktree-suggestions $repo.worktrees) | uniq-by value
    } catch { [] }
}

def complete-worktree [] {
    try { worktree-suggestions (repository | get worktrees) | uniq-by value } catch { [] }
}

def complete-target [] {
    try {
        let repo = (repository)
        let rows = ($repo.worktrees | where {|row| $row.branch != null and ($repo.current == null or not (same-path $row.path $repo.current))})
        worktree-suggestions $rows | uniq-by value
    } catch { [] }
}

def complete-remote [] {
    try { git-output $env.PWD ['remote'] | lines } catch { [] }
}

def complete-event [] { ['post-create' 'pre-merge' 'pre-remove'] }

# Helper execution inherits cwd; always scope it to the operation root.
def run-hooks [event: string, ctx: record, approve: bool, skip: bool] {
    do {
        cd $ctx.path
        try { wt-config execute $event $ctx --approve=$approve --skip=$skip } catch {|err|
            error make {msg: $"hook execution/approval failed: ($err.msg)"}
        }
    }
}

# Known-external root lets Nu expand aliases before resolving native subcommands.
@complete external
export extern main [...args]

# Inspect and manage this repository's registered Git worktrees.
export def wt [] { wt list }

# List worktrees as native records, including current/primary/locked state.
export def 'wt list' [--fast # Skip per-worktree dirty checks.
] {
    let repo = (repository)
    $repo.worktrees | each {|row|
        let value = ($row | reject bare | insert current ($repo.current != null and (same-path $row.path $repo.current)) | insert primary ($repo.primary != null and (same-path $row.path $repo.primary.path)))
        if $fast { $value } else { $value | insert dirty (if ($row.path | path exists) { dirty $row } else { null }) }
    }
}

# Switch worktrees, create from a branch/ref, or pick interactively.
# PR selectors require an explicit remote; --execute launches literal argv.
export def --env --wrapped 'wt switch' [
    selector?: string@complete-selector # Branch, registered path, or pr:<number>.
    ...command: string # Arguments when --execute names a single executable.
    --create: string # Name of a new branch; never resets an existing branch.
    --base: string@complete-base = 'HEAD' # Starting ref for a newly created branch.
    --remote: string@complete-remote # Remote for an explicit PR checkout.
    --no-submodules # Skip submodule initialization in new worktrees.
    --no-hooks # Skip all hook configuration, approvals, and execution.
    --approve-hooks # Approve the current project-hook command content.
    --execute: any # Literal argv list, or executable followed by argv.
    --help(-h) # Show native command help without performing an operation.
] {
    if $help { return (help 'git wt switch') }
    # With --create, remaining positionals belong to launch argv, not selection.
    let supplied = if $create != null and $execute != null and $selector != null { [$selector] | append $command } else { $command }
    let command = if $execute == null { $supplied } else if ($execute | describe) == 'string' {
        [$execute] | append $supplied
    } else if (($execute | describe) | str starts-with 'list<') {
        if not ($supplied | is-empty) { error make {msg: 'use either an argv list or trailing argv, not both'} }
        $execute
    } else { error make {msg: '--execute requires a literal argv list or command string'} }
    let selector = if $create != null and $execute != null { null } else { $selector }
    for arg in $command {
        if ($arg | describe) != 'string' { error make {msg: 'launch argv must contain only strings'} }
    }
    if ($execute == null and not ($command | is-empty)) or ($execute != null and ($command | is-empty)) {
        error make {msg: '--execute requires literal command argv after the selector'}
    }
    if $create != null and $selector != null { error make {msg: 'choose selector or --create, not both'} }
    let repo = (repository)
    let selected = if $selector == null and $create == null {
        if not $nu.is-interactive { error make {msg: 'worktree picker requires interactive Nu; specify a branch or path'} }
        let picked = try { $repo.worktrees | input list --fuzzy --display {|row| $"($row.branch | default 'HEAD')  ($row.path)"} 'Switch worktree' } catch { error make {msg: 'worktree selection cancelled'} }
        if $picked == null { error make {msg: 'worktree selection cancelled'} }
        $picked.path
    } else { $selector }
    let selected_pr = if $selected == null { [] } else { $selected | parse --regex '^pr:(?P<number>[1-9][0-9]*)$' }
    if not ($selected_pr | is-empty) and ($remote | is-empty) { error make {msg: 'PR checkout requires --remote'} }
    let selected_branch = if ($selected_pr | is-empty) { $selected } else { $"pr/($remote)/($selected_pr.0.number)" }
    let existing = if $selected == null { [] } else {
        $repo.worktrees | where {|row| $row.branch == $selected_branch or (same-path $row.path ($selected | path expand))}
    }
    mut created = false
    mut path = ''
    if not ($existing | is-empty) {
        if ($existing | length) != 1 { error make {msg: $"ambiguous worktree: ($selected)"} }
        $path = ($existing | first | get path)
        if not ($path | path exists) { error make {msg: $"worktree path is missing: ($path)"} }
        # Switching may enter dirty/locked worktrees, but never a redirected identity.
        let actual_common = (canonical (git-text $path ['rev-parse' '--path-format=absolute' '--git-common-dir']))
        if not (same-path $actual_common $repo.common_dir) { error make {msg: $"unsafe worktree identity: ($path)"} }
    } else {
        mut branch = $create
        mut base_ref = $base
        mut new_branch = ($create != null)
        mut tracking = false
        let pr = if $selected != null { $selected | parse --regex '^pr:(?P<number>[1-9][0-9]*)$' } else { [] }
        if $create == null and not ($pr | is-empty) {
            if ($remote | is-empty) { error make {msg: 'PR checkout requires --remote'} }
            let number = ($pr | first | get number)
            $branch = $"pr/($remote)/($number)"
            $new_branch = true
            $path = (destination $repo $branch)
            if (git-result $repo.path ['show-ref' '--verify' '--quiet' (branch-ref $branch)]).exit_code == 0 {
                error make {msg: $"PR branch already exists: ($branch)"}
            }
            let fetch_ref = $"refs/wt/pr/($remote)/($number)"
            git-output $repo.path ['fetch' '--no-tags' '--no-write-fetch-head' '--' $remote $"refs/pull/($number)/head:($fetch_ref)"] | ignore
            $base_ref = $fetch_ref
        } else if $create == null {
            let candidates = (branches $repo | where {|row| $row.branch == $selected or ($row.remote and $row.name == $selected)})
            if ($candidates | length) == 0 { error make {msg: $"unknown local or remote branch: ($selected)"} }
            if ($candidates | length) != 1 { error make {msg: $"ambiguous local/remote branch: ($selected); use an explicit remote-qualified name"} }
            let candidate = ($candidates | first)
            if $candidate.name == null { error make {msg: $"remote tracking ref has no configured remote: ($candidate.branch)"} }
            $branch = $candidate.name
            $base_ref = $candidate.ref
            $new_branch = $candidate.remote
            $tracking = $candidate.remote
        }
        if $path == '' { $path = (destination $repo $branch) }
        tip $repo.path $base_ref | ignore
        let args = if $new_branch {
            ['worktree' 'add'] | append (if $tracking { ['--track'] } else { [] }) | append ['-b' $branch '--' $path $base_ref]
        } else { ['worktree' 'add' '--' $path $branch] }
        let destination_path = $path
        try {
            git-output $repo.path $args | ignore
        } catch {|err|
            error make {msg: $"worktree creation failed; inspect preserved destination ($destination_path): ($err.msg)"}
        }
        $created = true
    }
    let path = $path
    cd $path
    if $created {
        try {
            if not $no_submodules { git-output $path ['submodule' 'update' '--init' '--recursive'] | ignore }
            let fresh = (repository)
            run-hooks 'post-create' (context $fresh (current-row $fresh)) $approve_hooks $no_hooks
        } catch {|err| error make {msg: $"worktree setup failed; worktree preserved at ($path): ($err.msg)"} }
    }
    if $execute != null {
        try {
            # Preserve the terminal for interactive agents/editors; do not pipe
            # their stdio through `complete` or capture it in a string.
            run-external ($command | first) ...($command | skip 1)
            if $env.LAST_EXIT_CODE != 0 { error make {msg: $"launch exit ($env.LAST_EXIT_CODE)"} }
        } catch {|err| error make {msg: $"launch failed; worktree preserved at ($path): ($err.msg)"} }
    }
    {path: $path, branch: (git-text $path ['branch' '--show-current']), created: $created}
}

# Explicitly list open PRs through the selected remote's forge CLI.
export def 'wt prs' [--remote: string@complete-remote # Required Git remote name.
] {
    let repo = (repository)
    wt-forge prs (context $repo (if $repo.current == null { {path: $repo.path, branch: 'HEAD'} } else { current-row $repo })) --remote $remote
}

# Run one configured hook event; unapproved project commands never run.
export def 'wt hook' [event: string@complete-event, --no-hooks, --approve-hooks] {
    let repo = (repository)
    run-hooks $event (context $repo (current-row $repo)) $approve_hooks $no_hooks
}

# Remove a clean, unlocked non-primary worktree; leave a surviving cwd.
export def --env 'wt remove' [
    selector?: string@complete-worktree # Branch or path; defaults to current.
    --keep-branch # Retain commits even if the branch is not integrated.
    --no-hooks # Skip all hook processing.
    --approve-hooks # Approve the exact current project-hook commands.
] {
    let repo = (repository)
    let row = if $selector == null { current-row $repo } else { select-row $repo $selector }
    removable $repo $row
    clean-row $repo $row
    if not $keep_branch { integrated $repo $row.branch (default-branch $repo) }
    let survivors = ($repo.worktrees | where {|other| not (same-path $other.path $row.path) and ($other.path | path exists)})
    if ($survivors | is-empty) { error make {msg: 'cannot remove last surviving worktree'} }
    let ctx = (context $repo $row)
    wt-config preflight 'pre-remove' $ctx --approve=$approve_hooks --skip=$no_hooks
    run-hooks 'pre-remove' $ctx false $no_hooks
    let fresh = (repository)
    let checked = (select-row $fresh $row.path)
    removable $fresh $checked
    clean-row $fresh $checked
    let target = if $keep_branch { null } else { default-branch $fresh }
    if not $keep_branch { integrated $fresh $checked.branch $target }
    if $repo.current != null and (same-path $repo.current $row.path) { cd ($survivors | first | get path) }
    try { git-output $env.PWD ['worktree' 'remove' '--' $row.path] | ignore } catch {|err|
        error make {msg: $"worktree removal incomplete; inspect ($row.path); branch retained: ($err.msg)"}
    }
    if not $keep_branch {
        try { delete-integrated-branch $env.PWD $row.branch $target } catch {|err|
            error make {msg: $"partial cleanup: worktree removed; branch/config cleanup incomplete: ($err.msg)"}
        }
    }
    {path: $row.path, branch: $row.branch, removed: true, branch_deleted: (not $keep_branch)}
}

# Squash committed work, rebase, run checks, fast-forward target, then clean up.
# Dirty work is refused; failures preserve the source and a recovery ref.
export def --env 'wt merge' [
    target?: string@complete-target # Target worktree/branch; default branch if omitted.
    --message: string # Squash commit subject; defaults to latest source subject.
    --keep # Retain source worktree and branch after integration.
    --no-hooks # Skip all hook processing.
    --approve-hooks # Approve the exact current project-hook commands.
] {
    let repo = (repository)
    let source = (current-row $repo)
    let target_name = if $target == null { default-branch $repo } else { $target }
    let destination_row = (select-row $repo $target_name)
    if (same-path $source.path $destination_row.path) or $source.branch == $destination_row.branch { error make {msg: 'source and target must be distinct worktrees and branches'} }
    clean-row $repo $source
    clean-row $repo $destination_row
    if not $keep { removable $repo $source }
    let ctx = (context $repo $source $destination_row)
    wt-config preflight 'pre-merge' $ctx --approve=$approve_hooks --skip=$no_hooks
    if not $keep { wt-config preflight 'pre-remove' $ctx --approve=$approve_hooks --skip=$no_hooks }
    let source_ref = (branch-ref $source.branch)
    let target_ref = (branch-ref $destination_row.branch)
    let original = (tip $source.path $source_ref)
    let target_tip = (tip $destination_row.path $target_ref)
    let base = (git-text $source.path ['merge-base' $original $target_tip])
    let backup = $"refs/wt/recovery/($source.branch)/(random uuid)"
    git-output $source.path ['update-ref' $backup $original ''] | ignore
    let merged_tip = try {
        let count = (git-text $source.path ['rev-list' '--count' $"($base)..($original)"] | into int)
        if $count > 0 {
            let subject = if $message == null { git-text $source.path ['log' '-1' '--format=%s' $original] } else { $message }
            let tree = (git-text $source.path ['rev-parse' $"($original)^{tree}"])
            let squashed = (git-text $source.path ['commit-tree' $tree '-p' $base '-m' $subject])
            # Same tree: update committed history without staging or resetting files.
            git-output $source.path ['update-ref' $source_ref $squashed $original] | ignore
        }
        git-output $source.path ['-c' 'rebase.autoStash=false' '-c' 'rebase.updateRefs=false' 'rebase' '--no-autostash' '--onto' $target_tip $base] | ignore
        let rebased = (tip $source.path 'HEAD')
        # Do not auto-approve commands newly introduced by the rebase.
        run-hooks 'pre-merge' $ctx false $no_hooks
        let fresh = (repository)
        let fresh_source = (select-row $fresh $source.path)
        let fresh_target = (select-row $fresh $destination_row.path)
        clean-row $fresh $fresh_source
        clean-row $fresh $fresh_target
        if $fresh_source.branch != $source.branch or $fresh_target.branch != $destination_row.branch or (tip $source.path 'HEAD') != $rebased {
            error make {msg: 'source or target branch changed during merge hooks'}
        }
        if (tip $destination_row.path 'HEAD') != $target_tip { error make {msg: 'target tip changed before fast-forward; retry explicitly'} }
        git-output $destination_row.path ['-c' 'merge.autoStash=false' 'merge' '--ff-only' '--no-autostash' $rebased] | ignore
        let actual_branch = (git-text $destination_row.path ['symbolic-ref' '--quiet' '--short' 'HEAD'])
        if $actual_branch != $destination_row.branch or (tip $destination_row.path $target_ref) != $rebased or (tip $destination_row.path 'HEAD') != $rebased {
            error make {msg: 'target changed concurrently with fast-forward; source retained for inspection'}
        }
        $rebased
    } catch {|err|
        let actual_target = try { tip $destination_row.path $target_ref } catch { null }
        let actual_source = try { tip $source.path $source_ref } catch { null }
        if $actual_target != null and $actual_target != $target_tip and $actual_target == $actual_source {
            error make {msg: $"partial success: target integrated but Git reported failure; source retained at ($source.path); recovery ref ($backup): ($err.msg)"}
        }
        error make {msg: $"merge stopped; source preserved at ($source.path); recovery ref ($backup): ($err.msg)"}
    }
    if not $keep {
        try {
            run-hooks 'pre-remove' $ctx false $no_hooks
            let fresh = (repository)
            let checked = (select-row $fresh $source.path)
            let target_checked = (select-row $fresh $destination_row.path)
            removable $fresh $checked
            clean-row $fresh $checked
            clean-row $fresh $target_checked
            if $checked.branch != $source.branch or $target_checked.branch != $destination_row.branch or (tip $destination_row.path $target_ref) != $merged_tip or (tip $source.path $source_ref) != $merged_tip {
                error make {msg: 'source or target changed before cleanup; worktree retained'}
            }
            integrated $fresh $source.branch $destination_row.branch
            cd $destination_row.path
            git-output $destination_row.path ['worktree' 'remove' '--' $source.path] | ignore
            delete-integrated-branch $destination_row.path $source.branch $destination_row.branch
        } catch {|err|
            error make {msg: $"partial success: target ($destination_row.branch) integrated; cleanup failed; inspect source ($source.path), recovery ref ($backup): ($err.msg)"}
        }
    }
    {source: $source.branch, target: $destination_row.branch, path: $destination_row.path, merged: true, kept: $keep, recovery_ref: $backup}
}