forked from Dicklesworthstone/agentic_coding_flywheel_setup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·6968 lines (6174 loc) · 286 KB
/
install.sh
File metadata and controls
executable file
·6968 lines (6174 loc) · 286 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
# shellcheck disable=SC1090,SC1091
# ACFS relies on Bash 4+ features (associative arrays, declare -g, etc.).
# macOS ships Bash 3.2 by default, so re-exec with Homebrew Bash when present.
if [[ -n "${BASH_VERSINFO:-}" ]] && (( BASH_VERSINFO[0] < 4 )); then
for acfs_modern_bash in /opt/homebrew/bin/bash /usr/local/bin/bash; do
if [[ -x "$acfs_modern_bash" ]]; then
exec "$acfs_modern_bash" "$0" "$@"
fi
done
cat >&2 <<'EOF'
ERROR: ACFS requires Bash 4+.
Detected: Bash 3.x (macOS system bash).
Install modern bash:
brew install bash
Then re-run:
/opt/homebrew/bin/bash ./install.sh --macos
EOF
exit 1
fi
# ============================================================
# ACFS - Agentic Coding Flywheel Setup
# Main installer script
#
# Usage:
# curl -fsSL "https://raw.githubusercontent.com/deepakdgupta1/agentic-coding/main/install.sh?$(date +%s)" | bash -s -- --yes --mode vibe
#
# Options:
# --yes Skip all prompts, use defaults
# --mode vibe Enable passwordless sudo, full agent permissions
# --dry-run Print what would be done without changing system
# --print Print upstream scripts/versions that will be run
# --idempotency-audit Dry-run idempotency audit for local modes
# --skip-postgres Skip PostgreSQL 18 installation
# --skip-vault Skip HashiCorp Vault installation
# --skip-cloud Skip cloud CLIs (wrangler, supabase, vercel)
# --resume Resume from checkpoint (default when state exists)
# --force-reinstall Start fresh, ignore existing state
# --resume-from <stage> Skip all phases before this stage
# --stop-after <stage> Exit cleanly after this stage completes
# --reset-state Move state file aside and exit (for debugging)
# --interactive Enable interactive prompts for resume decisions
# --skip-preflight Skip pre-flight system validation
# --auto-fix Enable auto-fix for pre-flight issues (prompt mode, default)
# --no-auto-fix Disable auto-fix (only warn about issues)
# --auto-fix-accept-all Auto-fix all issues without prompting (for CI)
# --auto-fix-dry-run Show what auto-fix would do without executing
# --skip-ubuntu-upgrade Skip automatic Ubuntu version upgrade
# --target-ubuntu=VER Set target Ubuntu version (default: 25.10)
# --local / --desktop Run in sandboxed LXD container (for desktop PCs)
# --strict Treat ALL tools as critical (any checksum mismatch aborts)
# --list-modules List available modules and exit
# --print-plan Print execution plan and exit (no installs)
# --only <module> Only run a specific module (repeatable)
# --only-phase <phase> Only run modules in a specific phase (repeatable)
# --skip <module> Skip a specific module (repeatable)
# --no-deps Disable automatic dependency closure (expert/debug)
# --checksums-ref <ref> Fetch checksums.yaml from this ref (default: main for pinned tags/SHAs)
# Silence the "Installation checklist" output by default to reduce console noise
: "${ACFS_CHECKLIST_PROGRESS:=false}"
export ACFS_CHECKLIST_PROGRESS
# ============================================================
set -euo pipefail
# Prevent apt/dpkg from displaying interactive dialogs (kernel upgrade prompts,
# debconf questions, etc.) that corrupt the terminal with ncurses escape sequences
export DEBIAN_FRONTEND=noninteractive
export NEEDRESTART_MODE=a # Automatically restart services without asking
export NEEDRESTART_SUSPEND=1 # Suppress needrestart prompts during installation
export DEBCONF_NONINTERACTIVE_SEEN=true
# ============================================================
# Configuration
# ============================================================
ACFS_VERSION="0.6.0"
# Allow fork installations by overriding these via environment variables
ACFS_REPO_OWNER="${ACFS_REPO_OWNER:-deepakdgupta1}"
ACFS_REPO_NAME="${ACFS_REPO_NAME:-agentic-coding}"
ACFS_REF="${ACFS_REF:-main}"
# Preserve the original ref (branch/tag/sha) before resolving to a commit SHA.
ACFS_REF_INPUT="$ACFS_REF"
# Checksums ref defaults to ACFS_REF_INPUT, but pinned tags/SHAs fall back to main
# to avoid stale checksums for fast-moving upstream installers.
ACFS_CHECKSUMS_REF="${ACFS_CHECKSUMS_REF:-}"
if [[ -z "$ACFS_CHECKSUMS_REF" ]]; then
if [[ "$ACFS_REF_INPUT" =~ ^v[0-9]+(\.[0-9]+){1,2}([.-][A-Za-z0-9]+)*$ ]] || [[ "$ACFS_REF_INPUT" =~ ^[0-9a-f]{7,40}$ ]]; then
ACFS_CHECKSUMS_REF="main"
else
ACFS_CHECKSUMS_REF="$ACFS_REF_INPUT"
fi
fi
ACFS_RAW="https://raw.githubusercontent.com/${ACFS_REPO_OWNER}/${ACFS_REPO_NAME}/${ACFS_REF}"
ACFS_CHECKSUMS_RAW="https://raw.githubusercontent.com/${ACFS_REPO_OWNER}/${ACFS_REPO_NAME}/${ACFS_CHECKSUMS_REF}"
export ACFS_RAW ACFS_CHECKSUMS_REF ACFS_CHECKSUMS_RAW ACFS_VERSION
export CHECKSUMS_FILE="${ACFS_CHECKSUMS_YAML:-}"
ACFS_COMMIT_SHA="" # Short SHA for display (12 chars)
ACFS_COMMIT_SHA_FULL="" # Full SHA for pinning resume scripts (40 chars)
# Early curl defaults: enforce HTTPS (including redirects) when supported.
# This is used before security.sh is available (bootstrap / early library sourcing).
ACFS_EARLY_CURL_ARGS=(-fsSL)
if command -v curl &>/dev/null && curl --help all 2>/dev/null | grep -q -- '--proto'; then
ACFS_EARLY_CURL_ARGS=(--proto '=https' --proto-redir '=https' -fsSL)
fi
# Note: ACFS_HOME is set after TARGET_HOME is determined
ACFS_LOG_DIR="/var/log/acfs"
# SCRIPT_DIR is empty when running via curl|bash (stdin; no file on disk)
SCRIPT_DIR=""
if [[ -n "${BASH_SOURCE[0]:-}" && -f "${BASH_SOURCE[0]}" ]]; then
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
fi
# Early PATH setup: ensure ~/.local/bin is available for native installers (e.g., Claude Code)
# This is critical because the Claude native installer puts the binary at ~/.local/bin/claude
export PATH="$HOME/.local/bin:$PATH"
# Default options
YES_MODE=false
DRY_RUN=false
PRINT_MODE=false
PIN_REF_MODE=false
HELP_MODE=false
MODE="vibe"
IDEMPOTENCY_AUDIT=false
SKIP_POSTGRES=false
SKIP_VAULT=false
SKIP_CLOUD=false
# Local desktop installation mode (LXD sandboxing)
# When true, ACFS runs inside an LXD container to protect the host
LOCAL_MODE=false
MACOS_MODE=false
# Manifest-driven selection options (mjt.5.3)
LIST_MODULES=false
PRINT_PLAN_MODE=false
ONLY_MODULES=()
ONLY_PHASES=()
SKIP_MODULES=()
NO_DEPS=false
# Resume/reinstall options (used by state.sh confirm_resume)
export ACFS_FORCE_RESUME=false
export ACFS_FORCE_REINSTALL=false
# NOTE: When unset/empty, downstream libs default to interactive behavior when a TTY is available.
# install.sh forces non-interactive behavior in --yes mode.
export ACFS_INTERACTIVE="${ACFS_INTERACTIVE:-}"
RESET_STATE_ONLY=false
# Preflight options
SKIP_PREFLIGHT=false
# Auto-fix options (bd-19y9.3.4)
# Modes: "prompt" (default, interactive), "yes" (accept all), "no" (disable), "dry-run" (preview only)
AUTO_FIX_MODE="prompt"
export AUTO_FIX_MODE
# Ubuntu upgrade options (nb4: integrate upgrade phase)
SKIP_UBUNTU_UPGRADE=false
TARGET_UBUNTU_VERSION="25.10"
# Target user configuration
# Default: detect the current user (or SUDO_USER if running under sudo).
# Override with env var: TARGET_USER=myuser
# Note: Previously defaulted to "ubuntu" which broke non-ubuntu VPS installs.
_ACFS_DETECTED_USER="${SUDO_USER:-$(whoami)}"
TARGET_USER="${TARGET_USER:-$_ACFS_DETECTED_USER}"
unset _ACFS_DETECTED_USER
# Leave TARGET_HOME unset by default; init_target_paths will derive it from:
# - $HOME when running as TARGET_USER
# - /home/$TARGET_USER otherwise
TARGET_HOME="${TARGET_HOME:-}"
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
GRAY='\033[0;90m'
NC='\033[0m' # No Color
# Check if gum is available for enhanced UI
HAS_GUM=false
if command -v gum &>/dev/null; then
HAS_GUM=true
fi
# ============================================================
# Prevent logging.sh from overwriting our inline gum-enhanced functions
# ============================================================
export _ACFS_LOGGING_SH_LOADED=1
# ============================================================
# Minimal error-tracking fallbacks
# These are replaced once scripts/lib/error_tracking.sh is sourced (detect_environment()).
# ============================================================
type -t set_phase &>/dev/null || set_phase() { :; }
type -t try_step &>/dev/null || try_step() { shift; "$@"; }
type -t try_step_eval &>/dev/null || try_step_eval() { shift; bash -e -o pipefail -c "$1"; }
# ============================================================
# Installer libraries are sourced later in main() via detect_environment(), after
# bootstrapping the repo archive for curl|bash runs (prevents mixed refs).
# ============================================================
# ============================================================
# Source Ubuntu upgrade library for auto-upgrade functionality (nb4)
# ============================================================
_source_ubuntu_upgrade_lib() {
# Already loaded?
if [[ -n "${ACFS_UBUNTU_UPGRADE_LOADED:-}" ]]; then
return 0
fi
# Prefer bootstrapped libs when available (curl|bash mode), to avoid mixed refs.
if [[ -n "${ACFS_LIB_DIR:-}" ]] && [[ -f "$ACFS_LIB_DIR/ubuntu_upgrade.sh" ]]; then
# shellcheck source=scripts/lib/ubuntu_upgrade.sh
source "$ACFS_LIB_DIR/ubuntu_upgrade.sh"
export ACFS_UBUNTU_UPGRADE_LOADED=1
return 0
fi
# Try local file first (when running from repo)
if [[ -n "${SCRIPT_DIR:-}" ]] && [[ -f "$SCRIPT_DIR/scripts/lib/ubuntu_upgrade.sh" ]]; then
# shellcheck source=scripts/lib/ubuntu_upgrade.sh
source "$SCRIPT_DIR/scripts/lib/ubuntu_upgrade.sh"
export ACFS_UBUNTU_UPGRADE_LOADED=1
return 0
fi
# Try relative path (when running from repo root)
if [[ -f "./scripts/lib/ubuntu_upgrade.sh" ]]; then
source "./scripts/lib/ubuntu_upgrade.sh"
export ACFS_UBUNTU_UPGRADE_LOADED=1
return 0
fi
# Download for curl|bash scenario
if command -v curl &>/dev/null; then
local tmp_upgrade=""
if command -v mktemp &>/dev/null; then
tmp_upgrade="$(mktemp "${TMPDIR:-/tmp}/acfs-ubuntu-upgrade.XXXXXX" 2>/dev/null)" || tmp_upgrade=""
fi
if [[ -n "$tmp_upgrade" ]] && curl "${ACFS_EARLY_CURL_ARGS[@]}" "$ACFS_RAW/scripts/lib/ubuntu_upgrade.sh" -o "$tmp_upgrade" 2>/dev/null; then
source "$tmp_upgrade"
rm -f "$tmp_upgrade"
export ACFS_UBUNTU_UPGRADE_LOADED=1
return 0
fi
fi
# If we can't load it, return failure (caller should handle)
return 1
}
# ACFS Color scheme (Catppuccin Mocha inspired)
ACFS_PRIMARY="#89b4fa"
ACFS_SUCCESS="#a6e3a1"
ACFS_WARNING="#f9e2af"
ACFS_ERROR="#f38ba8"
ACFS_MUTED="#6c7086"
# ============================================================
# Fetch commit SHA and date from GitHub API
# This ensures we always know exactly which version is running
# ============================================================
export ACFS_COMMIT_DATE="" # exported for child processes/debugging
ACFS_COMMIT_AGE=""
fetch_commit_sha() {
# Already have it? Skip
if [[ -n "$ACFS_COMMIT_SHA" && "$ACFS_COMMIT_SHA" != "(unknown)" ]]; then
return 0
fi
# Need curl
if ! command -v curl &>/dev/null; then
ACFS_COMMIT_SHA="(curl not available)"
return 0
fi
# Fetch from GitHub API - get the commit SHA for the ref
local api_url="https://api.github.com/repos/${ACFS_REPO_OWNER}/${ACFS_REPO_NAME}/commits/${ACFS_REF}"
local response
if response=$(curl -sf --max-time 5 "$api_url" 2>/dev/null); then
# Try to use python3 for robust JSON parsing if available
local sha=""
local commit_date=""
if command -v python3 &>/dev/null; then
# Python parsing - robust against JSON formatting changes
sha=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin).get('sha', ''))" 2>/dev/null)
commit_date=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin).get('commit', {}).get('author', {}).get('date', ''))" 2>/dev/null)
else
# Fallback: Extract SHA from JSON using grep/sed (works without jq/python)
# Use grep -o to handle minified JSON (puts matches on new lines)
sha=$(echo "$response" | grep -o '"sha":[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([a-f0-9]*\)".*/\1/')
# Extract commit date (format: "2025-12-21T10:30:00Z")
commit_date=$(echo "$response" | grep -o '"date":[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([^"]*\)".*/\1/')
fi
if [[ -n "$sha" && ${#sha} -ge 7 ]]; then
ACFS_COMMIT_SHA="${sha:0:12}"
# shellcheck disable=SC2034 # Used by scripts/lib/ubuntu_upgrade.sh to pin resume scripts to a specific commit.
[[ ${#sha} -ge 40 ]] && ACFS_COMMIT_SHA_FULL="$sha"
fi
if [[ -n "$commit_date" ]]; then
ACFS_COMMIT_DATE="$commit_date"
# Calculate age
local now commit_ts age_seconds
now=$(date +%s 2>/dev/null || echo 0)
# Parse ISO 8601 date - handle both GNU and BSD date
if date -d "$commit_date" +%s &>/dev/null; then
# GNU date
commit_ts=$(date -d "$commit_date" +%s 2>/dev/null || echo 0)
else
# BSD date - try simpler parsing
commit_ts=$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "$commit_date" +%s 2>/dev/null || echo 0)
fi
if [[ "$now" -gt 0 && "$commit_ts" -gt 0 ]]; then
age_seconds=$((now - commit_ts))
# Handle negative age (clock skew / future commit)
if [[ $age_seconds -lt 0 ]]; then
ACFS_COMMIT_AGE="just now"
elif [[ $age_seconds -lt 60 ]]; then
ACFS_COMMIT_AGE="${age_seconds}s ago"
elif [[ $age_seconds -lt 3600 ]]; then
ACFS_COMMIT_AGE="$((age_seconds / 60))m ago"
elif [[ $age_seconds -lt 86400 ]]; then
ACFS_COMMIT_AGE="$((age_seconds / 3600))h ago"
else
ACFS_COMMIT_AGE="$((age_seconds / 86400))d ago"
fi
fi
fi
if [[ -n "$ACFS_COMMIT_SHA" ]]; then
return 0
fi
fi
# Fallback
ACFS_COMMIT_SHA="(unknown)"
}
# ============================================================
# Install gum FIRST for beautiful UI from the start
# ============================================================
install_gum_early() {
# Already have gum? Great!
if command -v gum &>/dev/null; then
HAS_GUM=true
return 0
fi
# Respect dry-run / print-only modes: do not modify the system just to
# improve UI.
if [[ "${DRY_RUN:-false}" == "true" ]] || [[ "${PRINT_MODE:-false}" == "true" ]]; then
return 0
fi
# Only attempt early gum install on supported Ubuntu systems.
# Preflight/ensure_ubuntu will stop execution later, but this prevents
# partial modifications (apt repo/key) on unsupported OS versions.
if [[ -f /etc/os-release ]]; then
# shellcheck disable=SC1091
source /etc/os-release
local version_id="${VERSION_ID:-}"
local version_major="${version_id%%.*}"
if [[ "${ID:-}" != "ubuntu" ]] || [[ -z "$version_id" ]] || [[ "$version_major" -lt 22 ]]; then
return 0
fi
else
return 0
fi
# Need curl to fetch gum - if curl isn't installed yet, skip early install
# (gum will be installed later in install_cli_tools after ensure_base_deps)
if ! command -v curl &>/dev/null; then
return 0
fi
# Need gpg for apt key handling
if ! command -v gpg &>/dev/null; then
return 0
fi
# Need apt-get for installation
if ! command -v apt-get &>/dev/null; then
return 0
fi
# Need root/sudo for apt operations
local sudo_cmd=""
if [[ $EUID -ne 0 ]]; then
if command -v sudo &>/dev/null; then
sudo_cmd="sudo"
else
# Can't install gum without sudo, fall back to plain output
return 0
fi
fi
echo -e "\033[0;90m → Installing gum for enhanced UI...\033[0m" >&2
# Step 1: Fetch Charm GPG key (with timeout)
echo -e "\033[0;90m ↳ Fetching Charm repository key...\033[0m" >&2
$sudo_cmd mkdir -p /etc/apt/keyrings 2>/dev/null || true
if ! curl --connect-timeout 10 --max-time 30 -fsSL https://repo.charm.sh/apt/gpg.key 2>/dev/null | \
$sudo_cmd gpg --batch --yes --dearmor -o /etc/apt/keyrings/charm.gpg 2>/dev/null; then
echo -e "\033[0;33m ⚠ Could not fetch Charm key (skipping gum, will retry later)\033[0m" >&2
return 0
fi
# Step 2: Add apt repository (using DEB822 format to avoid .migrate warnings on upgrade)
$sudo_cmd tee /etc/apt/sources.list.d/charm.sources > /dev/null 2>&1 << 'EOF'
Types: deb
URIs: https://repo.charm.sh/apt/
Suites: *
Components: *
Signed-By: /etc/apt/keyrings/charm.gpg
EOF
# Step 3: Update apt (this can be slow on fresh systems)
# Disable fancy progress to prevent terminal cursor issues
echo -e "\033[0;90m ↳ Updating package lists (may take 30-60s on fresh systems)...\033[0m" >&2
if ! DEBIAN_FRONTEND=noninteractive timeout 120 $sudo_cmd apt-get update -y \
-o Dpkg::Progress-Fancy="0" -o APT::Color="0" >/dev/null 2>&1; then
# Reset terminal line position in case apt left cursor in bad state
echo -e "\r\033[K\033[0;33m ⚠ apt-get update slow/failed (skipping gum, will retry later)\033[0m" >&2
return 0
fi
# Step 4: Install gum
# Use DEBIAN_FRONTEND=noninteractive and disable fancy progress to prevent
# terminal cursor position issues when apt-get fails or times out
echo -e "\033[0;90m ↳ Installing gum package...\033[0m" >&2
local apt_output
if apt_output=$(DEBIAN_FRONTEND=noninteractive timeout 60 $sudo_cmd apt-get install -y \
-o Dpkg::Progress-Fancy="0" -o APT::Color="0" gum 2>&1); then
HAS_GUM=true
# Reset terminal line position and show success
echo -e "\r\033[K\033[0;32m ✓ gum installed - enhanced UI enabled!\033[0m" >&2
else
# Reset terminal line position in case apt left cursor in bad state
echo -e "\r\033[K\033[0;33m ⚠ gum install failed (continuing without enhanced UI)\033[0m" >&2
# Show brief reason if available (e.g., "Unable to locate package", timeout, etc.)
if echo "$apt_output" | grep -qi "unable to locate\|not found\|timeout"; then
echo -e "\033[0;90m (Charm repository may be unavailable or package not found)\033[0m" >&2
fi
fi
}
# ============================================================
# ASCII Art Banner
# ============================================================
print_banner() {
# Ensure terminal is in a clean state before printing banner
# (previous apt/dpkg operations may have left cursor in bad position)
echo -e "\r\033[K" >&2
# Build version line with proper padding (63 chars inner width)
local version_text="Agentic Coding Flywheel Setup v${ACFS_VERSION}"
local padding=$(( (63 - ${#version_text}) / 2 ))
local version_line
version_line=$(printf "║%*s%s%*s║" "$padding" "" "$version_text" "$((63 - padding - ${#version_text}))" "")
# Build commit info line
local commit_text=""
if [[ -n "$ACFS_COMMIT_SHA" && "$ACFS_COMMIT_SHA" != "(unknown)" ]]; then
commit_text="Commit: ${ACFS_COMMIT_SHA}"
if [[ -n "$ACFS_COMMIT_AGE" ]]; then
commit_text="${commit_text} (${ACFS_COMMIT_AGE})"
fi
fi
local commit_padding=$(( (63 - ${#commit_text}) / 2 ))
local commit_line
if [[ -n "$commit_text" ]]; then
commit_line=$(printf "║%*s%s%*s║" "$commit_padding" "" "$commit_text" "$((63 - commit_padding - ${#commit_text}))" "")
else
commit_line="║ ║"
fi
local banner="
╔═══════════════════════════════════════════════════════════════╗
║ ║
║ █████╗ ██████╗███████╗███████╗ ║
║ ██╔══██╗██╔════╝██╔════╝██╔════╝ ║
║ ███████║██║ █████╗ ███████╗ ║
║ ██╔══██║██║ ██╔══╝ ╚════██║ ║
║ ██║ ██║╚██████╗██║ ███████║ ║
║ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚══════╝ ║
║ ║
${version_line}
${commit_line}
║ ║
╚═══════════════════════════════════════════════════════════════╝
"
if [[ "$HAS_GUM" == "true" ]]; then
echo "$banner" | gum style --foreground "$ACFS_PRIMARY" --bold >&2
else
echo -e "${BLUE}$banner${NC}" >&2
fi
}
# ============================================================
# Pinned Ref Output (bd-31ps.8.1)
# Prints resolved SHA and copy-pasteable pinned command
# ============================================================
print_pinned_ref() {
local sha="${ACFS_COMMIT_SHA_FULL:-$ACFS_COMMIT_SHA}"
if [[ -z "$sha" || "$sha" == "(unknown)" || "$sha" == "(curl not available)" ]]; then
echo "Error: Could not resolve ref '$ACFS_REF' to SHA" >&2
echo "" >&2
echo "Possible causes:" >&2
echo " - Invalid ref (branch, tag, or SHA)" >&2
echo " - GitHub API rate limit or network issue" >&2
echo "" >&2
echo "Try:" >&2
echo " export ACFS_REF=main # use main branch" >&2
echo " export ACFS_REF=v1.0 # use a tag" >&2
exit 1
fi
local short_sha="${sha:0:12}"
local install_url="https://raw.githubusercontent.com/${ACFS_REPO_OWNER}/${ACFS_REPO_NAME}/${sha}/install.sh"
echo ""
echo "═════════════════════════════════════════════════════════════════"
echo " ACFS Pinned Reference"
echo "═════════════════════════════════════════════════════════════════"
echo ""
echo " Requested ref: ${ACFS_REF_INPUT:-$ACFS_REF}"
echo " Resolved SHA: ${short_sha}"
if [[ -n "${ACFS_COMMIT_SHA_FULL:-}" ]]; then
echo " Full SHA: ${ACFS_COMMIT_SHA_FULL}"
fi
if [[ -n "${ACFS_COMMIT_DATE:-}" ]]; then
echo " Commit date: ${ACFS_COMMIT_DATE}"
fi
if [[ -n "${ACFS_COMMIT_AGE:-}" ]]; then
echo " Commit age: ${ACFS_COMMIT_AGE}"
fi
echo ""
echo "─────────────────────────────────────────────────────────────────"
echo "Copy-paste this command to install from this exact commit:"
echo ""
echo " curl -fsSL \"${install_url}\" | ACFS_REF=\"${sha}\" bash -s -- --yes --mode vibe"
echo ""
echo "Or with environment variable:"
echo ""
echo " export ACFS_REF=\"${sha}\""
echo " curl -fsSL \"https://agent-flywheel.com/install\" | bash -s -- --yes --mode vibe"
echo ""
echo "─────────────────────────────────────────────────────────────────"
echo ""
echo "Tip: Pinned refs ensure reproducible installs across machines."
echo " Use tags (e.g., v1.0.0) for stable releases."
echo ""
}
# ============================================================
# Logging functions (with gum enhancement)
# ============================================================
log_step() {
local step="${1:-}"
local message="${2:-}"
# Allow single-arg usage: treat the arg as the message
if [[ -z "$message" ]]; then
message="$step"
step="*"
fi
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_PRIMARY" --bold "[$step]" | tr -d '\n' >&2
echo -n " " >&2
gum style "$message" >&2
else
echo -e "${BLUE}[$step]${NC} $message" >&2
fi
}
log_detail() {
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_MUTED" --margin "0 0 0 4" "→ $1" >&2
else
echo -e "${GRAY} → $1${NC}" >&2
fi
}
log_info() {
log_detail "$1"
}
log_success() {
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_SUCCESS" --bold "✓ $1" >&2
else
echo -e "${GREEN}✓ $1${NC}" >&2
fi
}
log_warn() {
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_WARNING" "⚠ $1" >&2
else
echo -e "${YELLOW}⚠ $1${NC}" >&2
fi
}
log_error() {
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_ERROR" --bold "✖ $1" >&2
else
echo -e "${RED}✖ $1${NC}" >&2
fi
}
log_fatal() {
log_error "$1"
exit 1
}
log_section() {
if [[ "$HAS_GUM" == "true" ]]; then
echo "" >&2
gum style --foreground "$ACFS_PRIMARY" --bold "═══ $1 ═══" >&2
else
echo "" >&2
echo -e "${BLUE}═══ $1 ═══${NC}" >&2
fi
}
# ============================================================
# Log file capture (tee stderr to file)
# ============================================================
# Initialize log file capture: tee stderr to a timestamped log file.
# After calling, all stderr output is captured to ACFS_LOG_FILE.
acfs_log_init() {
local log_dir="${1:-${ACFS_HOME:+${ACFS_HOME}/logs}}"
# Fallback if ACFS_HOME not set or empty
if [[ -z "$log_dir" ]]; then
log_dir="${ACFS_LOG_DIR:-/var/log/acfs}"
fi
# Create log directory
mkdir -p "$log_dir" 2>/dev/null || return 1
ACFS_LOG_FILE="${log_dir}/install-$(date +%Y%m%d_%H%M%S).log"
export ACFS_LOG_FILE
# Write log header
{
printf '=== ACFS Install Log ===\n'
printf 'Started: %s\n' "$(date -Iseconds)"
printf 'Version: %s\n' "${ACFS_VERSION:-unknown}"
printf 'User: %s\n' "${TARGET_USER:-unknown}"
printf 'Home: %s\n' "${TARGET_HOME:-unknown}"
printf 'Mode: %s\n' "${MODE:-unknown}"
printf 'Bash: %s\n' "${BASH_VERSION:-unknown}"
printf '========================\n\n'
} > "$ACFS_LOG_FILE" 2>/dev/null || return 1
# Fix ownership so target user can read logs
if [[ -n "${TARGET_USER:-}" ]] && [[ "$(id -u)" -eq 0 ]]; then
chown "${TARGET_USER}:${TARGET_USER}" "$log_dir" "$ACFS_LOG_FILE" 2>/dev/null || true
fi
# Tee stderr: all stderr output goes to both terminal and log file.
# fd 3 = original stderr (preserved for terminal output).
#
# NOTE: Process substitution >(tee ...) can fail on some systems
# (especially Ubuntu 25.04 with bash 5.3+). We use a subshell guard
# to prevent set -e from exiting the entire script on failure.
# If tee logging fails, we fall back to simple file redirection.
local tee_logging_ok=false
if command -v tee >/dev/null 2>&1; then
# Test if process substitution works before committing to it.
# On bash 5.3+, bare `exec` under set -e can exit the script
# before `if` catches the failure, so we test in a subshell.
# shellcheck disable=SC2261
if (exec 3>&1; echo test > >(cat >/dev/null)) 2>/dev/null; then
# Process substitution works - set up tee logging
# Save original stderr first
exec 3>&2 || true
# Now redirect stderr to tee (which sends to both log and original stderr)
# shellcheck disable=SC2261
# Use subshell test first to prevent exec from exiting under bash 5.3+
if (set +e; exec 2> >(tee -a "$ACFS_LOG_FILE" >&3)) 2>/dev/null; then
exec 2> >(tee -a "$ACFS_LOG_FILE" >&3) && tee_logging_ok=true
fi
fi
fi
if [[ "$tee_logging_ok" != "true" ]]; then
# Fallback: redirect stderr to both terminal (via original fd) and log file
# This is less elegant but works on all bash versions
echo "Note: Tee logging unavailable on this system, using fallback" >&2 || true
# Save original stderr, then append to log file for each command
# We'll rely on explicit logging calls instead of automatic tee
ACFS_LOG_FALLBACK=true
export ACFS_LOG_FALLBACK
fi
log_detail "Log file: $ACFS_LOG_FILE"
}
# Close log file capture and restore stderr.
# Strips ANSI color codes from the log for clean text output.
acfs_log_close() {
# Restore original stderr if fd 3 is open
if { true >&3; } 2>/dev/null; then
exec 2>&3 3>&-
fi
if [[ -n "${ACFS_LOG_FILE:-}" ]] && [[ -f "$ACFS_LOG_FILE" ]]; then
# Strip ANSI escape codes for clean log
sed -i $'s/\033\[[0-9;]*m//g' "$ACFS_LOG_FILE" 2>/dev/null || true
# Append footer
{
printf '\n========================\n'
printf 'Finished: %s\n' "$(date -Iseconds)"
printf '========================\n'
} >> "$ACFS_LOG_FILE"
# Fix ownership
if [[ -n "${TARGET_USER:-}" ]] && [[ "$(id -u)" -eq 0 ]]; then
chown "${TARGET_USER}:${TARGET_USER}" "$ACFS_LOG_FILE" 2>/dev/null || true
fi
fi
}
# ============================================================
# Install summary JSON (bd-31ps.3.2)
# ============================================================
# Emit a JSON summary of the install run for downstream tooling.
# Usage: acfs_summary_emit <status> [total_seconds]
# status: "success" or "failure"
# total_seconds: total wall-clock time (optional, default 0)
# Output: ~/.acfs/logs/install_summary_<timestamp>.json
acfs_summary_emit() {
local status="$1"
local total_seconds="${2:-0}"
# Require jq (installed by ensure_base_deps before phases run)
command -v jq &>/dev/null || return 1
local summary_dir="${ACFS_HOME:-${TARGET_HOME:?}/.acfs}/logs"
mkdir -p "$summary_dir" 2>/dev/null || return 1
ACFS_SUMMARY_FILE="${summary_dir}/install_summary_$(date +%Y%m%d_%H%M%S).json"
export ACFS_SUMMARY_FILE
# Read phase data from state.json if available
local phases_json="[]"
local failure_json="null"
if [[ -f "${ACFS_STATE_FILE:-}" ]] && command -v jq &>/dev/null; then
# Build phases array: [{id, name, duration_seconds}] in completion order
phases_json=$(jq -r '
(.completed_phases // []) as $completed |
(.phase_durations // {}) as $durations |
[$completed[] | {id: ., duration_seconds: ($durations[.] // null)}]
' "$ACFS_STATE_FILE" 2>/dev/null) || phases_json="[]"
# Build failure object if present with precise resume hint (bd-31ps.9.1)
local failed_phase
failed_phase=$(jq -r '.failed_phase // empty' "$ACFS_STATE_FILE" 2>/dev/null) || true
if [[ -n "$failed_phase" ]]; then
local resume_hint
resume_hint=$(generate_resume_hint "$failed_phase" "")
failure_json=$(jq -n \
--arg phase "$failed_phase" \
--arg step "$(jq -r '.failed_step // empty' "$ACFS_STATE_FILE" 2>/dev/null)" \
--arg error "$(jq -r '.failed_error // empty' "$ACFS_STATE_FILE" 2>/dev/null)" \
--arg resume_hint "$resume_hint" \
'{phase: $phase, step: (if $step == "" then null else $step end), error: (if $error == "" then null else $error end), resume_hint: $resume_hint}')
fi
fi
# Get Ubuntu version
local ubuntu_version="unknown"
if command -v lsb_release &>/dev/null; then
ubuntu_version=$(lsb_release -rs 2>/dev/null) || ubuntu_version="unknown"
fi
# Construct the summary JSON
jq -n \
--argjson schema_version 1 \
--arg status "$status" \
--arg timestamp "$(date -Iseconds)" \
--argjson total_seconds "$total_seconds" \
--arg acfs_version "${ACFS_VERSION:-unknown}" \
--arg mode "${MODE:-unknown}" \
--arg ubuntu_version "$ubuntu_version" \
--arg target_user "${TARGET_USER:-unknown}" \
--arg target_home "${TARGET_HOME:-unknown}" \
--argjson phases "$phases_json" \
--argjson failure "$failure_json" \
--arg log_file "${ACFS_LOG_FILE:-}" \
'{
schema_version: $schema_version,
status: $status,
timestamp: $timestamp,
total_seconds: $total_seconds,
environment: {
acfs_version: $acfs_version,
mode: $mode,
ubuntu_version: $ubuntu_version,
target_user: $target_user,
target_home: $target_home
},
phases: $phases,
failure: $failure,
log_file: (if $log_file != "" then $log_file else null end)
}' > "$ACFS_SUMMARY_FILE" 2>/dev/null || return 1
# Fix ownership so target user can read
if [[ -n "${TARGET_USER:-}" ]] && [[ "$(id -u)" -eq 0 ]]; then
chown "${TARGET_USER}:${TARGET_USER}" "$ACFS_SUMMARY_FILE" 2>/dev/null || true
fi
log_detail "Summary: $ACFS_SUMMARY_FILE"
}
# ============================================================
# Resume Hint Generation (bd-31ps.9.1)
# ============================================================
# Generates a precise, copyable command to resume installation from failure.
# Includes all relevant flags to reproduce the original invocation.
generate_resume_hint() {
local failed_phase="${1:-}"
local failed_step="${2:-}"
# Start with base command
local cmd=""
# Prefer curl|bash one-liner for curl invocations; local script for local runs
if [[ -z "${SCRIPT_DIR:-}" ]]; then
# curl|bash invocation - use one-liner format
cmd="curl -sSL"
if [[ -n "${ACFS_COMMIT_SHA_FULL:-}" ]]; then
# Pin to exact commit SHA for reproducibility
cmd="$cmd https://raw.githubusercontent.com/deepakdgupta1/agentic-coding/${ACFS_COMMIT_SHA_FULL}/install.sh"
elif [[ -n "${ACFS_REF_INPUT:-}" && "${ACFS_REF_INPUT}" != "main" ]]; then
cmd="$cmd https://raw.githubusercontent.com/deepakdgupta1/agentic-coding/${ACFS_REF_INPUT}/install.sh"
else
cmd="$cmd https://acfs.sh"
fi
cmd="$cmd | bash -s --"
else
# Local script invocation
cmd="bash install.sh"
fi
# Always add --resume flag (skips completed phases via state.json)
cmd="$cmd --resume"
# Add mode if not default
if [[ "${MODE:-vibe}" != "vibe" ]]; then
cmd="$cmd --mode $MODE"
fi
# Add skip flags that were used
[[ "${SKIP_POSTGRES:-false}" == "true" ]] && cmd="$cmd --skip-postgres"
[[ "${SKIP_VAULT:-false}" == "true" ]] && cmd="$cmd --skip-vault"
[[ "${SKIP_CLOUD:-false}" == "true" ]] && cmd="$cmd --skip-cloud"
[[ "${SKIP_PREFLIGHT:-false}" == "true" ]] && cmd="$cmd --skip-preflight"
[[ "${SKIP_UBUNTU_UPGRADE:-false}" == "true" ]] && cmd="$cmd --skip-ubuntu-upgrade"
# Add --yes if original run was non-interactive
[[ "${YES_MODE:-false}" == "true" ]] && cmd="$cmd --yes"
# Add --strict if it was set
[[ "${ACFS_STRICT_MODE:-false}" == "true" ]] && cmd="$cmd --strict"
echo "$cmd"
}
# Print the resume hint with explanation and copyable block
print_resume_hint() {
local failed_phase="${1:-}"
local failed_step="${2:-}"
local resume_cmd=""
resume_cmd=$(generate_resume_hint "${failed_phase:-}" "${failed_step:-}" 2>/dev/null) || resume_cmd="bash install.sh --resume --yes"
log_info ""
log_info "╔══════════════════════════════════════════════════════════════╗"
log_info "║ To resume installation from this point: ║"
log_info "╚══════════════════════════════════════════════════════════════╝"
log_info ""
log_info " ${resume_cmd:-bash install.sh --resume --yes}"
log_info ""
if [[ -n "${failed_phase:-}" ]]; then
log_detail "Failed phase: ${failed_phase:-}"
fi
if [[ -n "${failed_step:-}" ]]; then
log_detail "Failed step: ${failed_step:-}"
fi
# Also update the summary JSON with the precise resume hint.
# Wrap mktemp in || return 0: if /tmp is full, mktemp fails but
# cleanup must not abort — the user still needs to see the hint.
if [[ -f "${ACFS_STATE_FILE:-}" ]] && command -v jq &>/dev/null; then
local tmp_state=""
tmp_state=$(mktemp 2>/dev/null) || return 0
if jq --arg hint "${resume_cmd:-}" '.resume_hint = $hint' "${ACFS_STATE_FILE:-}" > "$tmp_state" 2>/dev/null; then
mv "$tmp_state" "${ACFS_STATE_FILE:-}" 2>/dev/null || true
else
rm -f "${tmp_state:-}" 2>/dev/null || true
fi
fi
}
# ============================================================
# Error handling
# ============================================================
# Track whether cleanup was triggered by a signal (not a normal EXIT).
_ACFS_SIGNAL_RECEIVED=""
_acfs_signal_handler() {
_ACFS_SIGNAL_RECEIVED="$1"
# Exit with 128+signum (standard convention) to trigger the EXIT trap.
case "$1" in
TERM) exit 143 ;;
INT) exit 130 ;;
HUP) exit 129 ;;
*) exit 1 ;;
esac
}
cleanup() {
# Capture exit code FIRST, before any other commands can overwrite $?
local exit_code=$?
# Cleanup must never abort — disable errexit for the entire function.
set +e
# If a signal triggered this cleanup, mark state as interrupted so
# resume logic does not see a partially-started phase.
if [[ -n "${_ACFS_SIGNAL_RECEIVED:-}" ]]; then
if type -t state_mark_interrupted &>/dev/null; then
state_mark_interrupted 2>/dev/null || true
fi
fi
if [[ $exit_code -ne 0 ]]; then
log_error ""
if [[ "${SMOKE_TEST_FAILED:-false}" == "true" ]]; then
log_error "ACFS installation completed, but the post-install smoke test failed."
else
log_error "ACFS installation failed!"
fi
log_error ""
log_error "To debug:"
if [[ -n "${ACFS_LOG_FILE:-}" ]] && [[ -f "${ACFS_LOG_FILE:-}" ]]; then
log_error " 1. Check the log: cat ${ACFS_LOG_FILE:-}"
elif [[ -n "${ACFS_LOG_DIR:-}" ]] && [[ -d "${ACFS_LOG_DIR:-}" ]]; then
log_error " 1. Check the log: cat ${ACFS_LOG_DIR:-}/install.log"
else
log_error " 1. Re-run with ACFS_DEBUG=true for detailed output"
fi
log_error " 2. If installed, run: acfs doctor (try as ${TARGET_USER:-ubuntu})"
log_error " (If you ran the installer as root: sudo -u ${TARGET_USER:-ubuntu} -i bash -lc 'acfs doctor')"
log_error ""
# Print precise resume hint if available (bd-31ps.9.1)
# Get failed phase from state if available
local failed_phase=""
local failed_step=""
if [[ -f "${ACFS_STATE_FILE:-}" ]] && command -v jq &>/dev/null; then
failed_phase=$(jq -r '.failed_phase // empty' "${ACFS_STATE_FILE:-}" 2>/dev/null) || true
failed_step=$(jq -r '.failed_step // empty' "${ACFS_STATE_FILE:-}" 2>/dev/null) || true
fi
print_resume_hint "${failed_phase:-}" "${failed_step:-}"
log_error ""
# Emit failure summary (best-effort)
acfs_summary_emit "failure" 0 2>/dev/null || true
# Send webhook notification for failure (bd-2zqr)
if type -t webhook_notify &>/dev/null; then
webhook_notify "failure" "${ACFS_SUMMARY_FILE:-}" 2>/dev/null || true
fi
# Send ntfy.sh notification for failure (bd-2igt6)
if type -t acfs_notify_install_failure &>/dev/null; then