-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·1612 lines (1497 loc) · 66.1 KB
/
setup.sh
File metadata and controls
executable file
·1612 lines (1497 loc) · 66.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
# 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.15.54
#
# 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
SETUP_STAGE=""
SETUP_STAGE_OPENCODE="setup_opencode_cli"
SETUP_STAGE_AGENTS="deploy_aidevops_agents"
SETUP_STAGE_HOOKS="setup_safety_hooks"
SETUP_STAGE_TABBY="setup_tabby"
SETUP_STAGE_PULSE="setup_supervisor_pulse"
SETUP_OS_DARWIN="Darwin"
# Python compatibility floor used by setup checks and skill/tool gating.
# Keep in sync with .agents/scripts/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 .agents/scripts/setup/modules (shell-env.sh,
# tool-install.sh) that reference them at runtime.
PLATFORM_MACOS=$([[ "$(uname -s)" == "$SETUP_OS_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 .agents/scripts/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/_scheduler_runtime.sh"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_runtime_helpers.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"
# shellcheck disable=SC1091
source "$SETUP_MODULES_DIR/_worktree_exclusions.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
}
# GH#21060 / t2911: Per-stage timing helper for non-interactive setup runs.
# Wraps a function call, records start/end time, and appends TSV lines to
# $HOME/.aidevops/logs/setup-stage-timings.log:
# iso8601_utc <TAB> stage_name <TAB> duration_seconds <TAB> exit_code
# A RUNNING row is written before each stage starts so a tool/worker timeout
# still leaves the currently executing phase in the timing log.
# Usage: _time_step "stage_name" function_name [args...]
# ShellCheck: $@ is used deliberately (SC2068 not applicable; no word-splitting
# issue since we shift the stage-name arg first and pass the rest as a command).
_time_step_log() {
local _ts_stage="$1"
local _ts_duration="$2"
local _ts_exit="$3"
printf '%s\t%s\t%s\t%s\n' \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
"$_ts_stage" \
"$_ts_duration" \
"$_ts_exit" \
>>"$HOME/.aidevops/logs/setup-stage-timings.log" 2>/dev/null || true
return 0
}
_time_step() {
local _ts_stage="$1"
shift
local _ts_start _ts_end _ts_duration _ts_exit
print_info "Starting setup stage: $_ts_stage"
_time_step_log "$_ts_stage" "0.00" "RUNNING"
_ts_start=$(date +%s.%N 2>/dev/null || date +%s)
_ts_exit=0
"$@" || _ts_exit=$?
_ts_end=$(date +%s.%N 2>/dev/null || date +%s)
_ts_duration=$(awk -v a="$_ts_start" -v b="$_ts_end" 'BEGIN { printf "%.2f", b - a }')
_time_step_log "$_ts_stage" "$_ts_duration" "$_ts_exit"
print_info "Finished setup stage: $_ts_stage (${_ts_duration}s, exit=${_ts_exit})"
return "$_ts_exit"
}
# 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
}
# Scheduler runtime helpers are sourced from .agents/scripts/setup/_scheduler_runtime.sh
# with the rest of the setup modules near the top of this file.
# Runtime helper functions are sourced from .agents/scripts/setup/_runtime_helpers.sh
# with the rest of the setup modules near the top of this file.
# 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
# .agents/scripts/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/.agents/scripts/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)" == "$SETUP_OS_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 .agents/scripts/setup/modules/ available)
cd "$_bootstrap_install_dir" || exit 1
exec bash "./setup.sh" "$@"
fi
unset _setup_script_dir
# Source modularized setup functions from the canonical setup module tree.
# The sibling .agents/scripts/setup/_*.sh files above are bootstrap/fallback
# helpers loaded early by the root entrypoint; normal setup implementation
# modules live under modules/ so the repository root has no module directory.
SETUP_IMPL_MODULES_DIR="${SETUP_MODULES_DIR}/modules"
# shellcheck disable=SC1091 # Dynamic path via $SETUP_IMPL_MODULES_DIR
source "${SETUP_IMPL_MODULES_DIR}/core.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/migrations.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/shell-env.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/tool-install.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/mcp-setup.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/agent-deploy.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/agent-runtime.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/tool-beads.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/config.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/plugins.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/schedulers.sh"
# shellcheck disable=SC1091
source "${SETUP_IMPL_MODULES_DIR}/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
;;
--stage)
if [[ -z "${2:-}" ]]; then
print_error "--stage requires a value"
_setup_print_stage_help
exit 1
fi
SETUP_STAGE="$2"
NON_INTERACTIVE=true
shift 2
;;
--stage=*)
SETUP_STAGE="${_opt#--stage=}"
if [[ -z "$SETUP_STAGE" ]]; then
print_error "--stage requires a value"
_setup_print_stage_help
exit 1
fi
NON_INTERACTIVE=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 " --stage <name> Run one supported setup stage/scope without full setup"
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 --stage for targeted updates: opencode, agents, hooks, tabby, pulse, full."
echo "Stage aliases: ${SETUP_STAGE_OPENCODE}, ${SETUP_STAGE_AGENTS}, ${SETUP_STAGE_HOOKS}, ${SETUP_STAGE_TABBY}, ${SETUP_STAGE_PULSE}."
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
if [[ -n "$SETUP_STAGE" ]]; then
_setup_validate_stage "$SETUP_STAGE" || exit $?
fi
return 0
}
_setup_print_stage_help() {
printf '%s\n' "Supported setup stages/scopes:"
printf ' opencode | %s Repair/install OpenCode CLI only\n' "$SETUP_STAGE_OPENCODE"
printf ' agents | %s Deploy .agents scripts/prompts only\n' "$SETUP_STAGE_AGENTS"
printf ' hooks | %s Install safety hooks only\n' "$SETUP_STAGE_HOOKS"
printf ' tabby | %s Sync Tabby profiles only\n' "$SETUP_STAGE_TABBY"
printf ' pulse | %s Install/refresh pulse scheduler only\n' "$SETUP_STAGE_PULSE"
printf '%s\n' " full Run the default full setup path"
return 0
}
_setup_canonical_stage() {
local stage="$1"
case "$stage" in
opencode | "$SETUP_STAGE_OPENCODE") printf '%s' "$SETUP_STAGE_OPENCODE" ;;
agents | "$SETUP_STAGE_AGENTS") printf '%s' "$SETUP_STAGE_AGENTS" ;;
hooks | "$SETUP_STAGE_HOOKS") printf '%s' "$SETUP_STAGE_HOOKS" ;;
tabby | "$SETUP_STAGE_TABBY") printf '%s' "$SETUP_STAGE_TABBY" ;;
pulse | "$SETUP_STAGE_PULSE") printf '%s' "$SETUP_STAGE_PULSE" ;;
full) printf '%s' "full" ;;
*) return 1 ;;
esac
return 0
}
_setup_validate_stage() {
local stage="$1"
if _setup_canonical_stage "$stage" >/dev/null; then
return 0
fi
print_error "Unknown setup stage/scope: $stage"
_setup_print_stage_help
return 1
}
# 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
}
# Deploy auto-hotfix.conf template to user-level configs if not already present.
# The template ships in .agents/configs/; this copies to ~/.aidevops/configs/
# where user edits survive `aidevops update`. Existing user config is preserved.
_deploy_hotfix_config() {
local source_conf="${INSTALL_DIR:-.}/.agents/configs/auto-hotfix.conf"
local target_dir="$HOME/.aidevops/configs"
local target_conf="$target_dir/auto-hotfix.conf"
if [[ ! -f "$source_conf" ]]; then
return 0
fi
# Only deploy if the user doesn't have one yet (preserve user edits)
if [[ -f "$target_conf" ]]; then
return 0
fi
mkdir -p "$target_dir"
cp "$source_conf" "$target_conf"
chmod 600 "$target_conf"
return 0
}
# t2919: Early pulse plist install. The pulse launchd agent is critical
# infrastructure — without it, every other pulse-driven feature (worker
# dispatch, issue routing, cross-repo coordination) is dead. Previously,
# setup_supervisor_pulse only ran inside _setup_post_setup_steps which
# executes AFTER ~25 other migration/setup steps. When `aidevops update`
# runs unattended and any earlier step times out (e.g. brew taps, MCP
# installs, slow repo scans), the pulse plist never gets installed/refreshed
# and the runner falls behind.
#
# Install immediately after deploy_aidevops_agents (so the scripts the plist
# references already exist on disk). The late install in _setup_post_setup_steps
# remains as the canonical regenerate-on-change path — _launchd_install_if_changed
# compares content and skips reload when identical, so the second call is a
# no-op when nothing changed. Failure here is non-fatal: the late path retries.
_setup_install_pulse_plist_early() {
local _early_os
_early_os="$(uname -s)"
if _should_setup_noninteractive_supervisor_pulse; then
setup_supervisor_pulse "$_early_os" || print_warning "Early pulse plist install failed (will retry late)"
fi
return 0
}
# Provision knowledge planes for all repos in repos.json where knowledge != "off".
# Idempotent: already-provisioned directories are not modified.
# Called from the non-interactive setup path (update) and after interactive init.
setup_knowledge_planes() {
local repos_file="$HOME/.config/aidevops/repos.json"
local helper
helper="${BASH_SOURCE[0]%/*}/.agents/scripts/knowledge-helper.sh"
if [[ ! -f "$helper" ]]; then
helper="$HOME/.aidevops/agents/scripts/knowledge-helper.sh"
fi
if [[ ! -f "$helper" ]]; then
print_warning "knowledge-helper.sh not found — skipping knowledge plane provisioning"
return 0
fi
if [[ ! -f "$repos_file" ]]; then
return 0
fi
if ! command -v jq &>/dev/null; then
print_warning "jq not installed — skipping knowledge plane provisioning"
return 0
fi
local repo_path mode
while IFS=$'\t' read -r repo_path mode; do
[[ -z "$repo_path" || "$mode" == "off" ]] && continue
if [[ ! -d "$repo_path" ]]; then
print_warning "knowledge-plane: repo path not found: $repo_path"
continue
fi
bash "$helper" provision "$repo_path" || print_warning "knowledge-plane: provision failed for $repo_path"
done < <(jq -r '.initialized_repos[] | select(.knowledge != null and .knowledge != "off") | [.path, .knowledge] | @tsv' "$repos_file" 2>/dev/null || true)
return 0
}
# Provision cases planes for all repos in repos.json where cases != "off".
# Idempotent: already-provisioned directories are not modified.
# Called from the non-interactive setup path (update) and after interactive init.
setup_cases_planes() {
local repos_file="$HOME/.config/aidevops/repos.json"
local helper
helper="${BASH_SOURCE[0]%/*}/.agents/scripts/case-helper.sh"
if [[ ! -f "$helper" ]]; then
helper="$HOME/.aidevops/agents/scripts/case-helper.sh"
fi
if [[ ! -f "$helper" ]]; then
print_warning "case-helper.sh not found — skipping cases plane provisioning"
return 0
fi
if [[ ! -f "$repos_file" ]]; then
return 0
fi
if ! command -v jq &>/dev/null; then
print_warning "jq not installed — skipping cases plane provisioning"
return 0
fi
local repo_path mode
while IFS=$'\t' read -r repo_path mode; do
[[ -z "$repo_path" || "$mode" == "off" ]] && continue
if [[ ! -d "$repo_path" ]]; then
print_warning "cases-plane: repo path not found: $repo_path"
continue
fi
bash "$helper" init "$repo_path" || print_warning "cases-plane: init failed for $repo_path"
done < <(jq -r '.initialized_repos[] | select(.cases != null and .cases != "off") | [.path, .cases] | @tsv' "$repos_file" 2>/dev/null || true)
return 0
}
# Non-interactive setup singleton state. This lock only gates the deployment path;
# interactive setup remains prompt-driven and can still be used for first-run init.
SETUP_NONINTERACTIVE_LOCK_HELD=false
SETUP_NONINTERACTIVE_LOCK_DIR=""
SETUP_NONINTERACTIVE_CHILD_PIDS=""
SETUP_NONINTERACTIVE_TERMINATING=false
_setup_lock_pid_alive() {
local pid="$1"
[[ "$pid" =~ ^[0-9]+$ ]] || return 1
kill -0 "$pid" 2>/dev/null
return $?
}
_setup_lock_pid_is_noninteractive_setup() {
local pid="$1"
local owner_args=""
[[ "$pid" =~ ^[0-9]+$ ]] || return 1
owner_args=$(ps -p "$pid" -o args= 2>/dev/null || true)
[[ -n "$owner_args" ]] || return 0
[[ "$owner_args" == *"setup.sh"* && ( "$owner_args" == *"--non-interactive"* || "$owner_args" == *"--stage"* ) ]]
return $?
}
_setup_lock_dir_age_seconds() {
local lock_dir="$1"
local lock_mtime=""
local now=""
if ! [[ -d "$lock_dir" ]]; then
printf '%s\n' 0
return 0
fi
if type _file_mtime_epoch >/dev/null 2>&1; then
lock_mtime=$(_file_mtime_epoch "$lock_dir" 2>/dev/null || true)
elif [[ "$(uname -s 2>/dev/null || true)" == "$SETUP_OS_DARWIN" || "$(uname -s 2>/dev/null || true)" == "FreeBSD" ]]; then
lock_mtime=$(stat -f %m "$lock_dir" 2>/dev/null || true)
else
lock_mtime=$(stat -c %Y "$lock_dir" 2>/dev/null || true)
fi
now=$(date +%s 2>/dev/null || true)
if [[ "$lock_mtime" =~ ^[0-9]+$ && "$now" =~ ^[0-9]+$ && "$now" -ge "$lock_mtime" ]]; then
printf '%s\n' $((now - lock_mtime))
return 0
fi
printf '%s\n' 0
return 0
}
_setup_lock_started_age_seconds() {
local lock_dir="$1"
local started_str=""
local started_epoch=""
local now_epoch=""
if [[ -r "$lock_dir/started_at" ]]; then
started_str=$(tr -d '[:space:]' <"$lock_dir/started_at" 2>/dev/null || true)
started_epoch=$(date -d "$started_str" +%s 2>/dev/null || \
date -u -jf '%Y-%m-%dT%H:%M:%SZ' "$started_str" +%s 2>/dev/null || true)
now_epoch=$(date +%s 2>/dev/null || true)
if [[ "$started_epoch" =~ ^[0-9]+$ && "$now_epoch" =~ ^[0-9]+$ && "$now_epoch" -ge "$started_epoch" ]]; then
printf '%s\n' $((now_epoch - started_epoch))
return 0
fi
fi
_setup_lock_dir_age_seconds "$lock_dir"
return 0
}
_setup_pid_elapsed_seconds() {
local pid="$1"
local etime=""
local first="" second="" third=""
local days=0 hours=0 minutes=0 seconds=0
[[ "$pid" =~ ^[0-9]+$ ]] || return 1
etime=$(ps -p "$pid" -o etime= 2>/dev/null || true)
etime="${etime//[[:space:]]/}"
[[ -n "$etime" ]] || return 1
IFS=':' read -r first second third <<<"$etime"
if [[ -n "$third" ]]; then
seconds="$third"
minutes="$second"
if [[ "$first" == *"-"* ]]; then
days="${first%%-*}"
hours="${first#*-}"
else
hours="$first"
fi
else
minutes="$first"
seconds="$second"
fi
if [[ "$days" =~ ^[0-9]+$ && "$hours" =~ ^[0-9]+$ && "$minutes" =~ ^[0-9]+$ && "$seconds" =~ ^[0-9]+$ ]]; then
printf '%s\n' $((days * 86400 + hours * 3600 + minutes * 60 + seconds))
return 0
fi
return 1
}
_setup_register_child_pid() {
local pid="$1"
[[ -n "$pid" ]] || return 0
SETUP_NONINTERACTIVE_CHILD_PIDS="${SETUP_NONINTERACTIVE_CHILD_PIDS}${SETUP_NONINTERACTIVE_CHILD_PIDS:+ }${pid}"
return 0
}
_setup_collect_child_pids() {
local parent_pid="$1"
local child_pid=""
local child_pids=""
local current_pid="${BASHPID:-$$}"
child_pids=$(pgrep -P "$parent_pid" 2>/dev/null || true)
for child_pid in $child_pids; do
[[ -n "$child_pid" && "$child_pid" != "$current_pid" ]] || continue
printf '%s\n' "$child_pid"
_setup_collect_child_pids "$child_pid"
done
return 0
}
_setup_kill_pid_tree() {
local signal_name="$1"
local root_pid="$2"
local child_pid=""
local current_pid="${BASHPID:-$$}"
[[ -n "$root_pid" && "$root_pid" != "$current_pid" ]] || return 0
for child_pid in $(_setup_collect_child_pids "$root_pid"); do
kill "-${signal_name}" "$child_pid" 2>/dev/null || true
done
kill "-${signal_name}" "$root_pid" 2>/dev/null || true
return 0
}
_setup_cleanup_noninteractive_children() {
local pid=""
local current_pid="${BASHPID:-$$}"
local grace_s="${AIDEVOPS_SETUP_CHILD_TERM_GRACE_S:-2}"
local has_live_child=false
[[ "$grace_s" =~ ^[0-9]+$ ]] || grace_s=2
for pid in $(_setup_collect_child_pids "$current_pid"); do
_setup_register_child_pid "$pid"
done
for pid in ${SETUP_NONINTERACTIVE_CHILD_PIDS:-}; do
if _setup_lock_pid_alive "$pid"; then
has_live_child=true
_setup_kill_pid_tree TERM "$pid"
fi
done
if [[ "$has_live_child" == "true" && "$grace_s" -gt 0 ]]; then
sleep "$grace_s" 2>/dev/null || true
fi
for pid in ${SETUP_NONINTERACTIVE_CHILD_PIDS:-}; do
if _setup_lock_pid_alive "$pid"; then
_setup_kill_pid_tree KILL "$pid"
fi
done
for pid in ${SETUP_NONINTERACTIVE_CHILD_PIDS:-}; do
wait "$pid" 2>/dev/null || true
done
return 0
}
_setup_run_noncritical_stage_bounded() {
local stage_label="$1"
local timeout_s="$2"
shift 2
local start_s=$SECONDS
local pid=""
local rc=0
[[ "$timeout_s" =~ ^[0-9]+$ ]] || timeout_s=60
"$@" &
pid=$!
_setup_register_child_pid "$pid"
while _setup_lock_pid_alive "$pid"; do
if (( SECONDS - start_s >= timeout_s )); then
_setup_kill_pid_tree TERM "$pid"
sleep "${AIDEVOPS_SETUP_CHILD_TERM_GRACE_S:-2}" 2>/dev/null || true
_setup_kill_pid_tree KILL "$pid"
wait "$pid" 2>/dev/null || true
print_warning "${stage_label} exceeded ${timeout_s}s — skipping remaining non-critical work"
return 0
fi
sleep 1
done
wait "$pid" 2>/dev/null || rc=$?
return "$rc"
}
_setup_release_noninteractive_setup_lock() {
local lock_dir="${SETUP_NONINTERACTIVE_LOCK_DIR:-}"
local owner_pid=""
if [[ "${SETUP_NONINTERACTIVE_LOCK_HELD:-false}" != "true" || -z "$lock_dir" ]]; then
return 0
fi
if [[ -r "$lock_dir/owner.pid" ]]; then
owner_pid=$(tr -d '[:space:]' <"$lock_dir/owner.pid" 2>/dev/null || true)
fi
if [[ -z "$owner_pid" || "$owner_pid" == "$$" ]]; then
rm -rf "$lock_dir" 2>/dev/null || true
fi
SETUP_NONINTERACTIVE_LOCK_HELD=false
return 0
}
_setup_noninteractive_signal_exit() {
local signal_name="$1"
local exit_code=143
[[ "$signal_name" == "INT" ]] && exit_code=130
SETUP_NONINTERACTIVE_TERMINATING=true
print_warning "setup.sh --non-interactive received ${signal_name}; cleaning up child deployment processes"
_setup_cleanup_noninteractive_children
_setup_release_noninteractive_setup_lock
exit "$exit_code"
}
# Compute how many seconds the live lock owner has held the setup lock.
# Uses started_at_epoch when it agrees with the owner PID runtime; falls back to
# the PID runtime when an old lock timestamp points at a newer live setup owner.
# Prints the age in seconds on stdout; prints 0 when unknown.
_setup_lock_owner_age() {
local lock_dir="$1"
local owner_pid="$2"
local _start_epoch="" _now_epoch="" _age_tmp="" _pid_age=""
if [[ -r "$lock_dir/started_at_epoch" ]]; then
_start_epoch=$(tr -d '[:space:]' <"$lock_dir/started_at_epoch" 2>/dev/null || true)
_now_epoch=$(date +%s 2>/dev/null || printf '0')
if [[ "$_start_epoch" =~ ^[0-9]+$ && "$_now_epoch" =~ ^[0-9]+$ && "$_now_epoch" -ge "$_start_epoch" ]]; then
_age_tmp="$((_now_epoch - _start_epoch))"
_pid_age=$(_setup_pid_elapsed_seconds "$owner_pid" 2>/dev/null || true)
if [[ "$_pid_age" =~ ^[0-9]+$ && "$_age_tmp" -gt $((_pid_age + 300)) ]]; then
printf '%s' "$_pid_age"
return 0
fi
printf '%s' "$_age_tmp"
return 0
fi
fi
# Fallback: ps etimes (seconds elapsed since process start).
_age_tmp=$(ps -p "$owner_pid" -o etimes= 2>/dev/null | tr -d '[:space:]')
if [[ "$_age_tmp" =~ ^[0-9]+$ ]]; then
printf '%s' "$_age_tmp"
return 0
fi
printf '0'
return 0
}
_setup_command_key_looks_secret() {
local key="$1"
key="${key#--}"
key="${key#-}"
case "$key" in
*password*|*passwd*|*secret*|*token*|*credential*|*api-key*|*api_key*|*apikey*|*access-key*|*access_key*|*private-key*|*private_key*|bearer)
return 0
;;
esac
return 1
}
_setup_redact_secret_like_command_values() {
local command_text="$1"
local redacted=""
local separator=""
local word=""
local lower_word=""
local key_part=""
local redact_next=false
for word in $command_text; do
lower_word=$(printf '%s' "$word" | tr '[:upper:]' '[:lower:]')
if [[ "$redact_next" == "true" ]]; then
word="[redacted]"
redact_next=false
elif [[ "$lower_word" == *=* ]]; then
key_part="${lower_word%%=*}"
if _setup_command_key_looks_secret "$key_part"; then
word="${word%%=*}=[redacted]"
fi
elif _setup_command_key_looks_secret "$lower_word"; then
redact_next=true
fi
redacted="${redacted}${separator}${word}"
separator=" "
done
printf '%s' "$redacted"
return 0
}
_setup_acquire_noninteractive_setup_lock() {
local lock_dir="${AIDEVOPS_SETUP_LOCK_DIR:-$HOME/.aidevops/locks/setup-noninteractive.lock.d}"
# Max seconds to wait for a live, non-stale owner before timing out.
local wait_ceiling="${AIDEVOPS_SETUP_WAIT_TIMEOUT_S:-900}"
# Max seconds a live owner may hold the lock before it is treated as
# stale and reclaimed (0 disables stale-live reclaim).
local stale_ceiling="${AIDEVOPS_SETUP_STALE_TIMEOUT_S:-1800}"
local owner_pid="" owner_cmd="" owner_age=0
local reclaim_attempts=0 waited=0
local _diag_stl="$HOME/.aidevops/logs/setup-stage-timings.log"
local _diag_interval_s="${AIDEVOPS_SETUP_LOCK_DIAG_INTERVAL_S:-60}"
[[ "$_diag_interval_s" =~ ^[0-9]+$ && "$_diag_interval_s" -gt 0 ]] || _diag_interval_s=60
mkdir -p "$(dirname "$lock_dir")" 2>/dev/null || true
while true; do
if mkdir "$lock_dir" 2>/dev/null; then
SETUP_NONINTERACTIVE_LOCK_DIR="$lock_dir"
SETUP_NONINTERACTIVE_LOCK_HELD=true
printf '%s\n' "$$" >"$lock_dir/owner.pid" 2>/dev/null || true
printf '%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$lock_dir/started_at" 2>/dev/null || true
printf '%s\n' "$(date +%s 2>/dev/null || printf '0')" >"$lock_dir/started_at_epoch" 2>/dev/null || true
printf '%s\n' "$0 $*" >"$lock_dir/command" 2>/dev/null || true
trap '_setup_cleanup_noninteractive_children; _setup_release_noninteractive_setup_lock' EXIT
trap '_setup_noninteractive_signal_exit TERM' TERM
trap '_setup_noninteractive_signal_exit INT' INT
return 0
fi
# Lock exists — inspect owner.
owner_pid=""
if [[ -r "$lock_dir/owner.pid" ]]; then
owner_pid=$(tr -d '[:space:]' <"$lock_dir/owner.pid" 2>/dev/null || true)
fi
if [[ -z "$owner_pid" ]]; then
local _lock_age="0"
_lock_age=$(_setup_lock_dir_age_seconds "$lock_dir")
if [[ "$_lock_age" -le 300 ]]; then
print_error "Another setup.sh --non-interactive process is acquiring the deploy lock (lock: ${lock_dir}, age ${_lock_age}s). Exiting to avoid overlapping deployments."
return 75
fi
print_warning "Removing stale setup.sh --non-interactive lock with no owner at ${lock_dir} (age ${_lock_age}s)"
rm -rf "$lock_dir" 2>/dev/null || true
reclaim_attempts=$((reclaim_attempts + 1))
if [[ "$reclaim_attempts" -ge 2 ]]; then
print_error "Unable to acquire setup.sh --non-interactive lock at ${lock_dir} after ${reclaim_attempts} stale-lock removals"
return 75
fi
continue
fi