-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·1728 lines (1600 loc) · 65.1 KB
/
setup.sh
File metadata and controls
executable file
·1728 lines (1600 loc) · 65.1 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
# 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.1.0
#
# 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
# 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
# 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"
fi
print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }
# 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 $?
}
# Detect whether a scheduler is already installed via launchd or cron.
# Optionally migrates legacy launchd labels / cron entries to launchd on macOS.
_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 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
fi
if [[ "$installed" == "true" ]]; 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
}
# Find best python3 binary (prefer Homebrew/pyenv over system)
find_python3() {
local candidates=(
"/opt/homebrew/bin/python3"
"/usr/local/bin/python3"
"$HOME/.pyenv/shims/python3"
)
for candidate in "${candidates[@]}"; do
if [[ -x "$candidate" ]]; then
echo "$candidate"
return 0
fi
done
# Fallback to PATH
if command -v python3 &>/dev/null; then
command -v python3
return 0
fi
return 1
}
# 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
}
# 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
if [[ -d "$source_path" ]]; then
cp -R "$source_path" "$backup_dir/"
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/config.sh"
# shellcheck disable=SC1091
source "$(dirname "${BASH_SOURCE[0]}")/setup-modules/plugins.sh"
parse_args() {
while [[ $# -gt 0 ]]; do
case "$1" 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: $1"
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
}
# Main setup function
main() {
# Bootstrap first (handles curl install)
bootstrap_repo "$@"
parse_args "$@"
local _os
_os="$(uname -s)"
# Auto-detect non-interactive terminals (CI/CD, agent shells, piped stdin)
# Must run after parse_args so explicit --interactive flag takes precedence
if [[ "$INTERACTIVE_MODE" != "true" && ! -t 0 ]]; then
NON_INTERACTIVE=true
fi
# Guard: --interactive and --non-interactive are mutually exclusive
if [[ "$INTERACTIVE_MODE" == "true" && "$NON_INTERACTIVE" == "true" ]]; then
print_error "--interactive and --non-interactive cannot be used together"
exit 1
fi
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 ""
# Non-interactive mode: deploy agents only, skip all optional installs
if [[ "$NON_INTERACTIVE" == "true" ]]; then
print_info "Non-interactive mode: deploying agents and running safe migrations only"
verify_location
check_requirements
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
cleanup_deprecated_mcps
cleanup_stale_bun_opencode
validate_opencode_config
deploy_aidevops_agents
sync_agent_sources
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 (18s), create_skill_symlinks (<1s), and
# scan_imported_skills (66s serial, ~10s with parallel scanning) are independent.
generate_agent_skills &
local _pid_skills=$!
create_skill_symlinks &
local _pid_symlinks=$!
scan_imported_skills &
local _pid_scan=$!
wait "$_pid_skills" 2>/dev/null || print_warning "Agent skills generation encountered issues (non-critical)"
wait "$_pid_symlinks" 2>/dev/null || print_warning "Skill symlink creation encountered issues (non-critical)"
wait "$_pid_scan" 2>/dev/null || print_warning "Skill security scan encountered issues (non-critical)"
inject_agents_reference
if is_feature_enabled manage_opencode_config 2>/dev/null; then
update_opencode_config
else
print_info "OpenCode config management disabled via config (integrations.manage_opencode_config)"
fi
if is_feature_enabled manage_claude_config 2>/dev/null; then
update_claude_config
else
print_info "Claude config management disabled via config (integrations.manage_claude_config)"
fi
disable_ondemand_mcps
else
# 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
confirm_step "Check optional dependencies (bun, node, python)" && check_optional_deps
confirm_step "Setup recommended tools (Tabby, Zed, etc.)" && setup_recommended_tools
confirm_step "Setup MiniSim (iOS/Android emulator launcher)" && setup_minisim
confirm_step "Setup Git CLIs (gh, glab, tea)" && setup_git_clis
confirm_step "Setup file discovery tools (fd, ripgrep, ripgrep-all)" && setup_file_discovery_tools
confirm_step "Setup rtk (token-optimized CLI output, 60-90% savings)" && setup_rtk
confirm_step "Setup shell linting tools (shellcheck, shfmt)" && setup_shell_linting_tools
setup_shellcheck_wrapper
confirm_step "Setup Qlty CLI (multi-linter code quality)" && setup_qlty_cli
confirm_step "Rosetta audit (Apple Silicon x86 migration)" && setup_rosetta_audit
confirm_step "Setup Worktrunk (git worktree management)" && setup_worktrunk
confirm_step "Setup SSH key" && setup_ssh_key
confirm_step "Setup configuration files" && setup_configs
confirm_step "Set secure permissions on config files" && set_permissions
confirm_step "Install aidevops CLI command" && install_aidevops_cli
confirm_step "Setup shell aliases" && setup_aliases
confirm_step "Setup terminal title integration" && setup_terminal_title
confirm_step "Deploy AI templates to home directories" && deploy_ai_templates
confirm_step "Migrate old backups to new structure" && migrate_old_backups
confirm_step "Migrate loop state from .claude/.agent/ to .agents/loop-state/" && migrate_loop_state_directories
confirm_step "Migrate .agent -> .agents in user projects" && migrate_agent_to_agents_folder
confirm_step "Migrate mcp-env.sh -> credentials.sh" && migrate_mcp_env_to_credentials
confirm_step "Migrate pulse-repos.json into repos.json" && migrate_pulse_repos_to_repos_json
confirm_step "Cleanup deprecated agent paths" && cleanup_deprecated_paths
confirm_step "Migrate orphaned supervisor to pulse-wrapper" && migrate_orphaned_supervisor
confirm_step "Cleanup deprecated MCP entries (hetzner, serper, etc.)" && cleanup_deprecated_mcps
confirm_step "Cleanup stale bun opencode install" && cleanup_stale_bun_opencode
confirm_step "Validate and repair OpenCode config schema" && validate_opencode_config
confirm_step "Extract OpenCode prompts" && extract_opencode_prompts
confirm_step "Check OpenCode prompt drift" && check_opencode_prompt_drift
confirm_step "Deploy aidevops agents to ~/.aidevops/agents/" && deploy_aidevops_agents
confirm_step "Sync agents from private repositories" && sync_agent_sources
setup_shellcheck_wrapper
confirm_step "Install Claude Code safety hooks (block destructive commands)" && setup_safety_hooks
confirm_step "Initialize settings.json (canonical config file)" && init_settings_json
confirm_step "Setup multi-tenant credential storage" && setup_multi_tenant_credentials
confirm_step "Generate agent skills (SKILL.md files)" && generate_agent_skills
confirm_step "Create symlinks for imported skills" && create_skill_symlinks
confirm_step "Check for skill updates from upstream" && check_skill_updates
confirm_step "Security scan imported skills" && scan_imported_skills
confirm_step "Inject agents reference into AI configs" && inject_agents_reference
confirm_step "Setup Python environment (DSPy, crawl4ai)" && setup_python_env
confirm_step "Setup Node.js environment" && setup_nodejs_env
confirm_step "Install MCP packages globally (fast startup)" && install_mcp_packages
confirm_step "Setup LocalWP MCP server" && setup_localwp_mcp
confirm_step "Setup Augment Context Engine MCP" && setup_augment_context_engine
confirm_step "Setup Beads task management" && setup_beads
confirm_step "Setup SEO integrations (curl subagents)" && setup_seo_mcps
confirm_step "Setup Google Analytics MCP" && setup_google_analytics_mcp
confirm_step "Setup QuickFile MCP (UK accounting)" && setup_quickfile_mcp
confirm_step "Setup browser automation tools" && setup_browser_tools
confirm_step "Setup AI orchestration frameworks info" && setup_ai_orchestration
confirm_step "Setup Google Workspace CLI (Gmail, Calendar, Drive)" && setup_google_workspace_cli
confirm_step "Setup OpenCode CLI (AI coding tool)" && setup_opencode_cli
confirm_step "Setup OpenCode plugins" && setup_opencode_plugins
# Run AFTER OpenCode CLI install so opencode.json may exist for agent config
confirm_step "Update OpenCode configuration" && update_opencode_config
# Run AFTER OpenCode config so Claude Code gets equivalent setup
confirm_step "Update Claude Code configuration (slash commands, MCPs, settings)" && update_claude_config
# Run AFTER all MCP setup functions to ensure disabled state persists
confirm_step "Disable on-demand MCPs globally" && disable_ondemand_mcps
fi
echo ""
print_success "🎉 Setup complete!"
# Enable auto-update if not already enabled
# Check both launchd (macOS) and cron (Linux) for existing installation
# Respects config: aidevops config set updates.auto_update false
local auto_update_script="$HOME/.aidevops/agents/scripts/auto-update-helper.sh"
if [[ -x "$auto_update_script" ]] && is_feature_enabled auto_update 2>/dev/null; then
local _auto_update_installed=false
if _scheduler_detect_installed \
"Auto-update" \
"com.aidevops.aidevops-auto-update" \
"com.aidevops.auto-update" \
"aidevops-auto-update" \
"$auto_update_script" \
"enable" \
"aidevops auto-update enable"; then
_auto_update_installed=true
fi
if [[ "$_auto_update_installed" == "false" ]]; then
if [[ "$NON_INTERACTIVE" == "true" ]]; then
# Non-interactive: enable silently
bash "$auto_update_script" enable >/dev/null 2>&1 || true
print_info "Auto-update enabled (every 10 min). Disable: aidevops auto-update disable"
else
echo ""
echo "Auto-update keeps aidevops current by checking every 10 minutes."
echo "Safe to run while AI sessions are active."
echo ""
read -r -p "Enable auto-update? [Y/n]: " enable_auto
if [[ "$enable_auto" =~ ^[Yy]?$ || -z "$enable_auto" ]]; then
bash "$auto_update_script" enable
else
print_info "Skipped. Enable later: aidevops auto-update enable"
fi
fi
fi
fi
# Supervisor pulse scheduler — consent-gated autonomous orchestration.
# Uses pulse-wrapper.sh which handles dedup, orphan cleanup, and RAM-based concurrency.
# macOS: launchd plist invoking wrapper | Linux: cron entry invoking wrapper
# The plist is ALWAYS regenerated on setup.sh to pick up config changes (env vars,
# thresholds). Only the first-install prompt is gated on consent state.
#
# Ensure crontab has a global PATH= line (Linux only; macOS uses launchd env).
# Must run before any cron entries are installed so they inherit the PATH.
if [[ "$_os" != "Darwin" ]]; then
_ensure_cron_path
fi
# Consent model (GH#2926):
# - Default OFF: supervisor_pulse defaults to false in all config layers
# - Explicit consent required: user must type "y" (prompt defaults to [y/N])
# - Consent persisted: written to config.jsonc so it survives updates
# - Never silently re-enabled: if config says false, skip entirely
# - Non-interactive: only installs if config explicitly says true
local wrapper_script="$HOME/.aidevops/agents/scripts/pulse-wrapper.sh"
local pulse_label="com.aidevops.aidevops-supervisor-pulse"
# Read explicit user consent from config.jsonc (not merged defaults).
# Empty = user never configured this; "true"/"false" = explicit choice.
local _pulse_user_config=""
if type _jsonc_get_raw &>/dev/null && [[ -f "${JSONC_USER:-$HOME/.config/aidevops/config.jsonc}" ]]; then
_pulse_user_config=$(_jsonc_get_raw "${JSONC_USER:-$HOME/.config/aidevops/config.jsonc}" "orchestration.supervisor_pulse")
fi
# Also check legacy .conf user override
if [[ -z "$_pulse_user_config" && -f "${FEATURE_TOGGLES_USER:-$HOME/.config/aidevops/feature-toggles.conf}" ]]; then
local _legacy_val
# Use awk instead of grep|tail|cut — grep exits 1 on no match, which
# aborts the script under set -euo pipefail. awk always exits 0.
_legacy_val=$(awk -F= '/^supervisor_pulse=/{val=$2} END{print val}' "${FEATURE_TOGGLES_USER:-$HOME/.config/aidevops/feature-toggles.conf}")
if [[ -n "$_legacy_val" ]]; then
_pulse_user_config="$_legacy_val"
fi
fi
# Also check env var override (highest priority)
if [[ -n "${AIDEVOPS_SUPERVISOR_PULSE:-}" ]]; then
_pulse_user_config="$AIDEVOPS_SUPERVISOR_PULSE"
fi
# Determine action based on consent state
local _do_install=false
local _pulse_lower
_pulse_lower=$(echo "$_pulse_user_config" | tr '[:upper:]' '[:lower:]')
if [[ "$_pulse_lower" == "false" ]]; then
# User explicitly declined — never prompt, never install
_do_install=false
elif [[ "$_pulse_lower" == "true" ]]; then
# User explicitly consented — install/regenerate
_do_install=true
elif [[ -z "$_pulse_user_config" ]]; then
# No explicit config — fresh install or never configured
if [[ "$NON_INTERACTIVE" == "true" ]]; then
# Non-interactive: default OFF, do not install without consent
_do_install=false
elif [[ -f "$wrapper_script" ]]; then
# Interactive: prompt with default-no
echo ""
echo "The supervisor pulse enables autonomous orchestration."
echo "It will act under your GitHub identity and consume API credits:"
echo " - Dispatches AI workers to implement tasks from GitHub issues"
echo " - Creates PRs, merges passing PRs, files improvement issues"
echo " - 4-hourly strategic review (opus-tier) for queue health"
echo " - Circuit breaker pauses dispatch on consecutive failures"
echo ""
read -r -p "Enable supervisor pulse? [y/N]: " enable_pulse
if [[ "$enable_pulse" =~ ^[Yy]$ ]]; then
_do_install=true
# Record explicit consent
if type cmd_set &>/dev/null; then
cmd_set "orchestration.supervisor_pulse" "true" || true
fi
else
_do_install=false
# Record explicit decline so we never re-prompt on updates
if type cmd_set &>/dev/null; then
cmd_set "orchestration.supervisor_pulse" "false" || true
fi
print_info "Skipped. Enable later: aidevops config set orchestration.supervisor_pulse true && ./setup.sh"
fi
fi
fi
# Guard: wrapper must exist
if [[ "$_do_install" == "true" && ! -f "$wrapper_script" ]]; then
# Wrapper not deployed yet — skip (will install on next run after rsync)
_do_install=false
fi
# Detect if pulse is already installed (for upgrade messaging)
# Uses shared helper to check both launchd and cron consistently
local _pulse_installed=false
if _scheduler_detect_installed \
"Supervisor pulse" \
"$pulse_label" \
"" \
"pulse-wrapper" \
"" \
"" \
""; then
_pulse_installed=true
fi
# Detect opencode binary location
local opencode_bin
opencode_bin=$(command -v opencode 2>/dev/null || echo "/opt/homebrew/bin/opencode")
if [[ "$_do_install" == "true" ]]; then
mkdir -p "$HOME/.aidevops/logs"
if [[ "$_os" == "Darwin" ]]; then
# macOS: use launchd plist with wrapper
local pulse_plist="$HOME/Library/LaunchAgents/${pulse_label}.plist"
# Unload old plist if upgrading
if _launchd_has_agent "$pulse_label"; then
launchctl unload "$pulse_plist" || true
pkill -f 'Supervisor Pulse' 2>/dev/null || true
fi