forked from garrytan/gstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup
More file actions
executable file
·2989 lines (2833 loc) · 144 KB
/
Copy pathsetup
File metadata and controls
executable file
·2989 lines (2833 loc) · 144 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# gstack setup — build browser binary + register skills with Claude Code / Codex
set -e
umask 077 # Restrict new files to owner-only (0o600 files, 0o700 dirs)
# Heredoc delivery guard. bash 5.2+ writes a heredoc body <=64KiB through a
# pipe in the forked child before exec, with no reader on the other end. On
# macOS under pipe-KVA pressure a fresh pipe gets a 512-byte buffer, so any
# body >=512B blocks write() forever — ./setup --help would hang with no
# output. Compat level 50 restores the tempfile path. This script is
# bash-3.2-clean, so the compat level costs it nothing. Not exported: the
# guard is per-script, and it survives `bash setup` call sites that bypass
# the shebang.
BASH_COMPAT=50
usage() {
cat <<'EOF'
gstack setup — install gstack skills + build browse binary
Usage: ./setup [options]
Options:
--host <name> Install for a specific host (claude, codex, kiro, factory,
opencode, openclaw, hermes, gbrain, auto). Default: claude.
--model <id> Codex model profile override. Otherwise reads Codex config.
--prefix Install skills with the gstack- prefix (e.g. /gstack-review).
--no-prefix Install skills with short names (e.g. /review). Default.
--team Switch to team mode (per-repo gstack with auto-update).
--no-team Force solo install even if a team-mode repo is detected.
-q, --quiet Suppress progress output.
-h, --help Show this help and exit.
Examples:
./setup # solo install for Claude Code
./setup --host codex # install for OpenAI Codex CLI
./setup --host codex --model gpt-5.6-sol
./setup --team # team mode for a shared repo
./setup --no-prefix # use short slash-command names
Docs: https://github.com/garrytan/gstack
EOF
}
# Short-circuit on -h/--help before any environment checks so users can
# discover flags even without bun installed.
for _arg in "$@"; do
case "$_arg" in
-h|--help) usage; exit 0 ;;
esac
done
if ! command -v bun >/dev/null 2>&1; then
echo "Error: bun is required but not installed." >&2
echo "Install with checksum verification:" >&2
echo ' BUN_VERSION="1.3.10"' >&2
echo ' tmpfile=$(mktemp)' >&2
echo ' curl -fsSL "https://bun.sh/install" -o "$tmpfile"' >&2
echo ' echo "Verify checksum before running: sha256sum $tmpfile # or: shasum -a 256 $tmpfile"' >&2
echo ' BUN_VERSION="$BUN_VERSION" bash "$tmpfile" && rm "$tmpfile"' >&2
exit 1
fi
INSTALL_GSTACK_DIR="$(cd "$(dirname "$0")" && pwd)"
SOURCE_GSTACK_DIR="$(cd "$(dirname "$0")" && pwd -P)"
INSTALL_SKILLS_DIR="$(dirname "$INSTALL_GSTACK_DIR")"
BROWSE_BIN="$SOURCE_GSTACK_DIR/browse/dist/browse"
CODEX_SKILLS="${CODEX_HOME:-$HOME/.codex}/skills"
CODEX_GSTACK="$CODEX_SKILLS/gstack"
FACTORY_SKILLS="$HOME/.factory/skills"
FACTORY_GSTACK="$FACTORY_SKILLS/gstack"
OPENCODE_SKILLS="$HOME/.config/opencode/skills"
OPENCODE_GSTACK="$OPENCODE_SKILLS/gstack"
CURSOR_SKILLS="$HOME/.cursor/skills"
CURSOR_GSTACK="$CURSOR_SKILLS/gstack"
IS_WINDOWS=0
case "$(uname -s)" in
MINGW*|MSYS*|CYGWIN*|Windows_NT) IS_WINDOWS=1 ;;
esac
# Windows: binaries are compiled with .exe suffix
if [ "$IS_WINDOWS" -eq 1 ]; then
BROWSE_BIN="$SOURCE_GSTACK_DIR/browse/dist/browse.exe"
fi
# ─── Symlink-or-copy helper ───────────────────────────────────
# On macOS/Linux: create a symlink (existing behavior).
# On Windows without Developer Mode (MSYS2/Git Bash): plain ln -snf silently
# creates a frozen file copy that doesn't refresh after `git pull`. We use
# explicit `cp -R` / `cp -f` so the user gets a real copy and the staleness
# is reportable (re-run ./setup after pull). Auto-detects file vs dir.
#
# INVARIANT: every symlink in this script MUST route through this helper.
# A raw ln call here will be caught by test/setup-windows-fallback.test.ts
# (the static-invariant assertion D7).
_link_or_copy() {
local src="$1"
local dst="$2"
if [ "$IS_WINDOWS" -eq 1 ]; then
rm -rf "$dst"
# Unix `ln -snf` accepts a name-only or relative-path source even when the
# target doesn't resolve from CWD (e.g. the connect-chrome alias points at
# the sibling-relative "gstack/open-gstack-browser"). On Windows the
# equivalent semantics don't exist — we'd need a real source on disk to
# copy. Skip the alias quietly rather than aborting setup under `set -e`.
if [ ! -e "$src" ]; then
return 0
fi
if [ -d "$src" ]; then
cp -R "$src" "$dst"
else
cp -f "$src" "$dst"
fi
else
ln -snf "$src" "$dst"
fi
}
# ─── Ownership gate for skill entries (#2119) ─────────────────────────────────
# setup and gstack-relink must never delete or link over a skill they do not
# own. This is the single rule both use (relink carries the same logic — keep
# them in sync until the shared helper filed in TODOS.md lands). Proof has two
# strengths: STRONG (a symlink resolving into gstack, or the .gstack-owned
# marker) means we created the entry and may delete or refresh it whole; WEAK
# (byte-identity with our source, or the two-line generated banner on a real
# file) covers only that SKILL.md — never the directory — and a differing
# weakly-proven file is moved to ${GSTACK_HOME:-~/.gstack}/backups/skills/<ts>/
# before we install over it. An entry is OURS
# when: it is a symlink resolving into the gstack payload / render dir (or any
# path with a `gstack` segment, the convention cleanup and gstack-uninstall
# already use, so entries from a sibling worktree still count), a real dir
# whose SKILL.md is such a symlink, or a real-file copy proven by the
# .gstack-owned marker, byte-identity with the source, or gen-skill-docs'
# generated header. Anything else is FOREIGN: skipped, reported, listed in
# the final summary.
_FOREIGN_SKIPPED_ENTRIES=()
_gstack_link_target_abs() {
# readlink of a relative link is relative to the link's directory; anchor it
# there and canonicalize the directory part (`..`, symlinked components).
local link="$1" dest d b d_real
dest="$(readlink "$link" 2>/dev/null || true)"
[ -n "$dest" ] || return 1
case "$dest" in /*) ;; *) dest="$(dirname "$link")/$dest" ;; esac
d="${dest%/*}"; b="${dest##*/}"
if d_real="$(cd "$d" 2>/dev/null && pwd -P)"; then printf '%s\n' "$d_real/$b"; else printf '%s\n' "$dest"; fi
}
_gstack_target_is_ours() {
# $1 = absolute target path, $2 = gstack payload dir
local t="$1" g="$2" g_real render render_real
g_real="$(cd "$g" 2>/dev/null && pwd -P || printf '%s' "$g")"
render="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}"
render_real="$(cd "$render" 2>/dev/null && pwd -P || printf '%s' "$render")"
case "$t" in
"$g"/*|"$g_real"/*|"$render"/*|"$render_real"/*|gstack/*|*/gstack/*|*/.gstack/render/claude/*) return 0 ;;
esac
# A checkout named without a `gstack` segment (git worktree add
# ../gstack-<branch>, a ZIP unpacked as gstack-main): the target's skill
# root is a gstack tree if it carries setup + VERSION + bin/gstack-relink
# (a hand-written skill repo with a VERSION file and a setup script does not).
local root="${t%/*/SKILL.md}"
if [ "$root" != "$t" ] && [ -f "$root/VERSION" ] && [ -f "$root/setup" ] && [ -f "$root/bin/gstack-relink" ]; then return 0; fi
return 1
}
_claude_entry_is_ours() {
# $1 = existing entry (dir or symlink), $2 = the gstack source SKILL.md it
# would be linked to, $3 = gstack payload dir
local entry="$1" src_md="$2" g="$3" render_md
_claude_entry_owned_strongly "$entry" "$g" && return 0
# A symlink that did not resolve into gstack is someone else's; never follow
# it into the "unclaimed directory" rule below.
[ -L "$entry" ] && return 1
# No SKILL.md at all: an UNCLAIMED directory (a weak cleanup left the user's
# other files behind, or it was never a skill). Adding our SKILL.md
# overwrites nothing, so installing into it is allowed; the cleanup arms
# require a SKILL.md and so never touch it.
if [ -d "$entry" ] && [ ! -e "$entry/SKILL.md" ] && [ ! -L "$entry/SKILL.md" ]; then return 0; fi
if [ -d "$entry" ] && [ -f "$entry/SKILL.md" ] && [ ! -L "$entry/SKILL.md" ]; then
[ -n "$src_md" ] && [ -f "$src_md" ] && cmp -s "$entry/SKILL.md" "$src_md" && return 0
# A gbrain install serves the RENDERED file (link_claude_skill_dirs prefers
# it), so an exact copy of that render is ours too.
if [ -n "$src_md" ]; then
render_md="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}/$(basename "$(dirname "$src_md")")/SKILL.md"
[ -f "$render_md" ] && cmp -s "$entry/SKILL.md" "$render_md" && return 0
fi
_gstack_generated_header "$entry/SKILL.md" && return 0
fi
return 1
}
# _claude_entry_owned_strongly ENTRY GSTACK_DIR — we created it: a symlink into
# gstack, or a real dir with the .gstack-owned marker or a SKILL.md symlink
# into gstack. Only strong proof authorizes deleting a directory whole.
_claude_entry_owned_strongly() {
local entry="$1" g="$2" dest
if [ -L "$entry" ]; then
dest="$(_gstack_link_target_abs "$entry")" || return 1
_gstack_target_is_ours "$dest" "$g"; return $?
fi
[ -d "$entry" ] || return 1
[ -f "$entry/.gstack-owned" ] && return 0
if [ -L "$entry/SKILL.md" ]; then
dest="$(_gstack_link_target_abs "$entry/SKILL.md")" || return 1
_gstack_target_is_ours "$dest" "$g"; return $?
fi
return 1
}
# Weakly-proven real files we would otherwise overwrite are moved here (mv, so
# the path is free for the link); the final summary prints one line.
_SKILL_BACKUP_ROOT="${GSTACK_HOME:-$HOME/.gstack}/backups/skills/$(date +%Y%m%dT%H%M%S)"
_BACKED_UP_SKILL_MDS=()
_backup_skill_md() {
# Returns non-zero when the file could NOT be moved: the caller must then
# leave the entry untouched (a failed backup is never a license to overwrite).
local file="$1" name="$2"
mkdir -p "$_SKILL_BACKUP_ROOT/$name" 2>/dev/null || return 1
mv -f "$file" "$_SKILL_BACKUP_ROOT/$name/SKILL.md" 2>/dev/null || return 1
_BACKED_UP_SKILL_MDS+=("$name")
return 0
}
# _cleanup_weak_dir DIR — remove only what weak proof covers: the SKILL.md and
# our marker. User files in the directory stay, and so does the directory
# when it is not empty afterwards.
# _cleanup_weak_dir DIR GSTACK_DIR [SRC_SKILL_MD NAME] — remove only what weak
# proof covers. A real SKILL.md that differs from our source (raw, or with its
# name: line rewritten to NAME, which is how alias and prefixed copies differ)
# is a customized file: it is moved to the backup root, never deleted, and if
# the backup fails it stays. Our runtime-asset links go; the user's files stay.
_cleanup_weak_dir() {
local d="$1" g="$2" src="${3:-}" name="${4:-${1##*/}}" e dest
if [ -f "$d/SKILL.md" ] && [ ! -L "$d/SKILL.md" ] && [ -n "$src" ] && [ -f "$src" ] \
&& ! cmp -s "$d/SKILL.md" "$src" \
&& ! sed "1,/^---\$/ s/^name:[[:space:]].*/name: $name/" "$src" | cmp -s - "$d/SKILL.md"; then
if ! _backup_skill_md "$d/SKILL.md" "$name"; then
echo " kept $name/SKILL.md: could not back up the customized file — left untouched" >&2
return 0
fi
else
rm -f "$d/SKILL.md"
fi
rm -f "$d/.gstack-owned"
for e in "$d"/* "$d"/.[!.]* "$d"/..?*; do
[ -L "$e" ] || continue
dest="$(_gstack_link_target_abs "$e")" || continue
if _gstack_target_is_ours "$dest" "$g"; then rm -f "$e"; fi
done
rmdir "$d" 2>/dev/null || echo " cleaned ${d##*/}/SKILL.md (other files in that directory were left in place)"
}
# _gstack_dir_only_links DIR GSTACK_DIR — true when deleting DIR whole loses
# nothing of the user's: every entry is a symlink resolving into gstack, or
# our marker. A user's own link (notes.md -> ~/notes) makes the dir mixed.
_gstack_dir_only_links() {
local d="$1" g="$2" e dest
for e in "$d"/* "$d"/.[!.]* "$d"/..?*; do
{ [ -e "$e" ] || [ -L "$e" ]; } || continue
[ "${e##*/}" = ".gstack-owned" ] && continue
[ -L "$e" ] || return 1
dest="$(_gstack_link_target_abs "$e")" || return 1
_gstack_target_is_ours "$dest" "$g" || return 1
done
return 0
}
# _cleanup_linked_dir DIR GSTACK_DIR — a real dir whose SKILL.md is a symlink
# into gstack. Whole-directory removal needs the marker (we created it) or a
# directory holding nothing but our links; otherwise only our files go.
_cleanup_linked_dir() {
if [ -f "$1/.gstack-owned" ] || _gstack_dir_only_links "$1" "$2"; then rm -rf "$1"; else _cleanup_weak_dir "$1" "$2"; fi
}
# _gstack_generated_header FILE — a pre-marker legacy COPY (Windows, before
# .gstack-owned existed) is recognized by gen-skill-docs' full two-line banner
# near the top, not by a one-line substring another generator could plausibly
# emit. Still forgeable by a gstack fork that renders the same banner — that
# residual is accepted and filed; the marker is the load-bearing signal.
_gstack_generated_header() {
# Bytes, not lines: a long frontmatter pushes the banner past line 40 in
# four real skills (investigate: line 57), and a line-count check left them
# "foreign" on every pre-marker Windows install.
local f="$1" head40
head40="$(head -c 8192 "$f" 2>/dev/null)" || return 1
case "$head40" in
*'<!-- AUTO-GENERATED from '*'<!-- Regenerate: bun run gen:skill-docs -->'*) return 0 ;;
esac
return 1
}
_write_owned_marker() {
# Windows copy installs have no symlink to readlink; the marker proves
# provenance. Records the owning payload's real path for forensics.
local dir="$1" g="$2"
printf '%s\n' "$(cd "$g" 2>/dev/null && pwd -P || printf '%s' "$g")" > "$dir/.gstack-owned" 2>/dev/null || true
}
# ─── Ownership gates for the Windows refresh bypass (#2444 → #2142) ─────────
# On Windows a refresh means rm -rf + re-copy (_link_or_copy). The host
# skills dirs are SHARED namespaces (~/.codex/skills, ~/.factory/skills,
# ~/.cursor/skills, ...), so a gstack* glob name can collide with a user's
# OWN real directory (e.g. ~/.cursor/skills/gstack-notes) — deleting it on
# every ./setup re-run is silent data loss. Mirror of bin/gstack-uninstall's
# provenance gate (#2563): an existing REAL skill dir may only be replaced
# when its SKILL.md carries the generated banner. Missing targets and
# symlinks always pass (replacing a link never destroys content); non-dir
# targets pass (file targets live inside gstack-owned roots).
_owned_for_windows_refresh() {
local dst="$1"
if [ ! -e "$dst" ] && [ ! -L "$dst" ]; then return 0; fi
if [ -L "$dst" ]; then return 0; fi
if [ ! -d "$dst" ]; then return 0; fi
grep -q '<!-- AUTO-GENERATED from' "$dst/SKILL.md" 2>/dev/null
}
# A sidecar/runtime ROOT (…/skills/gstack) is provably USER-owned when it is
# a real dir whose SKILL.md exists but lacks the generated banner — a
# hand-written skill squatting on the canonical name. The sidecar installers
# skip it entirely rather than write into (or wipe) someone else's skill.
# A root with NO SKILL.md stays presumed ours: it is the documented gstack
# install location and old/partial installs legitimately look like that.
_sidecar_root_user_owned() {
local root="$1"
[ -d "$root" ] || return 1
[ -L "$root" ] && return 1
[ -f "$root/SKILL.md" ] || return 1
! grep -q '<!-- AUTO-GENERATED from' "$root/SKILL.md" 2>/dev/null
}
# Swap a freshly-rendered tmp dir into the live render location (#2569
# hardening). Installed skills SYMLINK into the live dir, so it is only ever
# replaced AFTER a successful render — a failed render leaves the previous
# render (and every link into it) fully intact. Keep in sync with
# bin/gstack-config's _swap_in_render (same contract, both pinned by
# test/user-render-out-dir-install.test.ts).
_swap_in_render() {
local render_dir="$1" render_tmp="$2"
local render_old="$render_dir.old.$$"
rm -rf "$render_old"
if [ -e "$render_dir" ] || [ -L "$render_dir" ]; then mv "$render_dir" "$render_old"; fi
mv "$render_tmp" "$render_dir"
rm -rf "$render_old"
}
_WINDOWS_COPY_NOTE_PRINTED=0
_print_windows_copy_note_once() {
if [ "$IS_WINDOWS" -eq 1 ] && [ "$_WINDOWS_COPY_NOTE_PRINTED" -eq 0 ]; then
echo " note: Windows install uses file copies (no Developer Mode required). Re-run ./setup after every 'git pull' to refresh skill files."
_WINDOWS_COPY_NOTE_PRINTED=1
fi
}
# ─── Quiet mode helper ────────────────────────────────────────
QUIET=0
log() { [ "$QUIET" -eq 0 ] && echo "$@" || true; }
# ─── Parse flags ──────────────────────────────────────────────
HOST="claude"
LOCAL_INSTALL=0
SKILL_PREFIX=1
SKILL_PREFIX_FLAG=0
TEAM_MODE=0
NO_TEAM_MODE=0
PLAN_TUNE_HOOKS_MODE="" # "" = resolve from env/config/prompt; "yes"/"no" = explicit
TIMELINE_STOP_HOOK_MODE="" # "" = resolve from env/config; "yes"/"no" = explicit (#2677)
MODEL_OVERRIDE=""
MODEL_OVERRIDE_SET=0
while [ $# -gt 0 ]; do
case "$1" in
--host) [ -z "$2" ] && echo "Missing value for --host (expected claude, codex, kiro, factory, opencode, cursor, slate, openclaw, hermes, gbrain, or auto)" >&2 && exit 1; HOST="$2"; shift 2 ;;
--host=*) HOST="${1#--host=}"; shift ;;
--model) [ -z "$2" ] && echo "Missing value for --model" >&2 && exit 1; MODEL_OVERRIDE="$2"; MODEL_OVERRIDE_SET=1; shift 2 ;;
--model=*) MODEL_OVERRIDE="${1#--model=}"; MODEL_OVERRIDE_SET=1; shift ;;
--local) LOCAL_INSTALL=1; shift ;;
--prefix) SKILL_PREFIX=1; SKILL_PREFIX_FLAG=1; shift ;;
--no-prefix) SKILL_PREFIX=0; SKILL_PREFIX_FLAG=1; shift ;;
--team) TEAM_MODE=1; shift ;;
--no-team) NO_TEAM_MODE=1; shift ;;
--plan-tune-hooks) PLAN_TUNE_HOOKS_MODE="yes"; shift ;;
--no-plan-tune-hooks) PLAN_TUNE_HOOKS_MODE="no"; shift ;;
--plan-tune-hooks=*) PLAN_TUNE_HOOKS_MODE="${1#--plan-tune-hooks=}"; shift ;;
--timeline-stop-hook) TIMELINE_STOP_HOOK_MODE="yes"; shift ;;
--no-timeline-stop-hook) TIMELINE_STOP_HOOK_MODE="no"; shift ;;
--timeline-stop-hook=*) TIMELINE_STOP_HOOK_MODE="${1#--timeline-stop-hook=}"; shift ;;
-q|--quiet) QUIET=1; shift ;;
*) shift ;;
esac
done
# Shared by the instruction-tier explainer arms (openclaw, hermes). The digest
# path is anchored to the script's own directory — $(pwd) would print a
# nonexistent path when setup is invoked from anywhere else.
print_instruction_tier() {
echo ""
echo "Instruction-only tier (no install): copy the 2KB rules digest into a"
echo "location your agent reads (e.g. append to your project's AGENTS.md)."
echo "It carries gstack's ethos, reuse ladder, and voice rules:"
echo ""
echo " $SOURCE_GSTACK_DIR/agents-digest/gstack-AGENTS.md"
echo ""
echo "Re-copy it after upgrading gstack — the digest's first line shows its version."
echo ""
}
case "$HOST" in
claude|codex|kiro|factory|opencode|cursor|auto) ;;
slate)
echo ""
echo "Slate is not yet a first-class install target (docs/designs/SLATE_HOST.md —"
echo "blocked on the host-config refactor). Slate discovers skills from"
echo ".claude/skills as a compatibility fallback, so a Slate user is served by"
echo "the Claude install today:"
echo ""
echo " ./setup --host claude"
echo ""
exit 0 ;;
openclaw)
echo ""
echo "OpenClaw integration uses a different model — OpenClaw spawns Claude Code"
echo "sessions natively via ACP. gstack provides methodology artifacts, not a"
echo "full skill installation."
echo ""
echo "To integrate gstack with OpenClaw:"
echo " 1. Tell your OpenClaw agent: 'install gstack for openclaw'"
echo " 2. Or generate artifacts: bun run gen:skill-docs --host openclaw"
echo " 3. See docs/OPENCLAW.md for the full architecture"
print_instruction_tier
exit 0 ;;
hermes)
echo ""
echo "Hermes integration uses the same model as OpenClaw — Hermes spawns"
echo "Claude Code sessions, and gstack provides methodology artifacts."
echo ""
echo "To integrate gstack with Hermes:"
echo " 1. Tell your Hermes agent: 'install gstack for hermes'"
echo " 2. Or generate artifacts: bun run gen:skill-docs --host hermes"
print_instruction_tier
exit 0 ;;
gbrain)
echo ""
echo "GBrain is a mod for gstack — it makes coding skills brain-aware."
echo "GBrain generates brain-enhanced skill variants that search your brain"
echo "for context before starting and save results after finishing."
echo ""
echo "To generate brain-aware skills:"
echo " bun run gen:skill-docs --host gbrain"
echo ""
echo "GBrain setup and brain skills ship from the GBrain repo."
echo ""
exit 0 ;;
*) echo "Unknown --host value: $HOST (expected claude, codex, kiro, factory, opencode, cursor, slate, openclaw, hermes, gbrain, or auto)" >&2; exit 1 ;;
esac
# ─── Resolve skill prefix preference ─────────────────────────
# Priority: CLI flag > saved config > interactive prompt (or flat default for non-TTY)
GSTACK_CONFIG="$SOURCE_GSTACK_DIR/bin/gstack-config"
export GSTACK_SETUP_RUNNING=1 # Prevent gstack-config post-set hook from triggering relink mid-setup
if [ "$SKILL_PREFIX_FLAG" -eq 0 ]; then
_saved_prefix="$("$GSTACK_CONFIG" get skill_prefix 2>/dev/null || true)"
if [ "$_saved_prefix" = "true" ]; then
SKILL_PREFIX=1
elif [ "$_saved_prefix" = "false" ]; then
SKILL_PREFIX=0
else
# No saved preference — prompt interactively (or default flat for non-TTY/quiet)
if [ "$QUIET" -eq 1 ]; then
SKILL_PREFIX=0
elif [ -t 0 ]; then
echo ""
echo "Skill naming: how should gstack skills appear?"
echo ""
echo " 1) Short names: /qa, /ship, /review"
echo " Recommended. Clean and fast to type."
echo ""
echo " 2) Namespaced: /gstack-qa, /gstack-ship, /gstack-review"
echo " Use this if you run other skill packs alongside gstack to avoid conflicts."
echo ""
printf "Choice [1/2] (default: 1, auto-selects in 10s): "
read -t 10 -r _prefix_choice </dev/tty 2>/dev/null || _prefix_choice=""
case "$_prefix_choice" in
2) SKILL_PREFIX=1 ;;
*) SKILL_PREFIX=0 ;;
esac
else
SKILL_PREFIX=0
fi
# Save the choice for future runs
"$GSTACK_CONFIG" set skill_prefix "$([ "$SKILL_PREFIX" -eq 1 ] && echo true || echo false)" 2>/dev/null || true
fi
else
# Flag was passed explicitly — persist the choice
"$GSTACK_CONFIG" set skill_prefix "$([ "$SKILL_PREFIX" -eq 1 ] && echo true || echo false)" 2>/dev/null || true
fi
# --local: install to .claude/skills/ in the current working directory (deprecated)
if [ "$LOCAL_INSTALL" -eq 1 ]; then
echo "Warning: --local is deprecated. Use global install + --team instead." >&2
echo " See: https://github.com/garrytan/gstack#team-mode" >&2
if [ "$HOST" = "codex" ]; then
echo "Error: --local is only supported for Claude Code (not Codex)." >&2
exit 1
fi
INSTALL_SKILLS_DIR="$(pwd)/.claude/skills"
mkdir -p "$INSTALL_SKILLS_DIR"
HOST="claude"
INSTALL_CODEX=0
fi
# For auto: detect which agents are installed
INSTALL_CLAUDE=0
INSTALL_CODEX=0
INSTALL_KIRO=0
INSTALL_FACTORY=0
INSTALL_OPENCODE=0
INSTALL_CURSOR=0
if [ "$HOST" = "auto" ]; then
command -v claude >/dev/null 2>&1 && INSTALL_CLAUDE=1
command -v codex >/dev/null 2>&1 && INSTALL_CODEX=1
command -v kiro-cli >/dev/null 2>&1 && INSTALL_KIRO=1
command -v droid >/dev/null 2>&1 && INSTALL_FACTORY=1
command -v opencode >/dev/null 2>&1 && INSTALL_OPENCODE=1
# Cursor's `cursor` CLI shim isn't always on PATH; ~/.cursor is the
# reliable footprint of an installed Cursor IDE.
command -v cursor >/dev/null 2>&1 && INSTALL_CURSOR=1
[ -d "$HOME/.cursor" ] && INSTALL_CURSOR=1
# If none found, default to claude
if [ "$INSTALL_CLAUDE" -eq 0 ] && [ "$INSTALL_CODEX" -eq 0 ] && [ "$INSTALL_KIRO" -eq 0 ] && [ "$INSTALL_FACTORY" -eq 0 ] && [ "$INSTALL_OPENCODE" -eq 0 ] && [ "$INSTALL_CURSOR" -eq 0 ]; then
INSTALL_CLAUDE=1
fi
elif [ "$HOST" = "claude" ]; then
INSTALL_CLAUDE=1
elif [ "$HOST" = "codex" ]; then
INSTALL_CODEX=1
elif [ "$HOST" = "kiro" ]; then
INSTALL_KIRO=1
elif [ "$HOST" = "factory" ]; then
INSTALL_FACTORY=1
elif [ "$HOST" = "opencode" ]; then
INSTALL_OPENCODE=1
elif [ "$HOST" = "cursor" ]; then
INSTALL_CURSOR=1
fi
# A host that passes --host validation but sets no INSTALL_* flag would
# silently configure nothing and exit 0 (the #2361 slate failure class).
# Fail loudly if a future host lands in the accept-list without a dispatch arm.
if [ "$HOST" != "auto" ] && [ "$INSTALL_CLAUDE" -eq 0 ] && [ "$INSTALL_CODEX" -eq 0 ] && [ "$INSTALL_KIRO" -eq 0 ] && [ "$INSTALL_FACTORY" -eq 0 ] && [ "$INSTALL_OPENCODE" -eq 0 ] && [ "$INSTALL_CURSOR" -eq 0 ]; then
echo "Error: no install arm exists for host '$HOST' — it passed --host validation but sets no INSTALL_* flag, so setup would configure nothing and exit 0. This is a setup bug. Valid install targets: claude, codex, kiro, factory, opencode, cursor (informational: slate, openclaw, hermes, gbrain)." >&2
exit 1
fi
if [ "$MODEL_OVERRIDE_SET" -eq 1 ] && [ "$INSTALL_CODEX" -eq 0 ]; then
echo "Error: --model is supported only when Codex is selected (--host codex or --host auto with Codex installed)." >&2
exit 1
fi
migrate_direct_codex_install() {
local gstack_dir="$1"
local codex_gstack="$2"
local migrated_dir="$HOME/.gstack/repos/gstack"
[ "$gstack_dir" = "$codex_gstack" ] || return 0
[ -L "$gstack_dir" ] && return 0
mkdir -p "$(dirname "$migrated_dir")"
if [ -e "$migrated_dir" ] && [ "$migrated_dir" != "$gstack_dir" ]; then
echo "gstack setup failed: direct Codex install detected at $gstack_dir" >&2
echo "A migrated repo already exists at $migrated_dir; move one of them aside and rerun setup." >&2
exit 1
fi
log "Migrating direct Codex install to $migrated_dir to avoid duplicate skill discovery..."
mv "$gstack_dir" "$migrated_dir"
SOURCE_GSTACK_DIR="$migrated_dir"
INSTALL_GSTACK_DIR="$migrated_dir"
INSTALL_SKILLS_DIR="$(dirname "$INSTALL_GSTACK_DIR")"
BROWSE_BIN="$SOURCE_GSTACK_DIR/browse/dist/browse"
# Windows: binaries are compiled with .exe suffix (same as the top-level
# BROWSE_BIN assignment — this re-derivation must not drop the suffix).
if [ "$IS_WINDOWS" -eq 1 ]; then
BROWSE_BIN="$SOURCE_GSTACK_DIR/browse/dist/browse.exe"
fi
}
if [ "$INSTALL_CODEX" -eq 1 ]; then
migrate_direct_codex_install "$SOURCE_GSTACK_DIR" "$CODEX_GSTACK"
fi
# Kill an entire process tree rooted at $1, leaves first. Killing only the
# backgrounded subshell orphans the wedged node/bun -> Chromium probe
# processes underneath it — re-creating the #2136 stuck-process pile-up and
# potentially leaving Playwright cache locks held. macOS ships no setsid
# binary, so a portable group-kill isn't available; walk `pgrep -P` children
# depth-first instead (pgrep exists on macOS and Linux). Falls back to a
# plain kill of the root pid when pgrep is unavailable.
_kill_tree() {
local pid="$1" child
if command -v pgrep >/dev/null 2>&1; then
for child in $(pgrep -P "$pid" 2>/dev/null); do
_kill_tree "$child"
done
elif [ -d /proc ]; then
# debian-slim and git-bash ship no pgrep: walk /proc for children. The
# comm field "(name)" may contain spaces and parens, so strip through the
# LAST closing paren (proc(5)) before reading the ppid (second field after it).
for child in $(awk -v p="$pid" '{ s=$0; sub(/^.*\) /, "", s); split(s, f, " "); if (f[2]==p) print $1 }' /proc/[0-9]*/stat 2>/dev/null); do
_kill_tree "$child"
done
fi
kill -9 "$pid" 2>/dev/null || true
}
# Deadline-bounded wait for a background probe. macOS ships no GNU timeout;
# poll the PID and SIGKILL the whole probe tree past the deadline. Returns
# the probe's exit code, or 124 on timeout.
_wait_with_deadline() {
local pid="$1" deadline_s="$2" waited=0
while kill -0 "$pid" 2>/dev/null; do
if [ "$waited" -ge "$deadline_s" ]; then
_kill_tree "$pid"
wait "$pid" 2>/dev/null || true
return 124
fi
sleep 1
waited=$((waited + 1))
done
wait "$pid"
}
ensure_playwright_browser() {
# #2136: fresh installs hung forever at this probe (macOS arm64) and
# re-runs stacked stuck process trees, so skills never got linked. Two
# fixes: prefer Node for the launch probe everywhere it exists (the
# bun --eval launch is the same pipe-bug family already worked around on
# Windows), and bound the probe with a 90s deadline — a wedged probe now
# reports failure (which routes to the install path) instead of hanging
# setup.
local probe_cmd
if command -v node >/dev/null 2>&1; then
probe_cmd='node -e "const { chromium } = require((process.cwd()) + \"/node_modules/playwright\"); (async () => { const b = await chromium.launch(); await b.close(); })().then(() => process.exit(0), () => process.exit(1))"'
elif [ "$IS_WINDOWS" -eq 1 ]; then
echo "gstack setup failed: Node.js is required on Windows" >&2
return 1
else
probe_cmd="bun --eval 'import { chromium } from \"playwright\"; const browser = await chromium.launch(); await browser.close();'"
fi
(
cd "$SOURCE_GSTACK_DIR"
eval "$probe_cmd"
) >/dev/null 2>&1 &
_wait_with_deadline $! 90
}
# P0 #2554: a macOS XProtect definition update can start SIGKILLing the
# Chromium revision the lockfile pins, which surfaces here as a failed launch
# probe. Clear com.apple.quarantine on the Playwright cache bundles ONLY —
# never a GSTACK_CHROMIUM_PATH bundle (that belongs to the wrapper/embedder;
# same scope contract as browse's probePoisonedChromiumBundle) — so the
# reinstall below produces a launchable browser. Best-effort and macOS-only.
_clear_playwright_quarantine() {
[ "$(uname -s)" = "Darwin" ] || return 0
local cache_root="${PLAYWRIGHT_BROWSERS_PATH:-$HOME/Library/Caches/ms-playwright}"
[ -d "$cache_root" ] || return 0
local d
for d in "$cache_root"/chromium-* "$cache_root"/chromium_headless_shell-*; do
[ -d "$d" ] || continue
echo " clearing com.apple.quarantine on $(basename "$d") (XProtect self-heal, #2554)" >&2
xattr -dr com.apple.quarantine "$d" 2>/dev/null || true
done
}
# Ensure a color-emoji font is installed (Linux only).
#
# Chromium renders emoji code points as .notdef "tofu" (▯) when no color-emoji
# font is installed. macOS ships "Apple Color Emoji" and Windows ships "Segoe UI
# Emoji", so they're fine out of the box. Most Linux distros and containers ship
# NO color-emoji font, which is why make-pdf output shows tofu in headers/tables
# that contain emoji. Install Noto Color Emoji to fix it.
#
# Best-effort: warn (don't fail) if we can't install — PDFs still generate, they
# just fall back to tofu for emoji as before. Skip entirely with
# GSTACK_SKIP_FONTS=1 (CI without sudo, managed machines, offline envs).
#
# Returns 0 and sets EMOJI_FONT_INSTALLED=1 when it actually installs a font.
EMOJI_FONT_INSTALLED=0
ensure_emoji_font() {
# macOS/Windows ship a color-emoji font; nothing to do.
[ "$(uname -s)" = "Linux" ] || return 0
[ "${GSTACK_SKIP_FONTS:-0}" = "1" ] && return 0
# Idempotency: a real COLOR emoji font that resolves for an actual emoji code
# point (U+1F600). `fc-list :lang=und-zsye` is too broad — it matches symbol
# and last-resort fallback fonts — so we use fc-match and require color=True.
if command -v fc-match >/dev/null 2>&1; then
if fc-match -f '%{family[0]}\t%{color}\n' ':lang=und-zsye:charset=1F600' 2>/dev/null | grep -qi 'True'; then
return 0
fi
fi
local sudo=""
if [ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1; then
# -n: never prompt. If a password is required we fail fast into the
# warn-not-fail path below instead of hanging a non-interactive setup.
sudo="sudo -n"
fi
# Every package-manager call is wrapped in `timeout` so a stuck dpkg/rpm lock
# or a wedged mirror fails fast into the warn path instead of hanging setup.
if command -v apt-get >/dev/null 2>&1; then
echo "Installing color-emoji font (fonts-noto-color-emoji) so make-pdf emoji render (set GSTACK_SKIP_FONTS=1 to skip)..."
DEBIAN_FRONTEND=noninteractive timeout 30 $sudo apt-get update -qq >/dev/null 2>&1 || true
DEBIAN_FRONTEND=noninteractive timeout 120 $sudo apt-get install -y -qq fonts-noto-color-emoji >/dev/null 2>&1 || return 1
elif command -v dnf >/dev/null 2>&1; then
echo "Installing color-emoji font (google-noto-color-emoji-fonts)..."
timeout 120 $sudo dnf install -y google-noto-color-emoji-fonts >/dev/null 2>&1 || return 1
elif command -v pacman >/dev/null 2>&1; then
echo "Installing color-emoji font (noto-fonts-emoji)..."
timeout 120 $sudo pacman -Sy --noconfirm noto-fonts-emoji >/dev/null 2>&1 || return 1
elif command -v apk >/dev/null 2>&1; then
echo "Installing color-emoji font (font-noto-emoji)..."
timeout 120 $sudo apk add --no-cache font-noto-emoji >/dev/null 2>&1 || return 1
else
return 1
fi
# Refresh fontconfig cache so Chromium picks up the new font. Run under sudo
# for the system cache dirs (unprivileged fc-cache fails on unwritable dirs).
if command -v fc-cache >/dev/null 2>&1; then
$sudo fc-cache -f >/dev/null 2>&1 || fc-cache -f >/dev/null 2>&1 || true
fi
EMOJI_FONT_INSTALLED=1
return 0
}
# After a fresh font install, stop any running browse render daemon so the next
# make-pdf render spawns a fresh Chromium that sees the new font. Chromium
# caches its font list at process start, so a daemon that was alive before the
# install would keep emitting tofu. `browse stop` is the graceful API; the
# daemon auto-respawns on the next render. Best-effort and per-project-root, so
# we also print a note for daemons in other roots.
refresh_browse_daemon_for_fonts() {
[ "$EMOJI_FONT_INSTALLED" -eq 1 ] || return 0
if [ -x "$BROWSE_BIN" ]; then
"$BROWSE_BIN" stop >/dev/null 2>&1 || true
fi
echo " Installed a color-emoji font. The next make-pdf render will show emoji."
echo " If a gstack browser is running in another project, restart it to pick up the font."
}
prepare_bun_for_windows_compile() {
BUN_CMD="bun"
BUN_CMD_WAS_COPIED=0
[ "$IS_WINDOWS" -eq 1 ] || return 0
local bun_path
bun_path="$(command -v bun 2>/dev/null || true)"
case "$bun_path" in
*[![:ascii:]]*)
local bun_copy_dir="$SOURCE_GSTACK_DIR/.tmp-bun-bin"
mkdir -p "$bun_copy_dir"
cp -f "$bun_path" "$bun_copy_dir/bun.exe"
BUN_CMD="$bun_copy_dir/bun.exe"
BUN_CMD_WAS_COPIED=1
;;
esac
}
bun_cmd() {
"$BUN_CMD" "$@"
}
cleanup_copied_bun() {
if [ "${BUN_CMD_WAS_COPIED:-0}" -eq 1 ]; then
rm -rf "$SOURCE_GSTACK_DIR/.tmp-bun-bin"
fi
}
prepare_bun_for_windows_compile
trap cleanup_copied_bun EXIT
# Resolve the model overlay used for generated Codex skills. Setup auto-detects
# only Codex because it has one canonical TOML config surface; direct generator
# calls remain deterministic and use the host default unless --model is explicit.
# The resolver runs on EVERY setup, not just codex installs: step 1b regenerates
# .agents/ unconditionally, and existing ~/.codex/skills symlinks point into it —
# a plain `./setup` on a Sol user's machine must not clobber their profile with
# the hardcoded fallback. The resolver is a read-only TOML lookup that falls
# back to gpt when no Codex config exists.
CODEX_GENERATION_MODEL="gpt"
CODEX_GENERATION_MODEL_SOURCE="default (gpt)"
_CODEX_MODEL_ARGS=(run scripts/resolve-codex-generation-model.ts)
if [ "$MODEL_OVERRIDE_SET" -eq 1 ]; then
_CODEX_MODEL_ARGS+=(--explicit "$MODEL_OVERRIDE")
fi
_CODEX_MODEL_OUTPUT="$(cd "$SOURCE_GSTACK_DIR" && bun_cmd "${_CODEX_MODEL_ARGS[@]}")"
IFS=$'\t' read -r CODEX_GENERATION_MODEL CODEX_GENERATION_MODEL_SOURCE <<< "$_CODEX_MODEL_OUTPUT"
if [ -z "$CODEX_GENERATION_MODEL" ]; then
echo "gstack setup failed: Codex model resolver returned no model" >&2
exit 1
fi
if [ "$INSTALL_CODEX" -eq 1 ] || [ "$CODEX_GENERATION_MODEL" != "gpt" ]; then
log "Codex skill profile: $CODEX_GENERATION_MODEL"
log "Source: $CODEX_GENERATION_MODEL_SOURCE"
fi
# 1. Build browse binary if needed (smart rebuild: stale sources, package.json, lock)
NEEDS_BUILD=0
if [ ! -x "$BROWSE_BIN" ]; then
NEEDS_BUILD=1
elif [ -n "$(find "$SOURCE_GSTACK_DIR/browse/src" -type f -newer "$BROWSE_BIN" -print -quit 2>/dev/null)" ]; then
NEEDS_BUILD=1
elif [ "$SOURCE_GSTACK_DIR/package.json" -nt "$BROWSE_BIN" ]; then
NEEDS_BUILD=1
elif [ -f "$SOURCE_GSTACK_DIR/bun.lock" ] && [ "$SOURCE_GSTACK_DIR/bun.lock" -nt "$BROWSE_BIN" ]; then
NEEDS_BUILD=1
fi
if [ "$NEEDS_BUILD" -eq 1 ]; then
log "Building browse binary..."
(
cd "$SOURCE_GSTACK_DIR"
bun_cmd install --frozen-lockfile 2>/dev/null || bun_cmd install
bun_cmd run build
)
# Safety net: write .version if build script didn't (e.g., git not available during build)
if [ ! -f "$SOURCE_GSTACK_DIR/browse/dist/.version" ]; then
git -C "$SOURCE_GSTACK_DIR" rev-parse HEAD > "$SOURCE_GSTACK_DIR/browse/dist/.version" 2>/dev/null || true
fi
# macOS Apple Silicon: ad-hoc codesign compiled binaries.
# Bun's --compile can produce a corrupt or linker-only code signature that
# macOS kills with SIGKILL (exit 137). The two-step remove+re-sign is
# required because a naive `codesign -s - -f` fails when the existing
# signature block is corrupt. This is idempotent and costs <1s.
#
# Some binaries (observed: find-browse, gstack-global-discover) also carry
# trailing zero-padding AFTER the Mach-O LC_CODE_SIGNATURE region. macOS
# codesign requires the signature to be the last content and extend to EOF,
# so the padding triggers "main executable failed strict validation" on
# re-sign (and "internal error in Code Signing subsystem" on remove). We
# truncate that trailing slack to the end of LC_CODE_SIGNATURE first, which
# lets the identical re-sign succeed. The binary runs either way: Bun's
# adhoc code-page signature satisfies the kernel's exec check even when
# `codesign --verify` is unhappy, so a re-sign failure only warns when the
# binary is genuinely SIGKILL'd on exec (exit 137).
# See: https://github.com/garrytan/gstack/issues/997
if [ "$(uname -s)" = "Darwin" ] && [ "$(uname -m)" = "arm64" ]; then
for _bin in browse/dist/browse browse/dist/find-browse design/dist/design make-pdf/dist/pdf bin/gstack-global-discover; do
_bin_path="$SOURCE_GSTACK_DIR/$_bin"
[ -f "$_bin_path" ] && [ -x "$_bin_path" ] || continue
# Strip any trailing bytes past LC_CODE_SIGNATURE so codesign can re-sign.
# otool prints the signature's dataoff+datasize; if the file is larger,
# the extra bytes are Bun padding that breaks strict validation.
_sig_end=$(otool -l "$_bin_path" 2>/dev/null | awk '/LC_CODE_SIGNATURE/{f=1} f&&/dataoff/{o=$2} f&&/datasize/{print o+$2; exit}')
_fsize=$(stat -f%z "$_bin_path" 2>/dev/null)
if [ -n "$_sig_end" ] && [ -n "$_fsize" ] && [ "$_sig_end" -gt 0 ] 2>/dev/null && [ "$_sig_end" -lt "$_fsize" ] 2>/dev/null; then
_trunc_tmp=$(mktemp 2>/dev/null) || _trunc_tmp=""
if [ -n "$_trunc_tmp" ] && head -c "$_sig_end" "$_bin_path" > "$_trunc_tmp" 2>/dev/null; then
cat "$_trunc_tmp" > "$_bin_path" && chmod +x "$_bin_path"
fi
[ -n "$_trunc_tmp" ] && rm -f "$_trunc_tmp"
fi
codesign --remove-signature "$_bin_path" 2>/dev/null || true
if ! codesign -s - -f "$_bin_path" 2>/dev/null; then
# Re-sign failed. Only warn if the binary genuinely cannot execute
# (SIGKILL = exit 137). Otherwise Bun's adhoc code-page signature still
# runs fine and the codesign --verify miss is cosmetic. set -e safe.
_probe_rc=0
"$_bin_path" --help >/dev/null 2>&1 || _probe_rc=$?
if [ "$_probe_rc" -eq 137 ]; then
log "warning: codesign failed for $_bin and it is SIGKILL'd on exec (exit 137) — it may not run on Apple Silicon"
else
log "note: codesign could not re-sign $_bin, but it executes fine (Bun adhoc signature); continuing"
fi
fi
done
fi
# macOS: install coreutils for `gtimeout` (Codex hang protection in /codex + /autoplan).
# macOS ships BSD `timeout`-less; Homebrew's coreutils installs GNU timeout as
# `gtimeout` to avoid shadowing BSD utilities. The /codex and /autoplan skills
# fall back to unwrapped codex invocations when neither is available — this
# auto-install upgrades them to hang-protected where possible.
# Skip entirely with GSTACK_SKIP_COREUTILS=1 (CI, managed machines, offline envs).
if [ "$(uname -s)" = "Darwin" ] && [ "${GSTACK_SKIP_COREUTILS:-0}" != "1" ]; then
if ! command -v gtimeout >/dev/null 2>&1 && ! command -v timeout >/dev/null 2>&1; then
if command -v brew >/dev/null 2>&1; then
log "Installing coreutils for Codex hang protection (set GSTACK_SKIP_COREUTILS=1 to skip)..."
brew install coreutils >/dev/null 2>&1 || log "warning: brew install coreutils failed; /codex will run without hang protection"
else
log "warning: Homebrew not found. /codex will run without hang protection. Install coreutils manually or set GSTACK_SKIP_COREUTILS=1."
fi
fi
fi
fi
if [ ! -x "$BROWSE_BIN" ]; then
echo "gstack setup failed: browse binary missing at $BROWSE_BIN" >&2
exit 1
fi
# 1b. Generate .agents/ Codex skill docs — always regenerate to prevent stale descriptions.
# .agents/ is no longer committed — generated at setup time from .tmpl templates.
# bun run build generates the host-default artifact. Always render Codex again
# with the resolved user profile so a build cannot overwrite a Sol-specific render.
# Always regenerate: generation is fast (<2s) and mtime-based staleness checks are fragile
# (miss stale files when timestamps match after clone/checkout/upgrade).
AGENTS_DIR="$SOURCE_GSTACK_DIR/.agents/skills"
NEEDS_AGENTS_GEN=1
if [ "$NEEDS_AGENTS_GEN" -eq 1 ]; then
log "Generating .agents/ skill docs..."
(
cd "$SOURCE_GSTACK_DIR"
bun_cmd install --frozen-lockfile 2>/dev/null || bun_cmd install
bun_cmd run gen:skill-docs --host codex --model "$CODEX_GENERATION_MODEL"
)
fi
# 1c. Generate .factory/ Factory Droid skill docs
if [ "$INSTALL_FACTORY" -eq 1 ] && [ "$NEEDS_BUILD" -eq 0 ]; then
log "Generating .factory/ skill docs..."
(
cd "$SOURCE_GSTACK_DIR"
bun_cmd install --frozen-lockfile 2>/dev/null || bun_cmd install
bun_cmd run gen:skill-docs --host factory
)
fi
# 1d. Generate .opencode/ OpenCode skill docs
if [ "$INSTALL_OPENCODE" -eq 1 ] && [ "$NEEDS_BUILD" -eq 0 ]; then
log "Generating .opencode/ skill docs..."
(
cd "$SOURCE_GSTACK_DIR"
bun_cmd install --frozen-lockfile 2>/dev/null || bun_cmd install
bun_cmd run gen:skill-docs --host opencode
)
fi
# 1e. Generate .cursor/ Cursor skill docs
if [ "$INSTALL_CURSOR" -eq 1 ] && [ "$NEEDS_BUILD" -eq 0 ]; then
log "Generating .cursor/ skill docs..."
(
cd "$SOURCE_GSTACK_DIR"
bun_cmd install --frozen-lockfile 2>/dev/null || bun_cmd install
bun_cmd run gen:skill-docs --host cursor
)
fi
# 2. Ensure Playwright's Chromium is available
# Detect Ubuntu 26.04: Playwright does not yet ship a native chromium build for
# ubuntu26.04-x64. Override the platform to ubuntu24.04-x64 so the installer
# picks the correct binary. This is safe because the ubuntu24.04 build runs
# fine on ubuntu26.04 (same glibc lineage). See #2101.
_PLAYWRIGHT_PLATFORM_OVERRIDE=""
if [ -f /etc/os-release ]; then
_os_id=$(grep '^ID=' /etc/os-release | cut -d= -f2 | tr -d '"')
_os_ver=$(grep '^VERSION_ID=' /etc/os-release | cut -d= -f2 | tr -d '"')
if [ "$_os_id" = "ubuntu" ] && [ "$_os_ver" = "26.04" ]; then
_PLAYWRIGHT_PLATFORM_OVERRIDE="ubuntu24.04-x64"
echo "Ubuntu 26.04 detected — using PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=$_PLAYWRIGHT_PLATFORM_OVERRIDE"
fi
fi
# Chromium is BEST-EFFORT (#1900, #1901, #1902, #913, #2233). Every later step
# — skill registration (# 4), Codex/Kiro installs, migrations, hooks — is
# independent of the browser, so a failed or wedged download must never abort
# setup under `set -e`. Each failure records a reason code in _PW_FAIL_REASON;
# the skills that need Chromium (/qa, /qa-only, /design-review, /browse,
# make-pdf, /pair-agent) are named in the final summary instead of the user
# discovering a half-installed gstack. Lock contention is a reason too: another
# setup is installing Chromium right now, so this run registers skills and
# re-probes next time. The download is bounded (default 600s, env
# GSTACK_PLAYWRIGHT_INSTALL_TIMEOUT) because Playwright's own retries cover a
# flaky socket but not a wedged bunx; a wedged installer is killed with its
# child tree (_kill_tree: pgrep-walked, /proc-walked where pgrep is missing).
# Reason codes: skipped, chromium-install,
# chromium-install-timeout, chromium-install-locked, windows-no-node,
# windows-node-modules, post-install-launch.
# test/setup-playwright-best-effort.test.ts pins this block.
_PW_FAIL_REASON=""
_pw_fail() {
local code="$1"; shift
_PW_FAIL_REASON="${_PW_FAIL_REASON:+$_PW_FAIL_REASON,}$code"
echo " Chromium bootstrap: $code — $*" >&2
}
_PW_INSTALL_TIMEOUT="${GSTACK_PLAYWRIGHT_INSTALL_TIMEOUT:-600}"
# Normalize to a plain positive integer or fall back to the default: empty and
# non-numeric are garbage; "0"/"000" would kill the install on the first poll;
# "0600" is 600; anything past nine digits is not a deadline (a value bash
# cannot compare would leave the install unbounded — the exact failure the
# bound exists to prevent).
case "$_PW_INSTALL_TIMEOUT" in ''|*[!0-9]*) _PW_INSTALL_TIMEOUT=600 ;; esac
[ "${#_PW_INSTALL_TIMEOUT}" -le 9 ] || _PW_INSTALL_TIMEOUT=600
_PW_INSTALL_TIMEOUT=$((10#$_PW_INSTALL_TIMEOUT))
[ "$_PW_INSTALL_TIMEOUT" -gt 0 ] || _PW_INSTALL_TIMEOUT=600
if [ "${GSTACK_SKIP_PLAYWRIGHT:-0}" = "1" ]; then
_pw_fail skipped "GSTACK_SKIP_PLAYWRIGHT=1 — Chromium install skipped by request (#913)"
elif ! ensure_playwright_browser; then
echo "Installing Playwright Chromium..."
# XProtect self-heal (#2554): the probe failure may be the OS killing the
# cached Chromium, not a missing install. Clear quarantine on the Playwright
# cache bundles before reinstalling so the fresh fetch launches clean.
_clear_playwright_quarantine
_PW_LOCK="${TMPDIR:-/tmp}/gstack-playwright-install.lock"
# Stale-lock self-heal: a SIGKILL'd prior setup leaves the lock dir behind
# forever (mkdir mutexes have no owner). If the recorded holder PID is dead,