Help and docs
Sign in

grindlemire/dotfiles code browser

main 0375daa
Bash · 687 lines · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
# Get the nice ^r, ^a, and ^e behavior
set -o emacs

# aliases
alias la='ls -a'   # hidden
alias ll='ls -lh'  # long
alias lt='ls -lth' # long time sorted
alias lla='ls -lha' # long and hidden
alias less='less -R'
alias emacs='emacs -nw'
alias cap='ret=$?'
alias check='[ $ret == 0 ] && true || false'
lc() {
    local target="${1:-.}"
    find "$target" -type f \( \( -name '*.go' -a ! -name '*.sql.go' -a ! -name '*_templ.go' \) -o -name '*.templ' \) -print0 | xargs -0 wc -l
}

# ls colors for bsd/linux
ls --color &>/dev/null 2>&1 && alias ls='ls --color=tty' || alias ls='ls -G'

Red="\033[0;31m"
Green='\033[0;32m'
Color_Off='\033[0m'

godir() {
    c "$@"
}

# c [query]: jump to a repo under ~/code/<bucket>/<repo>. An exact repo name
# (c gitstack) or bucket/repo (c alethi/gitstack) goes straight there;
# anything else opens fzf filtered to the query, auto-picking a lone match.
c() {
    local root=$HOME/code dir
    local -a exact
    if [[ -n $1 ]]; then
        [[ $1 == */* && -d $root/$1 ]] && { cd "$root/$1"; return; }
        exact=($root/*/$1(/N))
        (( ${#exact} == 1 )) && { cd "$exact[1]"; return; }
    fi
    # No cd inside $(...): chpwd hooks (Ghostty's OSC 7) would print into the capture
    dir=$(ls -d "$root"/*/*/ 2>/dev/null | sed "s|^$root/||; s|/\$||" | fzf --select-1 --exit-0 --query="$*") && cd "$root/$dir"
}

# Installed Apps and scripts added to PATH
export PATH=~/Apps/bin:~/dotfiles/scripts:$PATH
export PATH="$PATH:/Applications/Visual Studio Code.app/Contents/Resources/app/bin"
export PATH=/opt/homebrew/bin:$PATH
export PATH=~/Library/Python/3.9/bin:$PATH
export PATH=$HOME/.local/bin:$PATH

# editor needs to be set for commits without -m
export EDITOR='vim'

# go stuff
export GOPATH=$HOME/go
export PATH=/usr/local/go/bin:$GOPATH/bin:/usr/local/bin:$PATH

# git signing stuff
git_sign_init() {
    git config --global gpg.format ssh
    git config --global user.signingKey "$(cat ~/.ssh/$1.pub)"
    git config --global commit.gpgsign true
    git config --global tag.gpgsign true
}

has_param() {
    local term="$1"
    shift
    for arg; do
        if [[ $arg == "$term" ]]; then
            return 0
        fi
    done
    return 1
}

gprune() {
    # auto-detect default branch
    local default_branch=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@')
    if [[ -z "$default_branch" ]]; then
        default_branch=$(git branch -l main master | sed 's/^[* ]*//' | head -1)
    fi
    if [[ -z "$default_branch" ]]; then
        echo "Could not determine default branch"; return 1
    fi

    local dry=false
    if has_param '--dry' "$@"; then
        dry=true
    else
        git fetch --prune --all
    fi

    git checkout -q "$default_branch"

    # collect branches that are regular-merged
    local merged_branches=$(git branch --merged "$default_branch" | sed 's/^[* ]*//' | grep -v "^${default_branch}$")

    git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do
        [[ "$branch" == "$default_branch" ]] && continue
        local dominated=false

        # check 1: regular merge (git branch --merged)
        if echo "$merged_branches" | grep -qx "$branch"; then
            dominated=true
        fi

        # check 2: squash merge (commit-tree trick)
        if ! $dominated; then
            local mergeBase=$(git merge-base "$default_branch" "$branch" 2>/dev/null)
            if [[ -n "$mergeBase" ]] && \
               [[ $(git cherry "$default_branch" $(git commit-tree $(git rev-parse "$branch^{tree}") -p $mergeBase -m _) 2>/dev/null) == "-"* ]]; then
                dominated=true
            fi
        fi

        # check 3: branch's remote was deleted (PR merged and branch cleaned up on remote)
        if ! $dominated; then
            local remote_ref=$(git config "branch.${branch}.merge" 2>/dev/null)
            local remote=$(git config "branch.${branch}.remote" 2>/dev/null)
            if [[ -n "$remote_ref" && -n "$remote" ]] && ! git rev-parse --verify "${remote}/${branch}" &>/dev/null; then
                dominated=true
            fi
        fi

        if $dominated; then
            if $dry; then
                echo "${Green}$branch ${Color_Off}is merged into $default_branch and can be deleted"
            else
                git branch -D "$branch"
            fi
        fi
    done
    return 0
}

# turn a video into a gif
to_gif() {
    FNAME="$(echo $1 | xargs -I file basename file .mov)"
    cmd="ffmpeg -i $1 \
        -vf \"fps=12,scale=1280:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse\" \
        -loop 0 ${FNAME}.gif"
    echo -e "${Green} Running Cmd:\n    ${cmd}${Color_Off}\n"
    eval "$cmd"
}

###############################################################################
# zsh stuff
###############################################################################

myip() {
    ifconfig en0 | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'
}

# set window title and share pwd accross sessions
update_terminal_cwd() {
    local PWD_URL="file://$HOSTNAME${PWD// /%20}"
    printf '\e]7;%s\a' "$PWD_URL"
}

clone() {
	git clone [email protected]:$1
}

fixssh() {
	. ensure-ssh-agent
}

rawbranch() {
    local branch=$(git branch 2>/dev/null | grep \* | awk -F '\\* ' '{$0=$2}1')
    [[ -z "$branch" ]] && return
    printf "%s" "$branch"
}

gbranch() {
    local branch=$(rawbranch)
    [[ -z "$branch" ]] && return
    # Add worktree indicator if in a worktree
    if [[ "$PWD" == *"/.worktrees/"* ]]; then
        printf "wt:%s" "$branch"
    else
        printf "%s" "$branch"
    fi
}

gproject() {
    local cwd="$PWD"
    if [[ "$cwd" == *"/.worktrees/"* ]]; then
        # In a worktree - extract project name (directory containing .worktrees)
        printf "%s" "$(echo "$cwd" | sed 's|/.worktrees/.*||' | xargs basename)"
    else
        # Not in worktree - show current directory
        printf "%s" "${PWD##*/}"
    fi
}

# alias git pull and git push from the current branch
gpull() {
    BRANCH=$(rawbranch)
    if [ -n "$1" ]; then
        BRANCH=$1
    fi

    CMD="git pull origin ${BRANCH}"
    echo -e "${Green} Running Cmd:\n    ${CMD} ${Color_Off}\n"
    eval "$CMD"
}

gpush() {
    BRANCH=$(rawbranch)
    if [ -n "$1" ]; then
        BRANCH=$1
    fi

    # If there are uncommitted changes, commit first
    if [ -n "$(git status --porcelain)" ]; then
        gcommit || return 1
    fi

    CMD="git push origin ${BRANCH}"
    echo -e "${Green} Running Cmd:\n    ${CMD} ${Color_Off}\n"
    eval "$CMD"
}

gadd() {
    CMD="git add ."
    echo -e "${Green} Running Cmd:\n    ${CMD} ${Color_Off}\n"
    eval "$CMD"
}

gcommit() {
    local NEED_GADD=false
    local MSG
    local CLAUDE_EXIT

    # If something is already staged, commit only staged changes.
    if git diff --cached --quiet --exit-code; then
        NEED_GADD=true
    fi

    if [ -n "$1" ] && [ "$1" = "-m" ]; then
        # Skip -m and use remaining arguments as message
        shift
        MSG="$@"
    elif [ -n "$1" ]; then
        MSG="$@"
    else
        # Auto-generate using Claude Code
        if [ "$NEED_GADD" = true ]; then
            gadd
            NEED_GADD=false
        fi
        echo -e "${Green}Generating commit message...${Color_Off}"
        MSG=$(git diff --cached --diff-algorithm=minimal | claude -p "Generate a concise git commit message (subject line only, no body, max 72 chars) for these changes. OUTPUT ONLY THE MESSAGE, NOTHING ELSE." 2>/dev/null)
        CLAUDE_EXIT=$?
        if [ -z "$MSG" ] || [ $CLAUDE_EXIT -ne 0 ]; then
            MSG="snapshot $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
            echo -e "${Red}Claude generation failed, using timestamp${Color_Off}"
        fi
    fi

    if [ "$NEED_GADD" = true ]; then
        gadd
    fi
    CMD="git commit -m \"$MSG\""
    echo -e "${Green} Running Cmd:\n    ${CMD} ${Color_Off}\n"
    fixssh > /dev/null 2>&1
    eval "$CMD"
}

grevert() {
    git reset --hard HEAD~1
}

grollback() {
    git revert --no-edit HEAD
}

unalias gs 2>/dev/null
unfunction gs 2>/dev/null

gstat() {
    git status -sb
}

# pretty git log
glog() {
    git log --graph --pretty=format:'%C(yellow)%h%Creset -%C(auto)%d%Creset %s %C(green)(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit "${@:-HEAD~10..HEAD}"
}

# better diff viewing with pager
gdiff() {
    git diff --color=always "$@" | less -R
}

# staged diff viewing with pager
gdiffs() {
    git diff --staged --color=always "$@" | less -R
}

# search for processes (cross-platform)
psgrep() {
    ps aux | grep -v grep | grep -i -e VSZ -e "$@"
}

# kill process on specific port (cross-platform)
killport() {
    if [ -z "$1" ]; then
        echo "usage: killport <port>"
        return 1
    fi

    if command -v lsof >/dev/null 2>&1; then
        # macOS and most Linux with lsof
        lsof -ti tcp:"$1" | xargs kill -9 2>/dev/null
    elif command -v ss >/dev/null 2>&1; then
        # Linux with ss (iproute2)
        local pid=$(ss -lptn "sport = :$1" | grep -oP 'pid=\K[0-9]+' | head -1)
        if [ -n "$pid" ]; then
            kill -9 "$pid"
        else
            echo "No process found on port $1"
            return 1
        fi
    else
        echo "Neither lsof nor ss available"
        return 1
    fi
}

# universal archive extractor
extract () {
    if [ -z "$1" ]
    then
            echo "usage: extract <archive>"
            return 1
    fi
    if [ -f "$1" ]
    then
        case "$1" in
            (*.tar.bz2) tar xjf "$1" ;;
            (*.tar.gz) tar xzf "$1" ;;
            (*.bz2) bunzip2 -k "$1" ;;
            (*.rar) unrar x "$1" ;;
            (*.gz) gunzip -k "$1" ;;
            (*.tar) tar xf "$1" ;;
            (*.tbz2) tar xjf "$1" ;;
            (*.tgz) tar xzf "$1" ;;
            (*.zip) unzip "$1" ;;
            (*.Z) gzip -dk "$1" ;;
            (*.7z) 7z x "$1" ;;
            (*.tar.xz) tar xf "$1" ;;
            (*.xz) xz -dk "$1" ;;
            (*) echo "'$1' cannot be extracted via extract()" ;;
        esac
    else
        echo "'$1' is not a valid file"
        return 1
    fi
}

grelease() {
    fixssh > /dev/null 2>&1

    local create_release=false
    if [ "$1" = "-push" ]; then
        create_release=true
        shift
    fi
    local version_type="${1:-patch}"

    # Validate version type
    if [[ ! "$version_type" =~ ^(patch|minor|major)$ ]]; then
        echo -e "${Red}Error: Version type must be patch, minor, or major${Color_Off}"
        return 1
    fi

    # Fetch latest tags from remote
    echo -e "${Green}Fetching latest tags...${Color_Off}"
    git fetch --tags --quiet

    # Get the latest version tag (vX.X.X format)
    local latest_tag=$(git tag -l 'v*' | sort -V | tail -n 1)

    # If no tags exist, start at v0.0.1
    if [ -z "$latest_tag" ]; then
        latest_tag="v0.0.0"
        echo -e "${Green}No existing tags found, starting from v0.0.0${Color_Off}"
    else
        echo -e "${Green}Current latest tag: ${latest_tag}${Color_Off}"
    fi

    # Extract version numbers (remove 'v' prefix)
    local version="${latest_tag#v}"
    local major minor patch

    # Parse version into components
    IFS='.' read -r major minor patch <<< "$version"

    # Ensure we have valid numbers (handle missing components)
    major=${major:-0}
    minor=${minor:-0}
    patch=${patch:-0}

    # Increment based on version type
    case "$version_type" in
        major)
            major=$((major + 1))
            minor=0
            patch=0
            ;;
        minor)
            minor=$((minor + 1))
            patch=0
            ;;
        patch)
            patch=$((patch + 1))
            ;;
    esac

    local new_version="v${major}.${minor}.${patch}"

    echo -e "${Green}New version: ${new_version}${Color_Off}"

    # Check if tag already exists
    if git rev-parse "$new_version" >/dev/null 2>&1; then
        echo -e "${Red}Error: Tag ${new_version} already exists${Color_Off}"
        return 1
    fi

    # Create and push the tag
    CMD="git tag -a ${new_version} -m \"Release ${new_version}\""
    echo -e "${Green}Running Cmd:\n    ${CMD}${Color_Off}\n"
    eval "$CMD"

    if [ $? -ne 0 ]; then
        echo -e "${Red}Error: Failed to create tag${Color_Off}"
        return 1
    fi

    CMD="git push origin ${new_version}"
    echo -e "\n${Green}Running Cmd:\n    ${CMD}${Color_Off}\n"
    eval "$CMD"

    if [ $? -ne 0 ]; then
        echo -e "${Red}Error: Failed to push tag${Color_Off}"
        return 1
    fi

    if [ "$create_release" = true ]; then
        echo -e "${Green}Generating release notes...${Color_Off}"

        # Get commits between previous and new tag
        local commit_log
        if [ "$latest_tag" = "v0.0.0" ]; then
            commit_log=$(git log --oneline HEAD)
        else
            commit_log=$(git log --oneline ${latest_tag}..${new_version})
        fi

        # Generate body via Claude
        local release_title="$new_version"

        local release_body
        release_body=$(echo "$commit_log" | claude -p "Generate release notes in markdown for these commits. Include a brief summary and bullet points for notable changes. Output ONLY the markdown." 2>/dev/null)
        local CLAUDE_BODY_EXIT=$?

        # Fallback if Claude fails
        if [ -z "$release_body" ] || [ $CLAUDE_BODY_EXIT -ne 0 ]; then
            release_body="$commit_log"
            echo -e "${Red}Claude body generation failed, using commit log${Color_Off}"
        fi

        # Create temporary file for release notes to handle newlines properly
        local notes_file=$(mktemp)
        echo "$release_body" > "$notes_file"

        # Create GitHub release
        CMD="gh release create ${new_version} --title \"${release_title}\" --notes-file \"${notes_file}\""
        echo -e "${Green}Running Cmd:\n    ${CMD}${Color_Off}\n"
        eval "$CMD"
        local release_exit=$?

        # Clean up temporary file
        rm -f "$notes_file"

        if [ $release_exit -ne 0 ]; then
            echo -e "${Red}Error: Failed to create GitHub release${Color_Off}"
            return 1
        fi
    fi
    return 0
}


setopt PROMPT_SUBST
# prompt
PROMPT='%(?^%F{green}[%n@%m] [$(gproject)] [$(gbranch)]%f^%F{red}[%n@%m] [$(gproject)] [$(gbranch)]%f)$ '

# in-place delete
bindkey '^[[3~'  delete-char
# zsh history
HISTFILE=$HOME/.zhistory
HISTSIZE=50000
SAVEHIST=50000
# setopt APPEND_HISTORY
setopt SHARE_HISTORY
history() { builtin history 1 }
# up/down searching
autoload -U up-line-or-beginning-search
autoload -U down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey "^[[A" up-line-or-beginning-search # Up
bindkey "^[[B" down-line-or-beginning-search # Down
# cmd line completion
fpath=(~/dotfiles/completions $fpath)
autoload -U compinit && compinit
zstyle ':completion:*' menu select
# batch rename
autoload -U zmv
# extended globbing but don't error on no match
setopt EXTENDED_GLOB
unsetopt NOMATCH
autoload -U add-zsh-hook
add-zsh-hook precmd update_terminal_cwd
add-zsh-hook preexec update_terminal_cwd
add-zsh-hook chpwd update_terminal_cwd

# set vi mode and make the cursor a block underline cursor if we are in cmd mode
bindkey -v
# I like these bindings and use them all the time. Make sure they stay the same
bindkey "^R" history-incremental-search-backward
bindkey "^E" end-of-line
bindkey "^A" beginning-of-line
function zle-keymap-select zle-line-init zle-line-finish {
  case $KEYMAP in
    vicmd)      echo -ne "\e[4 q";; # block underline cursor for cmd
    viins|main) echo -ne "\e[5 q";; # line cursor
  esac

  zle reset-prompt
  zle -R
}
zle -N zle-line-init
zle -N zle-line-finish
zle -N zle-keymap-select

HOMEBREW_AUTO_UPDATE_SECS=2629746

# source in the worktree helpers
. ~/dotfiles/worktree.sh 2>/dev/null
# source in the macbook specific config
. ~/dotfiles/macbook.sh &>/dev/null
# source in the virtualenv helpers
. ~/dotfiles/virtualenv.sh 2>/dev/null
# source in the docker-compose helpers
. ~/dotfiles/docker.sh 2>/dev/null
# source in the untracked environment specific configuration
. ~/dotfiles/local-zshrc.sh 2>/dev/null

. "$HOME/.local/bin/env"

# Ralph Wiggum loop - run claude with a prompt file until <promise>COMPLETE</promise> or max iterations
execute() {
    local prompt_file="${1:-prompt.md}"
    local max_iterations="${2:-10}"
    local iteration=1

    if [ ! -f "$prompt_file" ]; then
        echo -e "${Red}Error: Prompt file '$prompt_file' not found${Color_Off}"
        echo "usage: execute [prompt_file] [max_iterations]"
        echo "  prompt_file: path to prompt file (default: prompt.md)"
        echo "  max_iterations: max iterations before bailing (default: 10)"
        return 1
    fi

    echo -e "${Green}Starting execute loop with '$prompt_file' (max $max_iterations iterations)${Color_Off}"

    while [ $iteration -le $max_iterations ]; do
        echo -e "\n${Green}━━━ Iteration $iteration/$max_iterations ━━━${Color_Off}\n"

        local tmpfile=$(mktemp)
        local jsonbuf=$(mktemp)
        claude -p "$(cat "$prompt_file")" --dangerously-skip-permissions --output-format stream-json --verbose --include-partial-messages 2>&1 | tee "$tmpfile" | while IFS= read -r line; do
            echo "$line" | jq -rj --unbuffered '
              if .type == "stream_event" then
                if .event.type == "content_block_delta" and .event.delta.type == "text_delta" then
                  .event.delta.text
                elif .event.type == "content_block_delta" and .event.delta.type == "thinking_delta" then
                  "\u001b[0;90m\(.event.delta.thinking)\u001b[0m"
                elif .event.type == "content_block_start" and .event.content_block.type == "tool_use" then
                  "\n\u001b[0;36m● \(.event.content_block.name)\u001b[0m "
                elif .event.type == "content_block_start" and .event.content_block.type == "text" then
                  "\n\n"
                else empty
                end
              else empty
              end
            ' 2>/dev/null
            # Accumulate tool input JSON
            toolinput=$(echo "$line" | jq -r 'if .type == "stream_event" and .event.type == "content_block_delta" and .event.delta.type == "input_json_delta" then .event.delta.partial_json else empty end' 2>/dev/null)
            if [[ -n "$toolinput" ]]; then
                printf "%s" "$toolinput" >> "$jsonbuf"
            fi
            # On tool end, show formatted summary
            if echo "$line" | jq -e '.type == "stream_event" and .event.type == "content_block_stop"' >/dev/null 2>&1; then
                if [[ -s "$jsonbuf" ]]; then
                    summary=$(cat "$jsonbuf" | jq -r '
                      if .file_path then "\u001b[0;90m\(.file_path | split("/") | last)\u001b[0m"
                      elif .pattern then "\u001b[0;90m\(.pattern)\u001b[0m"
                      elif .command then "\u001b[0;90m\(.command | if length > 60 then .[0:60] + "..." else . end)\u001b[0m"
                      elif .todos then "\u001b[0;90m(\(.todos | length) items)\u001b[0m"
                      elif .query then "\u001b[0;90m\(.query)\u001b[0m"
                      else empty
                      end
                    ' 2>/dev/null)
                    [[ -n "$summary" ]] && printf "%s" "$summary"
                    : > "$jsonbuf"
                fi
            fi
        done
        rm -f "$jsonbuf"
        local result=$(cat "$tmpfile")

        # Extract token usage from the result message
        local token_stats=$(cat "$tmpfile" | grep '"type":"result"' | jq -r '
          def human(n): if n >= 1000000 then "\(n / 1000000 | . * 10 | floor / 10)M"
                        elif n >= 1000 then "\(n / 1000 | . * 10 | floor / 10)K"
                        else "\(n)" end;
          def cost(n): if n > 0 then "$\(n * 100 | floor / 100)" else "$0" end;
          "Input: \(human(.usage.input_tokens // 0))  Output: \(human(.usage.output_tokens // 0))  Cache ↓\(human(.usage.cache_read_input_tokens // 0)) ↑\(human(.usage.cache_creation_input_tokens // 0))  Cost: \(cost(.total_cost_usd // 0))"
        ' 2>/dev/null)
        rm -f "$tmpfile"

        echo -e "\n\033[0;33m${token_stats:-Token stats unavailable}\033[0m"

        # Extract just the text content from the final result, not the entire JSON stream
        local final_text=$(echo "$result" | grep '"type":"result"' | jq -r '.result // empty' 2>/dev/null)
        if [[ "$final_text" == *"<promise>COMPLETE</promise>"* ]]; then
            echo -e "\n${Green}✓ Completed successfully on iteration $iteration${Color_Off}"
            return 0
        fi

        echo -e "\n${Red}━━━ End of iteration $iteration ━━━${Color_Off}"
        iteration=$((iteration + 1))
    done

    echo -e "\n${Red}✗ Reached max iterations ($max_iterations)${Color_Off}"
    return 1
}

cc() {
    local yolo=1
    local args=()

    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case "$1" in
            -s|--safe)
                yolo=0
                shift
                ;;
            *)
                # Pass through to claude
                args+=("$1")
                shift
                ;;
        esac
    done

    if [[ $yolo -eq 1 ]]; then
        claude --permission-mode auto "${args[@]}"
    else
        claude "${args[@]}"
    fi
}

# Added by Antigravity
export PATH="/Users/joelholsteen/.antigravity/antigravity/bin:$PATH"

# bun completions
[ -s "/Users/joelholsteen/.bun/_bun" ] && source "/Users/joelholsteen/.bun/_bun"

# bun
export BUN_INSTALL="$HOME/.bun"
export PATH="$BUN_INSTALL/bin:$PATH"