Repository navigation
Expand file tree
/
Copy pathwt-herdr
More file actions
executable file
·846 lines (736 loc) · 30.4 KB
/
Copy pathwt-herdr
File metadata and controls
executable file
·846 lines (736 loc) · 30.4 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
#!/usr/bin/env bash
# wt-herdr — worktrunk ↔ herdr bridge
#
# Callable as `wt herdr <subcommand>` when `wt-herdr` is on PATH.
# Implements the worktrunk custom subcommand pattern.
#
# Subcommands:
# manifest Print plugin manifest JSON
# health Check dependencies (herdr, herdr server, jq, wt)
# sync Sync all worktrees as herdr workspaces
# clean Close herdr workspaces for deleted worktrees
# focus Focus herdr workspace for current worktree
# status Show mapping between worktrees and herdr workspaces
# update-labels Refresh status badges in workspace labels
# event Handle lifecycle events (called from hooks)
# init Set up hooks config + initial sync
set -euo pipefail
IFS=$'\n\t'
# ── Constants ──────────────────────────────────────────────────────────
SELF_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_MANIFEST='{
"name": "herdr",
"executable": "wt-herdr",
"description": "Worktrunk ↔ herdr bridge — auto-sync git worktrees as herdr workspaces",
"api_versions": ["wt-custom-subcommand.v0"],
"version": "0.1.0",
"source": "https://github.com/mattarau/wt-herdr",
"events": ["worktree-created","worktree-removed","worktree-switched"],
"subcommands": ["manifest","health","sync","clean","focus","status","update-labels","event","init"]
}'
# ── Output helpers ─────────────────────────────────────────────────────
err() { printf '%s\n' "$*" >&2; }
die() { err "$*"; exit 1; }
json() { printf '%s\n' "$*"; }
json_o() { json '{'"$1"'}'; }
json_kv(){ json '"'"$1"'": "'"$2"'",'; }
have() { command -v "$1" >/dev/null 2>&1; }
version_from_manifest() {
local line v=""
while IFS= read -r line; do
case "$line" in *'"version"'*) v=${line#*:}; v=${v//[\", ]/}; v=${v%,}; break;; esac
done <<< "$PLUGIN_MANIFEST"
printf '%s' "$v"
}
# ── Session handling ───────────────────────────────────────────────────
# HERDR_SESSION is set by main() from `--session <name>` or inherited from env.
# All herdr calls should use _session_prefix before the subcommand.
_session_prefix() {
local s="${HERDR_SESSION:+}"
if [[ -n "$s" ]]; then printf '--session %q ' "$s"; fi
}
# Run herdr with the active session
herdr_with_session() {
# shellcheck disable=SC2086
herdr $(_session_prefix) "$@"
}
# ── herdr helpers ──────────────────────────────────────────────────────
herdr_server_up() {
local _out
_out=$(herdr status server 2>/dev/null) || true
case "$_out" in
*"status: running"*) return 0 ;;
*) return 1 ;;
esac
}
herdr_workspace_list() {
# Direct pipe approach — capture stdout only, fallback on failure
herdr_with_session workspace list 2>/dev/null || echo '{"result":{"workspaces":[]}}'
}
# ── Session management ────────────────────────────────────────────────
_ensure_session() {
local name="$1"
# Default session is always running
[[ "$name" == "default" ]] && return 0
# Already running?
herdr session list --json 2>/dev/null | jq -e --arg n "$name" \
'.sessions[] | select(.name == $n and .running)' >/dev/null && return 0
# Start session server (background, auto-daemonizes)
herdr --session "$name" server >/dev/null 2>&1 &
# Poll until running (up to ~2s)
local i=0
while [[ $i -lt 10 ]]; do
herdr session list --json 2>/dev/null | jq -e --arg n "$name" \
'.sessions[] | select(.name == $n and .running)' >/dev/null && return 0
sleep 0.2
i=$((i+1))
done
err "wt-herdr: could not start session '$name'"
return 1
}
herdr_ws_close() {
local ws_id="$1"
herdr_with_session workspace close "$ws_id" >/dev/null 2>&1 || true
}
herdr_ws_focus() {
local ws_id="$1"
herdr_with_session workspace focus "$ws_id" >/dev/null 2>&1 || true
}
herdr_ws_rename() {
local ws_id="$1" new_label="$2"
herdr_with_session workspace rename "$ws_id" "$new_label" >/dev/null 2>&1 || true
}
herdr_tab_create() {
local ws_id="$1" cwd="$2" label="$3"
herdr_with_session tab create --workspace "$ws_id" --cwd "$cwd" --label "$label" --focus >/dev/null 2>&1 || true
}
herdr_notify() {
local title="$1" body="${2:-}" sound="${3:-none}"
local args=()
[[ -n "$body" ]] && args+=(--body "$body")
[[ "$sound" != "none" ]] && args+=(--sound "$sound")
[[ ${#args[@]} -gt 0 ]] && herdr_with_session notification show "$title" "${args[@]}" >/dev/null 2>&1 || true
}
# ── herdr worktree helpers ─────────────────────────────────────────────
herdr_worktree_list() {
herdr_with_session worktree list --json 2>/dev/null \
|| echo '{"result":{"worktrees":[]}}'
}
# Find workspace ID for a branch in a repo. Uses worktree metadata (fast path).
# Falls back to workspace label matching for legacy workspaces created
# before herdr worktree tracking was available.
herdr_wt_find_ws_by_branch() {
local repo="$1" branch="$2"
local ws_id
ws_id=$(herdr_worktree_list \
| jq -r --arg b "$branch" \
'.result.worktrees[] | select(.branch == $b) | .open_workspace_id' \
| head -1)
if [[ -z "$ws_id" ]]; then
ws_id=$(herdr_workspace_list \
| jq -r --arg repo "$repo" --arg b "$branch" \
'.result.workspaces[] | select((.label | startswith($repo + " / " + $b + " ")) or (.label == ($repo + " / " + $b))) | .workspace_id' \
| head -1)
fi
printf '%s' "$ws_id"
}
# Create workspace for worktree. Uses herdr workspace create for the main
# repo checkout. Uses herdr worktree open for linked worktrees (which gives
# native worktree metadata), with fallback to workspace create.
herdr_wt_open_or_create() {
local path="$1" label="$2" branch="$3" repo="$4"
local ws_id
ws_id=$(herdr_wt_find_ws_by_branch "$repo" "$branch")
[[ -n "$ws_id" ]] && { printf '%s' "$ws_id"; return 0; }
local repo_root
repo_root=$(git -C "$path" rev-parse --show-toplevel 2>/dev/null || echo "")
if [[ -n "$repo_root" && "$repo_root" != "$path" ]]; then
herdr_with_session worktree open --path "$path" --label "$label" --no-focus >/dev/null 2>&1 || {
herdr_with_session workspace create --label "$label" --cwd "$path" --no-focus >/dev/null 2>&1 || return 1
}
else
herdr_with_session workspace create --label "$label" --cwd "$path" --no-focus >/dev/null 2>&1 || return 1
fi
ws_id=$(herdr_wt_find_ws_by_branch "$repo" "$branch")
[[ -n "$ws_id" ]] || return 1
printf '%s' "$ws_id"
}
# Close workspace — prefers worktree remove for tracked worktrees,
# falls back to workspace close for legacy/non-worktree workspaces.
herdr_wt_remove_ws() {
local ws_id="$1"
local is_tracked
is_tracked=$(herdr_worktree_list \
| jq -r --arg wid "$ws_id" \
'.result.worktrees[] | select(.open_workspace_id == $wid) | .open_workspace_id' \
| head -1)
if [[ -n "$is_tracked" ]]; then
herdr_with_session worktree remove --workspace "$ws_id" --force >/dev/null 2>&1 || true
else
herdr_with_session workspace close "$ws_id" >/dev/null 2>&1 || true
fi
}
# ── Worktrunk helpers ──────────────────────────────────────────────────
_wt_list() {
wt list --format=json 2>/dev/null || echo '[]'
}
_wt_worktrees() {
_wt_list | jq -c '.[] | select(.kind == "worktree")'
}
_wt_current_branch() {
_wt_list | jq -r '.[] | select(.is_current) | .branch // empty' | head -1
}
_wt_repo_name() {
local name
name=$(git rev-parse --show-toplevel 2>/dev/null | xargs basename 2>/dev/null || true)
if [[ -z "$name" ]]; then
name=$(basename "$(git remote get-url origin 2>/dev/null)" .git 2>/dev/null || echo "repo")
fi
printf '%s' "$name"
}
_wt_worktree_for_branch() {
local branch="$1"
_wt_list | jq -r --arg branch "$branch" '.[] | select(.branch == $branch and .kind == "worktree") | .path // empty' | head -1
}
_wt_symbols() {
local branch="$1"
_wt_list | jq -r --arg branch "$branch" '.[] | select(.branch == $branch) | .symbols // empty' | head -1
}
# Build workspace label: "{repo} / {branch} {symbols}"
_make_label() {
local repo="$1" branch="$2" symbols="$3"
if [[ -n "$symbols" ]]; then
printf '%s / %s %s' "$repo" "$branch" "$symbols"
else
printf '%s / %s' "$repo" "$branch"
fi
}
# Extract branch name from a label that may have symbols
_label_branch() {
local label="$1"
local stripped="${label#* / }"
case "$stripped" in
*' '*) printf '%s' "${stripped%% *}" ;;
*) printf '%s' "$stripped" ;;
esac
}
# Extract repo name from a label
_label_repo() {
local label="$1"
printf '%s' "${label%% / *}"
}
# ── Subcommand: manifest ──────────────────────────────────────────────
cmd_manifest() {
printf '%s\n' "$PLUGIN_MANIFEST"
}
# ── Subcommand: health ────────────────────────────────────────────────
cmd_health() {
local v herdr_bin jq_bin wt_bin
local ha=false sr=false ja=false wa=false
v=$(version_from_manifest)
herdr_bin=$(command -v herdr 2>/dev/null || true)
jq_bin=$(command -v jq 2>/dev/null || true)
wt_bin=$(command -v wt 2>/dev/null || true)
[[ -n "$herdr_bin" ]] && ha=true
[[ -n "$jq_bin" ]] && ja=true
[[ -n "$wt_bin" ]] && wa=true
if $ha; then herdr_server_up 2>/dev/null && sr=true; fi
local ok=true reason="null"
if ! $ha; then ok=false; reason="\"herdr not installed\""
elif ! $sr; then ok=false; reason="\"herdr server not running\""
fi
if ! $ja; then ok=false; reason="\"jq not installed\""
fi
if ! $wa; then ok=false; reason="\"wt (worktrunk) not installed\""
fi
json "{
\"ok\": $ok,
\"version\": \"$v\",
\"reason\": $reason,
\"herdr\": \"$herdr_bin\",
\"herdr_available\": $ha,
\"server_running\": $sr,
\"jq\": \"$jq_bin\",
\"jq_available\": $ja,
\"wt\": \"$wt_bin\",
\"wt_available\": $wa
}"
$ok || exit 30
}
# ── Subcommand: sync ─────────────────────────────────────────────────
cmd_sync() {
local dry_run=false
while [[ $# -gt 0 ]]; do
case "$1" in
--dry-run) dry_run=true ;;
*) err "wt-herdr sync: unknown option '$1'"; exit 2 ;;
esac
shift
done
have herdr || die "wt-herdr: herdr not installed"
have jq || die "wt-herdr: jq not installed"
have wt || die "wt-herdr: wt (worktrunk) not installed"
local repo_name
repo_name=$(_wt_repo_name)
[[ -n "$repo_name" ]] || die "wt-herdr: not in a git repository"
export HERDR_SESSION="${HERDR_SESSION:-default}"
_ensure_session "$HERDR_SESSION" || die "wt-herdr: could not start session '$HERDR_SESSION'"
local created=0 updated=0 skipped=0 errors=0
local results="["
while IFS= read -r wt; do
[[ -n "$wt" ]] || continue
local branch path symbols label ws_id
branch=$(echo "$wt" | jq -r '.branch // "detached"')
path=$(echo "$wt" | jq -r '.path // ""')
symbols=$(echo "$wt" | jq -r '.symbols // ""')
is_current=$(echo "$wt" | jq -r '.is_current // false')
[[ -n "$path" ]] || { errors=$((errors+1)); continue; }
label=$(_make_label "$repo_name" "$branch" "$symbols")
if $dry_run; then
printf '{"branch":"%s","action":"would-create","label":"%s","path":"%s","is_current":%s}\n' \
"$branch" "$label" "$path" "$is_current"
skipped=$((skipped+1))
continue
fi
ws_id=$(herdr_wt_find_ws_by_branch "$repo_name" "$branch")
if [[ -z "$ws_id" ]]; then
ws_id=$(herdr_wt_open_or_create "$path" "$label" "$branch" "$repo_name") || {
errors=$((errors+1))
continue
}
herdr_tab_create "$ws_id" "$path" "$branch"
created=$((created+1))
else
local current_label
current_label=$(herdr_workspace_list | jq -r --arg wid "$ws_id" '.result.workspaces[] | select(.workspace_id == $wid) | .label // ""' | head -1)
if [[ "$current_label" != "$label" ]]; then
herdr_ws_rename "$ws_id" "$label"
updated=$((updated+1))
else
skipped=$((skipped+1))
fi
fi
done <<< "$(_wt_worktrees)"
# Remove trailing comma and close array
results="${results%,}]"
# Build final response
json "{
\"status\": \"ok\",
\"repo\": \"$repo_name\",
\"created\": $created,
\"updated\": $updated,
\"skipped\": $skipped,
\"errors\": $errors
}"
herdr_notify "wt-herdr: sync complete" "$created created, $updated updated, $skipped unchanged" "done"
}
# ── Subcommand: clean ─────────────────────────────────────────────────
cmd_clean() {
local dry_run=false
while [[ $# -gt 0 ]]; do
case "$1" in
--dry-run) dry_run=true ;;
*) err "wt-herdr clean: unknown option '$1'"; exit 2 ;;
esac
shift
done
have herdr || die "wt-herdr: herdr not installed"
have jq || die "wt-herdr: jq not installed"
have wt || die "wt-herdr: wt (worktrunk) not installed"
herdr_server_up || die "wt-herdr: herdr server not running"
local repo_name
repo_name=$(_wt_repo_name)
[[ -n "$repo_name" ]] || die "wt-herdr: not in a git repository"
export HERDR_SESSION="${HERDR_SESSION:-default}"
_ensure_session "$HERDR_SESSION" || die "wt-herdr: could not start session '$HERDR_SESSION'"
# Get active worktree branches
local active_branches
active_branches=$(_wt_list | jq -c '[.[] | select(.kind == "worktree") | .branch]')
local closed=0 errors=0
# Find orphan tracked worktrees (branch no longer in wt list)
while IFS= read -r wt; do
local branch is_linked ws_id
branch=$(echo "$wt" | jq -r '.branch // ""')
is_linked=$(echo "$wt" | jq -r '.is_linked_worktree // false')
ws_id=$(echo "$wt" | jq -r '.open_workspace_id // ""')
[[ "$is_linked" == "true" ]] || continue
local found
found=$(echo "$active_branches" | jq -r --arg b "$branch" 'contains([$b])')
if [[ "$found" != "true" ]]; then
if $dry_run; then
echo "Would close workspace: $branch ($ws_id)"
closed=$((closed+1))
else
herdr_wt_remove_ws "$ws_id" && closed=$((closed+1)) || errors=$((errors+1))
fi
fi
done <<< "$(herdr_worktree_list | jq -c '.result.worktrees[]')"
# Legacy cleanup: workspaces without worktree metadata
while IFS= read -r ws; do
local ws_id has_wt
ws_id=$(echo "$ws" | jq -r '.workspace_id')
has_wt=$(echo "$ws" | jq -r 'if .worktree then "true" else "false" end')
[[ "$has_wt" == "false" ]] || continue
local ws_label
ws_label=$(echo "$ws" | jq -r '.label // ""')
case "$ws_label" in
*" / "*) ;; *) continue ;;
esac
local lr
lr=$(_label_repo "$ws_label")
[[ "$lr" == "$repo_name" ]] || continue
local ws_branch
ws_branch=$(_label_branch "$ws_label")
[[ -n "$ws_branch" ]] || continue
local found
found=$(echo "$active_branches" | jq -r --arg b "$ws_branch" 'contains([$b])')
if [[ "$found" != "true" ]]; then
if $dry_run; then
echo "Would close workspace: $ws_label ($ws_id)"
closed=$((closed+1))
else
herdr_ws_close "$ws_id" && closed=$((closed+1)) || errors=$((errors+1))
fi
fi
done <<< "$(herdr_workspace_list | jq -c '.result.workspaces[]')"
json "{
\"status\": \"ok\",
\"repo\": \"$repo_name\",
\"closed\": $closed,
\"errors\": $errors
}"
if [[ "$closed" -gt 0 ]]; then
herdr_notify "wt-herdr: clean complete" "Closed $closed workspaces" "none"
fi
}
# ── Subcommand: focus ─────────────────────────────────────────────────
cmd_focus() {
have herdr || die "wt-herdr: herdr not installed"
have jq || die "wt-herdr: jq not installed"
have wt || die "wt-herdr: wt (worktrunk) not installed"
herdr_server_up || die "wt-herdr: herdr server not running"
local repo_name current_branch
repo_name=$(_wt_repo_name)
export HERDR_SESSION="${HERDR_SESSION:-default}"
_ensure_session "$HERDR_SESSION" || die "wt-herdr: could not start session '$HERDR_SESSION'"
current_branch=$(_wt_current_branch)
[[ -n "$current_branch" ]] || die "wt-herdr: could not detect current branch"
local ws_id
ws_id=$(herdr_wt_find_ws_by_branch "$repo_name" "$current_branch")
if [[ -z "$ws_id" ]]; then
local path symbols label
path=$(_wt_worktree_for_branch "$current_branch")
symbols=$(_wt_symbols "$current_branch")
label=$(_make_label "$repo_name" "$current_branch" "$symbols")
ws_id=$(herdr_wt_open_or_create "$path" "$label" "$current_branch" "$repo_name") || die "wt-herdr: could not create workspace for '$current_branch'"
herdr_tab_create "$ws_id" "$path" "$current_branch"
fi
herdr_ws_focus "$ws_id"
json "{
\"status\": \"ok\",
\"branch\": \"$current_branch\",
\"workspace_id\": \"$ws_id\"
}"
herdr_notify "wt-herdr: focus" "$current_branch" "none"
}
# ── Subcommand: status ────────────────────────────────────────────────
cmd_status() {
have herdr || die "wt-herdr: herdr not installed"
have jq || die "wt-herdr: jq not installed"
have wt || die "wt-herdr: wt (worktrunk) not installed"
herdr_server_up || die "wt-herdr: herdr server not running"
local repo_name
repo_name=$(_wt_repo_name)
[[ -n "$repo_name" ]] || die "wt-herdr: not in a git repository"
export HERDR_SESSION="${HERDR_SESSION:-default}"
_ensure_session "$HERDR_SESSION" || die "wt-herdr: could not start session '$HERDR_SESSION'"
local mapped=() missing_in_herdr=() orphan_ws=()
# Collect all worktree branches
local wt_branches=()
while IFS= read -r b; do
[[ -n "$b" ]] && wt_branches+=("$b")
done <<< "$(_wt_list | jq -r '.[] | select(.kind == "worktree") | .branch')"
# For each worktree branch, find workspace via worktree metadata
local b
for b in "${wt_branches[@]}"; do
local ws_id ws_label wt_entry
wt_entry=$(herdr_worktree_list | jq -c --arg b "$b" '.result.worktrees[] | select(.branch == $b)')
if [[ -n "$wt_entry" ]]; then
ws_id=$(echo "$wt_entry" | jq -r '.open_workspace_id // ""')
ws_label=$(herdr_workspace_list | jq -r --arg wid "$ws_id" '.result.workspaces[] | select(.workspace_id == $wid) | .label // ""' | head -1)
mapped+=("{\"branch\":\"$b\",\"workspace_id\":\"$ws_id\",\"label\":\"$ws_label\",\"status\":\"mapped\"}")
else
missing_in_herdr+=("{\"branch\":\"$b\",\"status\":\"missing_in_herdr\"}")
fi
done
# Find orphan tracked worktrees (branch no longer in wt list)
while IFS= read -r wt; do
local branch is_linked ws_id ws_label
branch=$(echo "$wt" | jq -r '.branch // ""')
is_linked=$(echo "$wt" | jq -r '.is_linked_worktree // false')
ws_id=$(echo "$wt" | jq -r '.open_workspace_id // ""')
[[ "$is_linked" == "true" ]] || continue
local found=false
for b in "${wt_branches[@]}"; do
[[ "$b" == "$branch" ]] && { found=true; break; }
done
if ! $found; then
ws_label=$(herdr_workspace_list | jq -r --arg wid "$ws_id" '.result.workspaces[] | select(.workspace_id == $wid) | .label // ""' | head -1)
orphan_ws+=("{\"branch\":\"$branch\",\"workspace_id\":\"$ws_id\",\"label\":\"$ws_label\",\"status\":\"orphan\"}")
fi
done <<< "$(herdr_worktree_list | jq -c '.result.worktrees[]')"
# Build JSON output (guarded against bash3 nounset with empty arrays)
local json_out="{\"repo\":\"$repo_name\","
json_out+="\"worktree_count\":${#wt_branches[@]},"
json_out+="\"mapped\":["
local sep=""
if [[ ${#mapped[@]} -gt 0 ]]; then
for entry in "${mapped[@]}"; do json_out+="$sep$entry"; sep=","; done
fi
json_out+="],\"missing_in_herdr\":["
sep=""
if [[ ${#missing_in_herdr[@]} -gt 0 ]]; then
for entry in "${missing_in_herdr[@]}"; do json_out+="$sep$entry"; sep=","; done
fi
json_out+="],\"orphan_workspaces\":["
sep=""
if [[ ${#orphan_ws[@]} -gt 0 ]]; then
for entry in "${orphan_ws[@]}"; do json_out+="$sep$entry"; sep=","; done
fi
json_out+="]}"
json "$json_out"
}
# ── Subcommand: update-labels ─────────────────────────────────────────
cmd_update_labels() {
local dry_run=false
while [[ $# -gt 0 ]]; do
case "$1" in
--dry-run) dry_run=true ;;
*) err "wt-herdr update-labels: unknown option '$1'"; exit 2 ;;
esac
shift
done
have herdr || die "wt-herdr: herdr not installed"
have jq || die "wt-herdr: jq not installed"
have wt || die "wt-herdr: wt (worktrunk) not installed"
herdr_server_up || die "wt-herdr: herdr server not running"
local repo_name
repo_name=$(_wt_repo_name)
[[ -n "$repo_name" ]] || die "wt-herdr: not in a git repository"
export HERDR_SESSION="${HERDR_SESSION:-default}"
_ensure_session "$HERDR_SESSION" || die "wt-herdr: could not start session '$HERDR_SESSION'"
local updated=0 skipped=0 errors=0
while IFS= read -r wt; do
[[ -n "$wt" ]] || continue
local branch path symbols label ws_id current_label
branch=$(echo "$wt" | jq -r '.branch // "detached"')
path=$(echo "$wt" | jq -r '.path // ""')
symbols=$(echo "$wt" | jq -r '.symbols // ""')
label=$(_make_label "$repo_name" "$branch" "$symbols")
ws_id=$(herdr_wt_find_ws_by_branch "$repo_name" "$branch")
[[ -z "$ws_id" ]] && { skipped=$((skipped+1)); continue; }
current_label=$(herdr_workspace_list | jq -r --arg wid "$ws_id" '.result.workspaces[] | select(.workspace_id == $wid) | .label // ""' | head -1)
if [[ "$current_label" != "$label" ]]; then
if $dry_run; then
skipped=$((skipped+1))
else
herdr_ws_rename "$ws_id" "$label" && updated=$((updated+1)) || errors=$((errors+1))
fi
else
skipped=$((skipped+1))
fi
done <<< "$(_wt_worktrees)"
json "{
\"status\": \"ok\",
\"repo\": \"$repo_name\",
\"updated\": $updated,
\"skipped\": $skipped,
\"errors\": $errors
}"
}
# ── Subcommand: event (lifecycle handler for hooks) ───────────────────
cmd_event() {
local event_type="${1:-}"
[[ -n "$event_type" ]] || die "wt-herdr event: usage: event <type>"
have herdr || die "wt-herdr: herdr not installed"
have jq || die "wt-herdr: jq not installed"
have wt || die "wt-herdr: wt (worktrunk) not installed"
# Read JSON context from stdin (worktrunk hooks pass template variables as JSON)
local ctx
ctx=$(cat)
# Extract context variables (falling back to runtime detection)
local branch path repo_name
branch=$(echo "$ctx" | jq -r '.branch // empty' 2>/dev/null)
path=$(echo "$ctx" | jq -r '.worktree_path // empty' 2>/dev/null)
# If context is missing fields, fall back to current state
[[ -n "$branch" ]] || branch=$(_wt_current_branch)
[[ -n "$path" ]] || path=$(_wt_worktree_for_branch "$branch")
repo_name=$(_wt_repo_name)
export HERDR_SESSION="${HERDR_SESSION:-default}"
_ensure_session "$HERDR_SESSION" || die "wt-herdr: could not start session '$HERDR_SESSION'"
[[ -n "$branch" ]] || die "wt-herdr event: could not determine branch"
[[ -n "$repo_name" ]] || die "wt-herdr event: could not determine repo"
case "$event_type" in
worktree-created)
local symbols label ws_id
symbols=$(_wt_symbols "$branch")
label=$(_make_label "$repo_name" "$branch" "$symbols")
ws_id=$(herdr_wt_find_ws_by_branch "$repo_name" "$branch")
if [[ -z "$ws_id" ]]; then
ws_id=$(herdr_wt_open_or_create "$path" "$label" "$branch" "$repo_name") || die "wt-herdr event: could not create workspace for '$branch'"
herdr_tab_create "$ws_id" "$path" "$branch"
herdr_notify "wt-herdr: created" "$branch" "done"
json "{\"status\":\"ok\",\"action\":\"created\",\"branch\":\"$branch\",\"workspace_id\":\"$ws_id\"}"
else
json "{\"status\":\"ok\",\"action\":\"already_exists\",\"branch\":\"$branch\",\"workspace_id\":\"$ws_id\"}"
fi
;;
worktree-removed)
local ws_id
ws_id=$(herdr_wt_find_ws_by_branch "$repo_name" "$branch")
if [[ -n "$ws_id" ]]; then
herdr_wt_remove_ws "$ws_id"
herdr_notify "wt-herdr: removed" "$branch" "none"
json "{\"status\":\"ok\",\"action\":\"closed\",\"branch\":\"$branch\",\"workspace_id\":\"$ws_id\"}"
else
json "{\"status\":\"noop\",\"action\":\"not_found\",\"branch\":\"$branch\"}"
fi
;;
worktree-switched)
local ws_id symbols label
symbols=$(_wt_symbols "$branch")
label=$(_make_label "$repo_name" "$branch" "$symbols")
ws_id=$(herdr_wt_find_ws_by_branch "$repo_name" "$branch")
if [[ -n "$ws_id" ]]; then
herdr_ws_rename "$ws_id" "$label"
herdr_ws_focus "$ws_id"
json "{\"status\":\"ok\",\"action\":\"focused\",\"branch\":\"$branch\",\"workspace_id\":\"$ws_id\"}"
else
ws_id=$(herdr_wt_open_or_create "$path" "$label" "$branch" "$repo_name") || die "wt-herdr event: could not create workspace for '$branch'"
herdr_tab_create "$ws_id" "$path" "$branch"
herdr_ws_focus "$ws_id"
herdr_notify "wt-herdr: created & focused" "$branch" "done"
json "{\"status\":\"ok\",\"action\":\"created_and_focused\",\"branch\":\"$branch\",\"workspace_id\":\"$ws_id\"}"
fi
;;
*)
die "wt-herdr event: unknown event type '$event_type' (valid: worktree-created, worktree-removed, worktree-switched)"
;;
esac
}
# ── Subcommand: init ─────────────────────────────────────────────────
cmd_init() {
have herdr || die "wt-herdr: herdr not installed"
have jq || die "wt-herdr: jq not installed"
have wt || die "wt-herdr: wt (worktrunk) not installed"
local repo_root
repo_root=$(git rev-parse --show-toplevel 2>/dev/null) || die "wt-herdr init: not in a git repository"
local config_dir="$repo_root/.config"
local config_file="$config_dir/wt.toml"
if [[ -f "$config_file" ]]; then
err "wt-herdr init: $config_file already exists"
err "Back it up or remove it first, or add hooks manually (see README)."
exit 1
fi
mkdir -p "$config_dir"
cat > "$config_file" << 'TOML'
# Worktrunk hooks — auto-sync worktrees with herdr workspaces
# Generated by `wt herdr init`
# See: https://github.com/mattarau/wt-herdr
# On new worktree creation: create a herdr workspace
[post-start]
herdr = "wt herdr event worktree-created"
# On worktree removal: close the matching herdr workspace
[post-remove]
herdr = "wt herdr event worktree-removed"
# On worktree switch: focus the matching herdr workspace
[post-switch]
herdr = "wt herdr event worktree-switched"
TOML
echo "Created $config_file"
# Also try to link wt-herdr into PATH if not already there
if ! have wt-herdr; then
local install_dir="${INSTALL_DIR:-/usr/local/bin}"
if [[ -d "$install_dir" ]]; then
local symlink_target="$install_dir/wt-herdr"
if [[ ! -f "$symlink_target" ]]; then
if ln -sf "$SELF_DIR/wt-herdr" "$symlink_target" 2>/dev/null; then
echo "Linked $symlink_target → $SELF_DIR/wt-herdr"
else
err "Warning: could not symlink to $install_dir (permission denied)"
err "Add $SELF_DIR to your PATH or run: sudo ln -sf $SELF_DIR/wt-herdr $install_dir/"
fi
fi
fi
fi
# Approve the hooks so they run without prompting
echo "Setting up hooks... (may prompt for approval)"
wt hook pre-start --yes 2>/dev/null || true
wt hook post-start --yes 2>/dev/null || true
wt hook pre-remove --yes 2>/dev/null || true
wt hook post-remove --yes 2>/dev/null || true
wt hook pre-switch --yes 2>/dev/null || true
wt hook post-switch --yes 2>/dev/null || true
# Run initial sync
echo "Running initial sync..."
cmd_sync
}
# ── Main dispatch ─────────────────────────────────────────────────────
main() {
# Support --session flag before subcommand
# IMPORTANT: never export HERDR_SESSION as empty string — herdr rejects it.
local session="${HERDR_SESSION:-}"
while [[ $# -gt 0 ]] && [[ "$1" == --session ]]; do
session="$2"
shift 2
done
if [[ -n "$session" ]]; then
export HERDR_SESSION="$session"
else
unset HERDR_SESSION
fi
case "${1:-}" in
manifest) cmd_manifest ;;
health) cmd_health ;;
sync) shift; cmd_sync "$@" ;;
clean) shift; cmd_clean "$@" ;;
focus) cmd_focus ;;
status) cmd_status ;;
update-labels) shift; cmd_update_labels "$@" ;;
event) shift; cmd_event "$@" ;;
init) cmd_init ;;
-h|--help|help|"")
cat <<'HELP'
wt-herdr — worktrunk ↔ herdr bridge
USAGE:
wt herdr <subcommand> [options]
SUBCOMMANDS:
manifest Print plugin manifest JSON
health Check dependencies (herdr, jq, wt) and server status
sync [--dry-run] Sync all worktrees as herdr workspaces
clean [--dry-run] Close herdr workspaces for deleted worktrees
focus Focus herdr workspace for current worktree
status Show mapping between worktrees and herdr workspaces
update-labels [--dry-run] Refresh status badges in workspace labels
event <type> Handle lifecycle event (read JSON context from stdin)
Types: worktree-created, worktree-removed, worktree-switched
init Set up hooks config + initial sync
GLOBAL OPTIONS:
--session <name> Target a specific herdr session (default: auto-detected from repo name)
EXAMPLES:
wt herdr sync # Sync all worktrees
wt herdr sync --dry-run # Preview without changes
wt herdr clean --dry-run # Preview cleanup
wt herdr focus # Focus current workspace
wt herdr status # Show sync mapping
wt herdr --session work sync # Target a specific session
wt herdr init # Set up hooks + sync
SOURCE: https://github.com/mattarau/wt-herdr
HELP
;;
*)
die "wt-herdr: unknown subcommand '$1'. Run 'wt herdr help' for usage."
;;
esac
}
main "$@"