-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·1255 lines (1138 loc) · 47.4 KB
/
setup.sh
File metadata and controls
executable file
·1255 lines (1138 loc) · 47.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
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
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2025-2026 Marcus Quinn
# Shell safety baseline
set -Eeuo pipefail
IFS=$'\n\t'
# shellcheck disable=SC2154 # rc is assigned by $? in the trap string
trap 'rc=$?; echo "[ERROR] ${BASH_SOURCE[0]}:${LINENO} exit $rc" >&2' ERR
shopt -s inherit_errexit 2>/dev/null || true
# AI Assistant Server Access Framework Setup Script
# Helps developers set up the framework for their infrastructure
#
# Version: 3.8.74
#
# Quick Install:
# npm install -g aidevops && aidevops update (recommended)
# brew install marcusquinn/tap/aidevops && aidevops update (Homebrew)
# bash <(curl -fsSL https://aidevops.sh/install) (manual)
# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color
# Global flags
CLEAN_MODE=false
INTERACTIVE_MODE=false
NON_INTERACTIVE="${AIDEVOPS_NON_INTERACTIVE:-false}"
UPDATE_TOOLS_MODE=false
# Python compatibility floor used by setup checks and skill/tool gating.
# Keep in sync with setup-modules/plugins.sh requirements.
PYTHON_REQUIRED_MAJOR=3
PYTHON_REQUIRED_MINOR=10
export PYTHON_REQUIRED_MAJOR PYTHON_REQUIRED_MINOR
# Platform constants — exported for sourced setup-modules (shell-env.sh,
# tool-install.sh) that reference them at runtime.
PLATFORM_MACOS=$([[ "$(uname -s)" == "Darwin" ]] && echo true || echo false)
PLATFORM_ARM64=$([[ "$(uname -m)" == "arm64" || "$(uname -m)" == "aarch64" ]] && echo true || echo false)
export PLATFORM_MACOS PLATFORM_ARM64
readonly PLATFORM_MACOS PLATFORM_ARM64
# Extended platform detection (t1748: Linux/WSL2 support).
# Sources platform-detect.sh when available to export AIDEVOPS_PLATFORM,
# AIDEVOPS_SCHEDULER, AIDEVOPS_CLIPBOARD_COPY, etc.
_platform_detect_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.agents/scripts/platform-detect.sh"
if [[ -f "$_platform_detect_script" ]]; then
# shellcheck disable=SC1090 # dynamic path, exists at runtime
source "$_platform_detect_script"
fi
unset _platform_detect_script
# Repo constants — exported; consumed by setup-modules/core.sh, agent-deploy.sh
REPO_URL="https://github.com/marcusquinn/aidevops.git"
# INSTALL_DIR: resolve from the directory where setup.sh is executed (supports worktrees)
# For bootstrap (curl install), this will be /dev/fd/NN and trigger re-exec after clone
INSTALL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export REPO_URL INSTALL_DIR
# Source modular setup functions (t316.2)
# These modules are sourced only when setup.sh is run from the repo directory
# (not during bootstrap from curl, which re-execs after cloning)
SETUP_MODULES_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.agents/scripts/setup" 2>/dev/null && pwd)" || true
if [[ -d "$SETUP_MODULES_DIR" ]]; then
# shellcheck disable=SC1091 # Dynamic path via $SETUP_MODULES_DIR; files exist at runtime
source "$SETUP_MODULES_DIR/_common.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_backup.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_validation.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_migration.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_shell.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_installation.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_deployment.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_opencode.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_tools.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_services.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_bootstrap.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_routines.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_privacy_guard.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_complexity_guard.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_task_id_guard.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_canonical_guard.sh"
fi
print_info() { local _m="$1"; echo -e "${BLUE}[INFO]${NC} $_m"; return 0; }
print_success() { local _m="$1"; echo -e "${GREEN}[SUCCESS]${NC} $_m"; return 0; }
print_warning() { local _m="$1"; echo -e "${YELLOW}[WARNING]${NC} $_m"; return 0; }
print_error() { local _m="$1"; echo -e "${RED}[ERROR]${NC} $_m"; return 0; }
# Source shared-constants for config support (is_feature_enabled / config_enabled)
# Try repo-local first, then deployed location
_SHARED_CONSTANTS="${BASH_SOURCE[0]%/*}/.agents/scripts/shared-constants.sh"
if [[ ! -f "$_SHARED_CONSTANTS" ]]; then
_SHARED_CONSTANTS="$HOME/.aidevops/agents/scripts/shared-constants.sh"
fi
if [[ -f "$_SHARED_CONSTANTS" ]]; then
# shellcheck disable=SC1090 # Dynamic path resolved at runtime
source "$_SHARED_CONSTANTS"
fi
unset _SHARED_CONSTANTS
# Escape a string for safe embedding in XML (plist heredocs).
# Prevents XML injection if paths contain &, <, >, ", or ' characters.
_xml_escape() {
local str="$1"
str="${str//&/&}"
str="${str//</<}"
str="${str//>/>}"
str="${str//\"/"}"
str="${str//\'/'}"
printf '%s' "$str"
return 0
}
# Escape a string for safe embedding in crontab entries.
# Wraps value in single quotes (prevents $(…), backtick, and variable expansion
# by cron's /bin/sh). Embedded single quotes are escaped via the '\'' idiom.
_cron_escape() {
local str="$1"
str="${str//$'\n'/ }"
str="${str//$'\r'/ }"
# Replace each ' with '\'' (end quote, escaped quote, start quote)
str="${str//\'/\'\\\'\'}"
printf "'%s'" "$str"
return 0
}
# Resolve the canonical main worktree path for the current repo.
# When setup.sh is run from a linked worktree, launchd/cron should still point
# autonomous services at the main repo checkout, not the feature worktree.
_resolve_main_worktree_dir() {
local repo_dir="$1"
local main_worktree=""
main_worktree=$(git -C "$repo_dir" worktree list --porcelain 2>/dev/null | awk '/^worktree / {print substr($0, 10); exit}') || main_worktree=""
if [[ -n "$main_worktree" && -d "$main_worktree" ]]; then
printf '%s' "$main_worktree"
return 0
fi
printf '%s' "$repo_dir"
return 0
}
# Ensure the crontab has a single PATH= line at the top with the current $PATH.
# Individual cron entries must NOT set inline PATH= — it overrides the global one
# and hardcodes system-specific paths (nvm, bun, cargo, etc.). This function
# manages a tagged comment + PATH line pair; re-running setup.sh updates it
# idempotently. The marker must be a separate comment line because crontab does
# NOT support inline comments on environment variable lines — anything after
# PATH= is treated as part of the value.
_ensure_cron_path() {
local current_crontab marker="# aidevops-path"
current_crontab=$(crontab -l 2>/dev/null) || current_crontab=""
# Deduplicate PATH entries (preserving order)
# Bash 3.2 compat: no associative arrays — use string-based seen list
local deduped_path=""
local seen_dirs=" "
local IFS=':'
for dir in $PATH; do
if [[ -n "$dir" && "$seen_dirs" != *" ${dir} "* ]]; then
seen_dirs="${seen_dirs}${dir} "
deduped_path="${deduped_path:+${deduped_path}:}${dir}"
fi
done
unset IFS
# Marker on its own line, PATH on the next — crontab treats everything
# after PATH= as the value (no inline comments)
local path_block="${marker}
PATH=${deduped_path}"
# Remove only the aidevops-managed marker + PATH pair.
# User-owned PATH= lines are left untouched.
local filtered
filtered=$(printf '%s\n' "$current_crontab" | awk -v marker="$marker" '
$0 == marker { drop_next_path=1; next }
drop_next_path && /^PATH=/ { drop_next_path=0; next }
{ drop_next_path=0; print }
')
if [[ -n "$filtered" ]]; then
current_crontab="${path_block}
${filtered}"
else
current_crontab="$path_block"
fi
printf '%s\n' "$current_crontab" | crontab - 2>/dev/null || true
return 0
}
# Check if a launchd agent is loaded (SIGPIPE-safe for pipefail, t1265)
_launchd_has_agent() {
local label="$1"
local output
output=$(launchctl list 2>/dev/null) || true
echo "$output" | grep -qF "$label"
return $?
}
# Install a launchd plist only if its content has changed.
# Avoids unnecessary unload/reload which resets StartInterval timers.
# Usage: _launchd_install_if_changed <label> <plist_path> <new_content>
# Returns: 0 = installed or unchanged, 1 = failed to load
_launchd_install_if_changed() {
local label="$1"
local plist_path="$2"
local new_content="$3"
# Compare with existing plist — skip reload if identical
if [[ -f "$plist_path" ]]; then
local existing_content
existing_content=$(cat "$plist_path")
if [[ "$existing_content" == "$new_content" ]]; then
# Ensure it's loaded even if content unchanged
if ! _launchd_has_agent "$label"; then
launchctl load "$plist_path" 2>/dev/null || return 1
fi
return 0
fi
# Content changed — unload before replacing
if _launchd_has_agent "$label"; then
launchctl unload "$plist_path" 2>/dev/null || true
fi
fi
# Write new plist and load
printf '%s\n' "$new_content" >"$plist_path"
launchctl load "$plist_path" 2>/dev/null || return 1
return 0
}
# Detect whether a scheduler is already installed via launchd, cron, or systemd.
# Optionally migrates legacy launchd labels / cron entries to launchd on macOS.
# Args: arg1=scheduler_name, arg2=launchd_label, arg3=legacy_launchd_label,
# arg4=cron_marker, arg5=migrate_script, arg6=migrate_arg, arg7=migrate_hint
# arg8=systemd_unit (optional — base name without .timer suffix, e.g. "aidevops-supervisor-pulse")
_scheduler_detect_installed() {
local scheduler_name="$1"
local launchd_label="$2"
local legacy_launchd_label="$3"
local cron_marker="$4"
local migrate_script="$5"
local migrate_arg="$6"
local migrate_hint="$7"
local systemd_unit="${8:-}"
local installed=false
if _launchd_has_agent "$launchd_label"; then
installed=true
elif [[ -n "$legacy_launchd_label" ]] && _launchd_has_agent "$legacy_launchd_label"; then
if [[ -n "$migrate_script" ]] && [[ -x "$migrate_script" ]]; then
if bash "$migrate_script" "$migrate_arg" >/dev/null 2>&1; then
print_info "$scheduler_name LaunchAgent migrated to new label"
else
print_warning "$scheduler_name label migration failed. Run: $migrate_hint"
fi
fi
installed=true
elif crontab -l 2>/dev/null | grep -qF "$cron_marker"; then
if [[ "$PLATFORM_MACOS" == "true" ]] && [[ -n "$migrate_script" ]] && [[ -x "$migrate_script" ]]; then
if bash "$migrate_script" "$migrate_arg" >/dev/null 2>&1; then
print_info "$scheduler_name migrated from cron to launchd"
else
print_warning "$scheduler_name cron->launchd migration failed. Run: $migrate_hint"
fi
fi
installed=true
elif [[ -n "$systemd_unit" ]] && command -v systemctl >/dev/null 2>&1 &&
systemctl --user is-enabled "${systemd_unit}.timer" >/dev/null 2>&1; then
# Systemd user timer detected (GH#17381 — Linux systemd path was missing)
installed=true
fi
if [[ "$installed" == "true" ]]; then
return 0
fi
return 1
}
_should_setup_noninteractive_supervisor_pulse() {
local pulse_label="com.aidevops.aidevops-supervisor-pulse"
if _scheduler_detect_installed \
"Supervisor pulse" \
"$pulse_label" \
"" \
"pulse-wrapper" \
"" \
"" \
"" \
"aidevops-supervisor-pulse"; then
return 0
fi
if type config_enabled &>/dev/null && config_enabled "orchestration.supervisor_pulse"; then
return 0
fi
return 1
}
# Generic non-interactive scheduler detection (GH#17695 Finding B).
# Returns 0 if the named scheduler is already installed on any backend,
# meaning it should be regenerated during non-interactive setup.
# Args: arg1=name arg2=launchd_label arg3=cron_marker arg4=systemd_unit
_should_setup_noninteractive_scheduler() {
local name="$1"
local launchd_label="$2"
local cron_marker="$3"
local systemd_unit="${4:-}"
if _scheduler_detect_installed \
"$name" \
"$launchd_label" \
"" \
"$cron_marker" \
"" \
"" \
"" \
"$systemd_unit"; then
return 0
fi
return 1
}
# Spinner for long-running operations
# Usage: run_with_spinner "Installing package..." command arg1 arg2
run_with_spinner() {
local message="$1"
shift
local pid
local spin_chars='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
local i=0
# Suppress Homebrew's slow auto-update for all backgrounded brew commands.
# run_with_spinner backgrounds via "$@" &, so env var prefix syntax
# (VAR=x cmd) doesn't propagate. Export globally for the child process.
local _brew_was_set="${HOMEBREW_NO_AUTO_UPDATE:-}"
local _cmd="${1:-}"
local _subcmd="${2:-}"
if [[ "$_cmd" == "brew" && "$_subcmd" != "update" ]]; then
export HOMEBREW_NO_AUTO_UPDATE=1
fi
# Start command in background
"$@" &>/dev/null &
pid=$!
# Show spinner while command runs
printf "${BLUE}[INFO]${NC} %s " "$message"
while kill -0 "$pid" 2>/dev/null; do
printf "\r${BLUE}[INFO]${NC} %s %s" "$message" "${spin_chars:i++%${#spin_chars}:1}"
sleep 0.1
done
# Check exit status
wait "$pid"
local exit_code=$?
# Restore HOMEBREW_NO_AUTO_UPDATE to previous state
if [[ -z "$_brew_was_set" ]]; then
unset HOMEBREW_NO_AUTO_UPDATE
fi
# Clear spinner and show result
printf "\r"
if [[ $exit_code -eq 0 ]]; then
print_success "$message done"
else
print_error "$message failed"
fi
return $exit_code
}
# Verified install: download script to temp file, inspect, then execute
# Replaces unsafe curl|sh patterns with download-verify-execute
# Usage: verified_install "description" "url" [extra_args...]
# Options (set before calling):
# VERIFIED_INSTALL_SUDO="true" - run with sudo
# VERIFIED_INSTALL_SHELL="sh" - use sh instead of bash (default: bash)
# Returns: 0 on success, 1 on failure
verified_install() {
local description="$1"
local url="$2"
shift 2
local extra_args=("$@")
local shell="${VERIFIED_INSTALL_SHELL:-bash}"
local use_sudo="${VERIFIED_INSTALL_SUDO:-false}"
# Reset options for next call
VERIFIED_INSTALL_SUDO="false"
VERIFIED_INSTALL_SHELL="bash"
# Create secure temp file
local tmp_script
tmp_script=$(mktemp "${TMPDIR:-/tmp}/aidevops-install-XXXXXX.sh") || {
print_error "Failed to create temp file for $description"
return 1
}
# Ensure cleanup on exit from this function
# shellcheck disable=SC2064
trap "rm -f '$tmp_script'" RETURN
# Download script to file (not piped to shell)
print_info "Downloading $description install script..."
if ! curl -fsSL "$url" -o "$tmp_script" 2>/dev/null; then
print_error "Failed to download $description install script from $url"
return 1
fi
# Verify download is non-empty and looks like a script
if [[ ! -s "$tmp_script" ]]; then
print_error "Downloaded $description script is empty"
return 1
fi
# Basic content safety check: reject binary content
if file "$tmp_script" 2>/dev/null | grep -qv 'text'; then
print_error "Downloaded $description script appears to be binary, not a shell script"
return 1
fi
# Make executable
chmod +x "$tmp_script"
# Execute from file
# Build cmd array once; prepend sudo conditionally to avoid duplicating the safe expansion
# Use ${extra_args[@]+"${extra_args[@]}"} for safe expansion under set -u when array is empty
local cmd=()
[[ "$use_sudo" == "true" ]] && cmd+=(sudo)
cmd+=("$shell" "$tmp_script" ${extra_args[@]+"${extra_args[@]}"})
if "${cmd[@]}"; then
print_success "$description installed"
return 0
else
print_error "$description installation failed"
return 1
fi
}
# Find OpenCode config file (checks multiple possible locations)
# Returns: path to config file, or empty string if not found
find_opencode_config() {
local candidates=(
"$HOME/.config/opencode/opencode.json" # XDG standard (Linux, some macOS)
"$HOME/.opencode/opencode.json" # Alternative location
"$HOME/Library/Application Support/opencode/opencode.json" # macOS standard
)
for candidate in "${candidates[@]}"; do
if [[ -f "$candidate" ]]; then
echo "$candidate"
return 0
fi
done
return 1
}
# get_latest_homebrew_python_formula() and find_python3() are defined in
# _common.sh (sourced above). Not duplicated here — see GH#5239 review.
# Install a package globally via npm, with sudo when needed on Linux.
# Usage: npm_global_install "package-name" OR npm_global_install "package@version"
# On Linux with apt-installed npm, automatically prepends sudo.
# Returns: 0 on success, 1 on failure
npm_global_install() {
local pkg="$1"
if command -v npm >/dev/null 2>&1; then
# npm global installs need sudo on Linux when prefix dir isn't writable
if [[ "$(uname)" != "Darwin" ]] && [[ ! -w "$(npm config get prefix 2>/dev/null)/lib" ]]; then
sudo npm install -g "$pkg"
else
npm install -g "$pkg"
fi
return $?
else
return 1
fi
}
# Prompt the user for input, with non-interactive fallback.
# Canonical definition in .agents/scripts/setup/_common.sh; this fallback
# ensures the function exists even when _common.sh was not sourced (e.g.
# bootstrap from curl where setup-modules/ doesn't exist yet).
if ! type setup_prompt &>/dev/null; then
setup_prompt() {
local var_name="$1"
local prompt_text="$2"
local default_value="${3:-}"
# Non-interactive: use default without prompting
if [[ "${NON_INTERACTIVE:-false}" == "true" ]] || [[ ! -t 0 ]]; then
# shellcheck disable=SC2059 # var_name is a variable name, not a format string
printf -v "$var_name" '%s' "$default_value"
return 0
fi
local _setup_prompt_reply=""
read -r -p "$prompt_text" _setup_prompt_reply || _setup_prompt_reply="$default_value"
# shellcheck disable=SC2059 # var_name is a variable name, not a format string
printf -v "$var_name" '%s' "$_setup_prompt_reply"
return 0
}
fi
# Confirm step in interactive mode
# Usage: confirm_step "Step description" && function_to_run
# Returns: 0 if confirmed or not interactive, 1 if skipped
confirm_step() {
local step_name="$1"
# Skip confirmation in non-interactive mode
if [[ "$INTERACTIVE_MODE" != "true" ]]; then
return 0
fi
echo ""
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}Step:${NC} $step_name"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
while true; do
echo -n -e "${GREEN}Run this step? [Y]es / [n]o / [q]uit: ${NC}"
read -r response
# Convert to lowercase (bash 3.2 compatible)
response=$(echo "$response" | tr '[:upper:]' '[:lower:]')
case "$response" in
y | yes | "")
return 0
;;
n | no | s | skip)
print_warning "Skipped: $step_name"
return 1
;;
q | quit | exit)
echo ""
print_info "Setup cancelled by user"
exit 0
;;
*)
echo "Please answer: y (yes), n (no), or q (quit)"
;;
esac
done
}
# Backup rotation settings
BACKUP_KEEP_COUNT=10
# Create a backup with rotation (keeps last N backups)
# Usage: create_backup_with_rotation <source_path> <backup_name>
# Example: create_backup_with_rotation "$target_dir" "agents"
# Creates: ~/.aidevops/agents-backups/20251221_123456/
create_backup_with_rotation() {
local source_path="$1"
local backup_name="$2"
local backup_base="$HOME/.aidevops/${backup_name}-backups"
local backup_dir
backup_dir="$backup_base/$(date +%Y%m%d_%H%M%S)"
# Create backup directory
mkdir -p "$backup_dir"
# Copy source to backup (tolerant of broken symlinks / missing entries)
if [[ -d "$source_path" ]]; then
if command -v rsync >/dev/null 2>&1 && rsync --help 2>&1 | grep -q -- '--ignore-missing-args'; then
# rsync >= 3.1.0: --ignore-missing-args skips missing/broken entries gracefully
if ! rsync -a --ignore-missing-args "$source_path/" "$backup_dir/$(basename "$source_path")/" 2>/dev/null; then
print_warning "Backup had partial failures (broken symlinks?), continuing"
fi
else
# Fallback: cp -R may fail on broken symlinks under set -e,
# so run in a subshell that tolerates errors
if ! (cp -R "$source_path" "$backup_dir/" 2>/dev/null); then
print_warning "Backup had partial failures (broken symlinks?), continuing"
fi
fi
elif [[ -f "$source_path" ]]; then
cp "$source_path" "$backup_dir/"
else
print_warning "Source path does not exist: $source_path"
return 1
fi
print_info "Backed up to $backup_dir"
# Rotate old backups (keep last N)
local backup_count
backup_count=$(find "$backup_base" -maxdepth 1 -type d -name "20*" 2>/dev/null | wc -l | tr -d ' ')
if [[ $backup_count -gt $BACKUP_KEEP_COUNT ]]; then
local to_delete=$((backup_count - BACKUP_KEEP_COUNT))
print_info "Rotating backups: removing $to_delete old backup(s), keeping last $BACKUP_KEEP_COUNT"
# Delete oldest backups (sorted by name = sorted by date)
find "$backup_base" -maxdepth 1 -type d -name "20*" 2>/dev/null | sort | head -n "$to_delete" | while read -r old_backup; do
rm -rf "$old_backup"
done
fi
return 0
}
# Validate namespace string for safe use in paths and shell commands
# Returns 0 if valid, 1 if invalid
# Valid: alphanumeric, dash, underscore, forward slash (no .., no shell metacharacters)
validate_namespace() {
local ns="$1"
# Reject empty
[[ -z "$ns" ]] && return 1
# Reject path traversal
[[ "$ns" == *".."* ]] && return 1
# Reject shell metacharacters and dangerous characters
[[ "$ns" =~ [^a-zA-Z0-9/_-] ]] && return 1
# Reject absolute paths
[[ "$ns" == /* ]] && return 1
# Reject trailing slash (causes issues with rsync/tar exclusions)
[[ "$ns" == */ ]] && return 1
return 0
}
# =============================================================================
# Bootstrap guard: detect curl/process-substitution execution
# When running via `bash <(curl ...)`, BASH_SOURCE[0] is /dev/fd/NN and the
# setup-modules/ directory doesn't exist at that path. We must clone the repo
# first, then re-exec the local copy. This MUST run before any source lines.
# =============================================================================
_setup_script_dir="$(dirname "${BASH_SOURCE[0]}")"
if [[ ! -d "$_setup_script_dir/setup-modules" ]]; then
# Running from curl pipe or process substitution — bootstrap the repo
print_info "Remote install detected — bootstrapping repository..."
# Auto-install git if missing
if ! command -v git >/dev/null 2>&1; then
if [[ "$(uname)" == "Darwin" ]]; then
print_info "Installing Xcode Command Line Tools (includes git)..."
xcode-select --install 2>/dev/null || true
xcode_wait=0
while ! command -v git >/dev/null 2>&1 && [[ $xcode_wait -lt 300 ]]; do
sleep 5
xcode_wait=$((xcode_wait + 5))
done
if ! command -v git >/dev/null 2>&1; then
print_error "git not available after Xcode CLT install. Re-run after installation completes."
exit 1
fi
elif command -v apt-get >/dev/null 2>&1; then
sudo apt-get update -qq && sudo apt-get install -y -qq git
elif command -v dnf >/dev/null 2>&1; then
sudo dnf install -y git
elif command -v yum >/dev/null 2>&1; then
sudo yum install -y git
elif command -v pacman >/dev/null 2>&1; then
sudo pacman -S --noconfirm git
elif command -v apk >/dev/null 2>&1; then
sudo apk add git
else
print_error "git is required but not installed and no supported package manager found"
exit 1
fi
fi
# Clone or update the repo (use hardcoded path for bootstrap)
# After clone, INSTALL_DIR will be set correctly by the re-exec
_bootstrap_install_dir="$HOME/Git/aidevops"
mkdir -p "$(dirname "$_bootstrap_install_dir")"
if [[ -d "$_bootstrap_install_dir/.git" ]]; then
print_info "Existing installation found — updating..."
cd "$_bootstrap_install_dir" || exit 1
git pull --ff-only || {
print_warning "Git pull failed — resetting to origin/main"
git fetch origin
git reset --hard origin/main
}
else
if [[ -d "$_bootstrap_install_dir" ]]; then
print_warning "Directory exists but is not a git repo — backing up"
mv "$_bootstrap_install_dir" "$_bootstrap_install_dir.backup.$(date +%Y%m%d_%H%M%S)"
fi
print_info "Cloning aidevops to $_bootstrap_install_dir..."
git clone "$REPO_URL" "$_bootstrap_install_dir" || {
print_error "Failed to clone repository"
exit 1
}
fi
print_success "Repository ready at $_bootstrap_install_dir"
# Re-execute the local copy (which has setup-modules/ available)
cd "$_bootstrap_install_dir" || exit 1
exec bash "./setup.sh" "$@"
fi
unset _setup_script_dir
# Source modularized setup functions
# shellcheck disable=SC1091 # Dynamic path via BASH_SOURCE; files exist at runtime
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/core.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/migrations.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/shell-env.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/tool-install.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/mcp-setup.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/agent-deploy.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/agent-runtime.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/tool-beads.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/config.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/plugins.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/schedulers.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/post-setup.sh"
parse_args() {
while [[ $# -gt 0 ]]; do
local _opt="$1"
case "$_opt" in
--clean)
CLEAN_MODE=true
shift
;;
--interactive | -i)
INTERACTIVE_MODE=true
shift
;;
--non-interactive | -n)
NON_INTERACTIVE=true
shift
;;
--update | -u)
UPDATE_TOOLS_MODE=true
shift
;;
--help | -h)
echo "Usage: ./setup.sh [OPTIONS]"
echo ""
echo "Options:"
echo " --clean Remove stale files before deploying (cleans ~/.aidevops/agents/)"
echo " --interactive, -i Ask confirmation before each step"
echo " --non-interactive, -n Deploy agents only, skip all optional installs (no prompts)"
echo " --update, -u Check for and offer to update outdated tools after setup"
echo " --help Show this help message"
echo ""
echo "Default behavior adds/overwrites files without removing deleted agents."
echo "Use --clean after removing or renaming agents to sync deletions."
echo "Use --interactive to control each step individually."
echo "Use --non-interactive for CI/CD or AI agent shells (no stdin required)."
echo "Use --update to check for tool updates after setup completes."
exit 0
;;
*)
print_error "Unknown option: $_opt"
echo "Use --help for usage information"
exit 1
;;
esac
done
return 0
}
# Initialize ~/.config/aidevops/settings.json with documented defaults.
# Idempotent — merges missing keys without overwriting existing values.
init_settings_json() {
local settings_helper="$HOME/.aidevops/agents/scripts/settings-helper.sh"
if [[ -x "$settings_helper" ]]; then
if bash "$settings_helper" init >/dev/null 2>&1; then
print_info "Settings file initialized: ~/.config/aidevops/settings.json"
fi
else
# Fallback: try from repo directory (first run before deployment)
local repo_helper
repo_helper="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.agents/scripts/settings-helper.sh"
if [[ -x "$repo_helper" ]]; then
if bash "$repo_helper" init >/dev/null 2>&1; then
print_info "Settings file initialized: ~/.config/aidevops/settings.json"
fi
fi
fi
return 0
}
# Print the setup header based on active mode flags.
_setup_print_header() {
echo "🤖 AI DevOps Framework Setup"
echo "============================="
if [[ "$CLEAN_MODE" == "true" ]]; then
echo "Mode: Clean (removing stale files)"
fi
if [[ "$NON_INTERACTIVE" == "true" ]]; then
echo "Mode: Non-interactive (deploy + migrations only, no prompts)"
elif [[ "$INTERACTIVE_MODE" == "true" ]]; then
echo "Mode: Interactive (confirm each step)"
echo ""
echo "Controls: [Y]es (default) / [n]o skip / [q]uit"
fi
if [[ "$UPDATE_TOOLS_MODE" == "true" ]]; then
echo "Mode: Update (will check for tool updates after setup)"
fi
echo ""
return 0
}
# GH#18950 (t2087) + GH#18965 (t2094): ensure modern bash is installed
# and up to date on macOS. Runs after platform detection, before deploy.
# Uses the canonical `ensure` subcommand which combines install + upgrade:
# - Missing → interactive prompt for install (or silent with --yes)
# - Installed but drifted → silent upgrade (brew upgrade bash)
# - Current → no-op
# Rate-limits `brew update` to 24h internally. Always fail-open — never
# blocks setup on a bash upgrade failure.
#
# Opt-out: AIDEVOPS_AUTO_UPGRADE_BASH=0 disables install + upgrade entirely.
_setup_check_bash_upgrade() {
# Only applies to macOS; Linux bash is already modern on any current distro.
if [[ "${AIDEVOPS_PLATFORM:-}" != "macos" ]]; then
return 0
fi
local helper="${INSTALL_DIR}/.agents/scripts/bash-upgrade-helper.sh"
[[ -x "$helper" ]] || return 0
if [[ "$NON_INTERACTIVE" == "true" ]]; then
# Non-interactive: ensure does everything silently (install with
# --yes, upgrade on drift, no-op when current). Same pattern as
# `aidevops update` — fire-and-forget.
"$helper" ensure --yes --quiet || print_warning "bash ensure failed (non-fatal) — advisory written"
return 0
fi
# Interactive: ensure prompts on first install (inherited from
# _bu_cmd_install's read path), runs silently on upgrade. Users don't
# see a prompt on every `./setup.sh` run — only the first one.
"$helper" ensure || print_warning "bash ensure failed (non-fatal) — advisory written"
return 0
}
# GH#17769: Comment out deprecated model env vars in a single credentials file.
_comment_out_deprecated_model_vars() {
local file="$1"
local deprecated_vars="AIDEVOPS_HEADLESS_MODELS|PULSE_MODEL"
local deprecation_note="# DEPRECATED by aidevops v3.7+ — model routing is now automatic (GH#17769)"
[[ -f "$file" ]] || return 0
# Only process lines that are active exports (not already commented)
if grep -qE "^[[:space:]]*export[[:space:]]+(${deprecated_vars})=" "$file" 2>/dev/null; then
sed -i.bak -E "s/^([[:space:]]*)(export[[:space:]]+(${deprecated_vars})=.*)$/\1${deprecation_note}\n\1# \2/" "$file"
rm -f "${file}.bak"
print_info "Commented out deprecated model env vars in $(basename "$file")"
fi
return 0
}
# GH#17769: Comment out deprecated model env vars from credentials.sh.
# Runs on every `aidevops update`. Uses sed to comment out (not delete) lines
# so the user's file history is preserved.
_cleanup_legacy_model_config() {
local creds_file="${HOME}/.config/aidevops/credentials.sh"
_comment_out_deprecated_model_vars "$creds_file"
# Clean up tenant credentials files
local tenant_dir="${HOME}/.config/aidevops/tenants"
if [[ -d "$tenant_dir" ]]; then
local tenant_creds=""
while IFS= read -r -d '' tenant_creds; do
_comment_out_deprecated_model_vars "$tenant_creds"
done < <(find "$tenant_dir" -name "credentials.sh" -print0 2>/dev/null)
fi
return 0
}
# Non-interactive path: deploy agents and run safe migrations only (no prompts).
_setup_run_non_interactive() {
print_info "Non-interactive mode: deploying agents and running safe migrations only"
verify_location
check_requirements
# Run quality tool detection in non-interactive mode too (warn-only path).
check_quality_tools
check_python_upgrade_available
set_permissions
migrate_old_backups
migrate_loop_state_directories
migrate_agent_to_agents_folder
migrate_mcp_env_to_credentials
migrate_pulse_repos_to_repos_json
cleanup_deprecated_paths
migrate_orphaned_supervisor
backfill_issue_relationships
cleanup_deprecated_mcps
cleanup_stale_bun_opencode
cleanup_stale_health_issue_caches
cleanup_worktree_entries_in_repos_json
_cleanup_legacy_model_config
validate_opencode_config
deploy_aidevops_agents
sync_agent_sources
install_aidevops_cli
setup_shellcheck_wrapper
if is_feature_enabled safety_hooks 2>/dev/null; then
setup_safety_hooks
fi
init_settings_json
# Parallelise independent skill operations (t1356: ~84s serial -> ~18s parallel)
# generate_agent_skills must complete before create_skill_symlinks (symlinks
# depend on generated SKILL.md files). scan_imported_skills is independent.
local _pid_symlinks=""
if generate_agent_skills; then
create_skill_symlinks &
_pid_symlinks=$!
else
print_warning "Agent skills generation failed — skipping skill symlinks"
fi
scan_imported_skills &
local _pid_scan=$!
if [[ -n "$_pid_symlinks" ]]; then
wait "$_pid_symlinks" 2>/dev/null || print_warning "Skill symlink creation encountered issues (non-critical)"
fi
wait "$_pid_scan" 2>/dev/null || print_warning "Skill security scan encountered issues (non-critical)"
inject_agents_reference
deploy_agents_to_runtimes
update_opencode_config
update_claude_config
update_codex_config
update_cursor_config
disable_ondemand_mcps
# Scaffold personal routines repo if not already present (idempotent).
# Creates local git repo + private GitHub remote for personal repo only.
# Org repos require explicit: aidevops init-routines --org <name>
setup_routines
# Install/refresh the privacy-guard pre-push hook in every initialized
# repo so TODO/todo/README/ISSUE_TEMPLATE pushes to public GitHub repos
# are scanned for private slug leaks (t1968).
setup_privacy_guard
# Install/refresh the complexity-regression pre-push hook in every
# initialized repo so pushes that introduce new function-complexity,
# nesting-depth, or file-size violations are caught before CI (t2198).
setup_complexity_guard
# Install/refresh the canonical-on-main post-checkout hook in every
# initialized repo so branch switches away from main in the canonical
# directory are warned against (t1995). Complements pre-edit-check.sh's
# t1990 edit-time check by catching the branch switch itself.
setup_canonical_guard
# Install/refresh the task-id collision guard commit-msg hook in every
# initialized repo so invented t-IDs in commit subjects are rejected
# at commit time (t2047). Belt-and-braces with the CI check in
# .github/workflows/task-id-collision-check.yml.
setup_task_id_guard
return 0
}
# Interactive path: all optional steps gated behind confirm_step prompts.
_setup_run_interactive() {
# Required steps (always run)
verify_location
check_requirements
# Quality tools check (optional but recommended)
confirm_step "Check quality tools (shellcheck, shfmt)" && check_quality_tools
# Core runtime setup (early - many later steps depend on these)
confirm_step "Setup Node.js runtime (required for OpenCode and tools)" && setup_nodejs
# Shell environment setup (early, so later tools benefit from zsh/Oh My Zsh)
confirm_step "Setup Oh My Zsh (optional, enhances zsh)" && setup_oh_my_zsh
confirm_step "Setup cross-shell compatibility (preserve bash config in zsh)" && setup_shell_compatibility
# OrbStack (macOS only - offer VM option early)
confirm_step "Setup OrbStack (lightweight Linux VMs on macOS)" && setup_orbstack_vm
# Optional steps with confirmation in interactive mode