-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun
More file actions
executable file
·2101 lines (1904 loc) · 69.3 KB
/
run
File metadata and controls
executable file
·2101 lines (1904 loc) · 69.3 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
# AgentGate CLI - Single entry point for development and operations
# Uses gum (https://github.com/charmbracelet/gum) for interactive UI
# Falls back to plain text if gum is not installed
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
# ---------------------------------------------------------------------------
# Theme: Supabase Dark
# ---------------------------------------------------------------------------
C_PRIMARY="#3ECF8E"
C_BORDER="#2A2A2A"
C_TEXT="#EDEDED"
C_MUTED="#8F8F8F"
C_ERROR="#F87171"
C_WARNING="#FBBF24"
# ANSI fallback colors
RESET='\033[0m'
BOLD='\033[1m'
DIM='\033[2m'
GREEN='\033[32m'
RED='\033[31m'
YELLOW='\033[33m'
CYAN='\033[36m'
VERSION="$(sed -n 's/^version = "\(.*\)"/\1/p' "$SCRIPT_DIR/pyproject.toml" | head -n 1)"
if [[ -z "$VERSION" ]]; then
VERSION="unknown"
fi
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-$RANDOM"
CONTAINER_TRACKING_DIR="$SCRIPT_DIR/tests/artifacts/operations/container_lifecycle"
MIGRATIONS_APPLIED=false
# ---------------------------------------------------------------------------
# Gum detection
# ---------------------------------------------------------------------------
HAS_GUM=false
if command -v gum &>/dev/null; then
HAS_GUM=true
fi
# ---------------------------------------------------------------------------
# Utility helpers
# ---------------------------------------------------------------------------
info() {
if $HAS_GUM; then
gum style --foreground "$C_PRIMARY" " $1"
else
echo -e "${GREEN} $1${RESET}"
fi
}
warn() {
if $HAS_GUM; then
gum style --foreground "$C_WARNING" " $1"
else
echo -e "${YELLOW} $1${RESET}"
fi
}
err() {
if $HAS_GUM; then
gum style --foreground "$C_ERROR" " $1"
else
echo -e "${RED} $1${RESET}" >&2
fi
}
muted() {
if $HAS_GUM; then
gum style --foreground "$C_MUTED" " $1"
else
echo -e "${DIM} $1${RESET}"
fi
}
banner() {
echo ""
if $HAS_GUM; then
gum style \
--foreground "$C_PRIMARY" \
--bold \
--margin "0 2" \
" agentgate"
gum style \
--foreground "$C_MUTED" \
--margin "0 2" \
" v${VERSION} -- AI Agent Security Middleware"
else
echo -e " ${BOLD}${GREEN}agentgate${RESET}"
echo -e " ${DIM}v${VERSION} -- AI Agent Security Middleware${RESET}"
fi
echo ""
}
confirm_action() {
local prompt="$1"
if $HAS_GUM; then
gum confirm \
--prompt.foreground "$C_TEXT" \
--selected.background "$C_PRIMARY" \
--selected.foreground "#000000" \
"$prompt"
else
echo -en "${YELLOW} $prompt [y/N] ${RESET}"
read -r answer
[[ "$answer" =~ ^[Yy]$ ]]
fi
}
spin() {
local title="$1"
shift
if $HAS_GUM; then
gum spin \
--spinner dot \
--spinner.foreground "$C_PRIMARY" \
--title "$title" \
-- "$@"
else
echo -e "${CYAN} $title${RESET}"
"$@"
fi
}
compose_project_name() {
if [[ -n "${COMPOSE_PROJECT_NAME:-}" ]]; then
echo "$COMPOSE_PROJECT_NAME"
return 0
fi
basename "$SCRIPT_DIR" | tr '[:upper:]' '[:lower:]'
}
record_container_event() {
local command_name="$1"
local phase="$2"
local note="${3:-}"
local project_name
project_name="$(compose_project_name)"
mkdir -p "$CONTAINER_TRACKING_DIR"
local python_bin="python3"
if [[ -x "$SCRIPT_DIR/.venv/bin/python" ]]; then
python_bin="$SCRIPT_DIR/.venv/bin/python"
fi
"$python_bin" - "$CONTAINER_TRACKING_DIR" "$RUN_ID" \
"$command_name" "$phase" "$project_name" "$note" <<'PY'
import json
import subprocess
import sys
import uuid
from datetime import datetime, timezone
from pathlib import Path
def _run(command: list[str]) -> str:
try:
completed = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
)
except OSError:
return ""
if completed.returncode != 0:
return ""
return completed.stdout
def _parse_json_lines(raw: str) -> list[dict]:
parsed: list[dict] = []
for line in raw.splitlines():
line = line.strip()
if not line:
continue
try:
value = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(value, dict):
parsed.append(value)
return parsed
output_dir = Path(sys.argv[1])
run_id = sys.argv[2]
command_name = sys.argv[3]
phase = sys.argv[4]
project_name = sys.argv[5]
note = sys.argv[6]
timestamp_utc = datetime.now(timezone.utc).isoformat()
compose_ps = _parse_json_lines(_run(["docker", "compose", "ps", "--format", "json"]))
docker_ps = _parse_json_lines(_run(["docker", "ps", "--format", "{{json .}}"]))
project_volumes = _parse_json_lines(
_run(
[
"docker",
"volume",
"ls",
"--filter",
f"label=com.docker.compose.project={project_name}",
"--format",
"{{json .}}",
]
)
)
health_counts = {
"healthy": 0,
"unhealthy": 0,
"starting": 0,
"unknown": 0,
}
for row in compose_ps:
health = str(row.get("Health") or "").strip().lower()
if health == "healthy":
health_counts["healthy"] += 1
continue
if health == "unhealthy":
health_counts["unhealthy"] += 1
continue
if health == "starting":
health_counts["starting"] += 1
continue
health_counts["unknown"] += 1
event = {
"event_id": str(uuid.uuid4()),
"timestamp_utc": timestamp_utc,
"run_id": run_id,
"command": command_name,
"phase": phase,
"project_name": project_name,
"cwd": str(Path.cwd()),
"note": note,
"compose_containers": compose_ps,
"runtime_containers": docker_ps,
"project_volumes": project_volumes,
"summary": {
"compose_container_count": len(compose_ps),
"runtime_container_count": len(docker_ps),
"project_volume_count": len(project_volumes),
"health": health_counts,
},
}
events_file = output_dir / "events.jsonl"
with events_file.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(event, sort_keys=True) + "\n")
latest_file = output_dir / "latest.json"
latest_file.write_text(json.dumps(event, indent=2, sort_keys=True), encoding="utf-8")
PY
}
run_db_migrations() {
local db_user="${POSTGRES_USER:-agentgate}"
local db_name="${POSTGRES_DB:-agentgate}"
local users_exists
local principal_id_exists
local alembic_exists
users_exists=$(
docker compose exec -T db psql -U "$db_user" -d "$db_name" -tAc \
"SELECT CASE WHEN to_regclass('public.users') IS NULL THEN '0' ELSE '1' END;" \
2>/dev/null | tr -d '[:space:]'
)
if [[ "$users_exists" != "1" ]]; then
MIGRATIONS_APPLIED=false
info "Skipping Alembic: bootstrap schema not initialized yet."
return 0
fi
principal_id_exists=$(
docker compose exec -T db psql -U "$db_user" -d "$db_name" -tAc \
"SELECT CASE WHEN EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema='public' AND table_name='users' AND column_name='principal_id'
) THEN '1' ELSE '0' END;" \
2>/dev/null | tr -d '[:space:]'
)
alembic_exists=$(
docker compose exec -T db psql -U "$db_user" -d "$db_name" -tAc \
"SELECT CASE WHEN to_regclass('public.alembic_version') IS NULL THEN '0' ELSE '1' END;" \
2>/dev/null | tr -d '[:space:]'
)
if [[ "$alembic_exists" != "1" && "$principal_id_exists" == "1" ]]; then
MIGRATIONS_APPLIED=false
info "Skipping Alembic: schema already includes identity columns."
return 0
fi
if [[ "$principal_id_exists" != "1" ]]; then
info "Reconciling legacy identity schema columns..."
if docker compose exec -T db psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" <<'SQL' >/tmp/agentgate_schema_patch.log 2>&1
ALTER TABLE IF EXISTS users ADD COLUMN IF NOT EXISTS principal_id VARCHAR(64);
ALTER TABLE IF EXISTS users ADD COLUMN IF NOT EXISTS identity_provider VARCHAR(64) DEFAULT 'local';
ALTER TABLE IF EXISTS users ADD COLUMN IF NOT EXISTS provider_subject VARCHAR(255);
ALTER TABLE IF EXISTS users ADD COLUMN IF NOT EXISTS tenant_id VARCHAR(128) DEFAULT 'default';
CREATE INDEX IF NOT EXISTS ix_users_principal_id ON users (principal_id);
CREATE INDEX IF NOT EXISTS ix_users_identity_provider ON users (identity_provider);
CREATE INDEX IF NOT EXISTS ix_users_provider_subject ON users (provider_subject);
CREATE INDEX IF NOT EXISTS ix_users_tenant_id ON users (tenant_id);
ALTER TABLE IF EXISTS pii_sessions ADD COLUMN IF NOT EXISTS tenant_id VARCHAR(128) DEFAULT 'default';
ALTER TABLE IF EXISTS pii_sessions ADD COLUMN IF NOT EXISTS principal_id VARCHAR(64);
CREATE INDEX IF NOT EXISTS ix_pii_sessions_tenant_id ON pii_sessions (tenant_id);
CREATE INDEX IF NOT EXISTS ix_pii_sessions_principal_id ON pii_sessions (principal_id);
SQL
then
MIGRATIONS_APPLIED=true
info "Legacy identity schema reconciliation completed."
return 0
fi
err "Legacy identity schema reconciliation failed."
muted "Schema patch log:"
sed -n '1,120p' /tmp/agentgate_schema_patch.log
return 1
fi
info "Applying database migrations (alembic upgrade head)..."
if docker compose run --rm --no-deps server \
/app/.venv/bin/python -m alembic -c /app/alembic.ini upgrade head \
>/tmp/agentgate_migrate.log 2>&1; then
MIGRATIONS_APPLIED=true
info "Database migrations completed."
return 0
fi
err "Database migrations failed."
muted "Migration log:"
sed -n '1,120p' /tmp/agentgate_migrate.log
return 1
}
# ---------------------------------------------------------------------------
# Env loading
# ---------------------------------------------------------------------------
load_env_file_exports() {
local env_file="$1"
if [[ ! -f "$env_file" ]]; then
return 0
fi
# shellcheck disable=SC1090
set -a
source "$env_file"
set +a
}
# ---------------------------------------------------------------------------
# .env auto-setup
# ---------------------------------------------------------------------------
setup_env() {
local changed=false
if [[ ! -f "$SCRIPT_DIR/.env" ]]; then
if [[ -f "$SCRIPT_DIR/.env.example" ]]; then
cp "$SCRIPT_DIR/.env.example" "$SCRIPT_DIR/.env"
local secret_key
secret_key=$(openssl rand -hex 32 2>/dev/null || python3 -c "import secrets; print(secrets.token_hex(32))")
local nextauth_secret
nextauth_secret=$(openssl rand -hex 32 2>/dev/null || python3 -c "import secrets; print(secrets.token_hex(32))")
local postgres_pw
postgres_pw=$(openssl rand -hex 16 2>/dev/null || python3 -c "import secrets; print(secrets.token_hex(16))")
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' "s/your-secret-key-here/$secret_key/" "$SCRIPT_DIR/.env"
sed -i '' "s/your-nextauth-secret-here/$nextauth_secret/" "$SCRIPT_DIR/.env"
sed -i '' "s/generate-secure-password-here/$postgres_pw/" "$SCRIPT_DIR/.env"
else
sed -i "s/your-secret-key-here/$secret_key/" "$SCRIPT_DIR/.env"
sed -i "s/your-nextauth-secret-here/$nextauth_secret/" "$SCRIPT_DIR/.env"
sed -i "s/generate-secure-password-here/$postgres_pw/" "$SCRIPT_DIR/.env"
fi
info "Created .env with generated secrets"
changed=true
# If a postgres volume already exists, the new random password
# won't match the one baked into it.
local vol_name
vol_name=$(docker volume ls -q 2>/dev/null \
| grep -E "agentgate.*postgres" || true)
if [[ -n "$vol_name" ]]; then
warn "Existing PostgreSQL volume detected ($vol_name)."
warn "The new .env has a fresh password that won't"
warn "match the one stored in the volume."
echo ""
muted "Keeping existing volume by default to preserve user credentials."
muted "If you intentionally need a full reset, run: ./run clean --wipe-data"
echo ""
fi
fi
fi
if [[ ! -f "$SCRIPT_DIR/server/.env" ]]; then
if [[ -f "$SCRIPT_DIR/server/.env.example" ]]; then
cp "$SCRIPT_DIR/server/.env.example" "$SCRIPT_DIR/server/.env"
local server_secret
server_secret=$(openssl rand -hex 32 2>/dev/null || python3 -c "import secrets; print(secrets.token_hex(32))")
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' "s/your-secret-key-change-this/$server_secret/" "$SCRIPT_DIR/server/.env"
else
sed -i "s/your-secret-key-change-this/$server_secret/" "$SCRIPT_DIR/server/.env"
fi
info "Created server/.env with generated secret"
changed=true
fi
fi
if [[ ! -f "$SCRIPT_DIR/dashboard/.env" ]]; then
if [[ -f "$SCRIPT_DIR/dashboard/.env.example" ]]; then
cp "$SCRIPT_DIR/dashboard/.env.example" "$SCRIPT_DIR/dashboard/.env"
local dash_secret
dash_secret=$(openssl rand -hex 32 2>/dev/null || python3 -c "import secrets; print(secrets.token_hex(32))")
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' "s/your-secret-key-here-minimum-32-characters/$dash_secret/" "$SCRIPT_DIR/dashboard/.env"
else
sed -i "s/your-secret-key-here-minimum-32-characters/$dash_secret/" "$SCRIPT_DIR/dashboard/.env"
fi
info "Created dashboard/.env with generated secret"
changed=true
fi
fi
if $changed; then
echo ""
fi
# Load environment values for run-managed processes.
load_env_file_exports "$SCRIPT_DIR/.env"
load_env_file_exports "$SCRIPT_DIR/server/.env"
load_env_file_exports "$SCRIPT_DIR/dashboard/.env"
}
# ---------------------------------------------------------------------------
# open_url - cross-platform browser open
# ---------------------------------------------------------------------------
open_url() {
local url="$1"
if command -v open &>/dev/null; then
open "$url"
elif command -v xdg-open &>/dev/null; then
xdg-open "$url"
elif command -v wslview &>/dev/null; then
wslview "$url"
else
info "Open in your browser: $url"
fi
}
# ---------------------------------------------------------------------------
# wait_for_health - poll an endpoint until it responds with expected content
# ---------------------------------------------------------------------------
wait_for_health() {
local url="$1"
local name="$2"
local max_attempts="${3:-60}"
local attempt=0
while [[ $attempt -lt $max_attempts ]]; do
local body
body=$(curl -sf "$url" 2>/dev/null || true)
if [[ -n "$body" ]]; then
# For the API, verify it returns AgentGate's health signature
if [[ "$url" == *"/api/health"* ]]; then
if echo "$body" | grep -q '"status"'; then
return 0
fi
else
# Dashboard just needs to respond
return 0
fi
fi
attempt=$((attempt + 1))
sleep 2
done
err "$name did not become healthy after $((max_attempts * 2))s"
return 1
}
# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
cmd_demo() {
local fresh=false
local no_open=false
record_container_event "demo" "start" "demo command invoked"
while [[ $# -gt 0 ]]; do
case "$1" in
--fresh|--from-zero)
fresh=true
shift
;;
--no-open)
no_open=true
shift
;;
*)
err "Unknown demo option: $1"
muted "Usage: ./run demo [--fresh|--from-zero] [--no-open]"
return 1
;;
esac
done
if $fresh; then
warn "Fresh mode enabled: removing existing containers and volumes."
docker compose down -v --remove-orphans >/dev/null 2>&1 || true
docker compose --profile test down -v --remove-orphans >/dev/null 2>&1 || true
local project_name
project_name="$(compose_project_name)"
local lingering_volumes
lingering_volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project_name" || true)
if [[ -n "$lingering_volumes" ]]; then
echo "$lingering_volumes" | xargs -r docker volume rm -f >/dev/null 2>&1 || true
fi
record_container_event "demo" "after_fresh_reset" "fresh reset completed"
info "Docker state reset complete."
echo ""
fi
if ! $fresh; then
local runtime_volume
runtime_volume=$(docker volume ls --format '{{.Name}}' 2>/dev/null | \
grep -E '(^agentgate_postgres_data$|_postgres_data$)' || true)
if [[ -n "$runtime_volume" ]]; then
warn "Existing PostgreSQL volume detected. Persisted data will be reused."
muted "Use './run demo --fresh' for deterministic zero-state startup."
echo ""
fi
fi
info "Starting full stack with Docker Compose..."
echo ""
local compose_exit=0
# Use compact progress output to reduce verbosity
export BUILDKIT_PROGRESS=plain
if $HAS_GUM; then
gum spin \
--spinner dot \
--spinner.foreground "$C_PRIMARY" \
--title "Building and starting containers..." \
-- docker compose up -d --build \
|| compose_exit=$?
else
echo -e "${CYAN} Building and starting containers...${RESET}"
docker compose up -d --build 2>&1 | \
grep -v "^#" | \
grep -v "=>" | \
grep -v "transferring" | \
cat
compose_exit=${PIPESTATUS[0]}
fi
if [[ $compose_exit -ne 0 ]]; then
record_container_event "demo" "compose_failed" "docker compose up returned non-zero"
echo ""
err "Docker Compose failed (exit $compose_exit)."
# Check for common causes
if ! docker info &>/dev/null 2>&1; then
err "Docker daemon is not running. Start Docker Desktop and retry."
elif docker compose logs server 2>/dev/null \
| tail -5 | grep -qi "password\|auth"; then
err "Database authentication failed."
err "The password in .env doesn't match the existing volume."
muted "Fix: ./run clean (removes volumes, then re-run ./run demo)"
else
muted "Check logs: ./run logs"
fi
return 1
fi
record_container_event "demo" "after_compose_up" "containers built and started"
if ! run_db_migrations; then
record_container_event "demo" "migration_failed" "alembic upgrade head failed"
return 1
fi
record_container_event "demo" "after_migrations" "alembic upgrade head completed"
if $MIGRATIONS_APPLIED; then
info "Restarting API server after migrations..."
docker compose restart server >/dev/null 2>&1 || true
fi
echo ""
info "Waiting for services to become healthy..."
echo ""
local server_ok=false
local dash_ok=false
if $HAS_GUM; then
gum spin \
--spinner dot \
--spinner.foreground "$C_PRIMARY" \
--title "Waiting for API server (port 8000)..." \
-- bash -c "$(declare -f wait_for_health); wait_for_health http://localhost:8000/api/health 'API Server' 60" \
&& server_ok=true
else
echo -e "${CYAN} Waiting for API server (port 8000)...${RESET}"
if wait_for_health "http://localhost:8000/api/health" "API Server" 60; then
server_ok=true
fi
fi
if $server_ok; then
info "API server is healthy"
else
err "API server failed to start"
fi
if $HAS_GUM; then
gum spin \
--spinner dot \
--spinner.foreground "$C_PRIMARY" \
--title "Waiting for Dashboard (port 3000)..." \
-- bash -c "$(declare -f wait_for_health); wait_for_health http://localhost:3000 Dashboard 60" \
&& dash_ok=true
else
echo -e "${CYAN} Waiting for Dashboard (port 3000)...${RESET}"
if wait_for_health "http://localhost:3000" "Dashboard" 60; then
dash_ok=true
fi
fi
if $dash_ok; then
info "Dashboard is healthy"
else
err "Dashboard failed to start"
fi
echo ""
if $server_ok && $dash_ok; then
record_container_event "demo" "healthy" "api and dashboard healthy"
info "AgentGate is running!"
echo ""
muted " Dashboard: http://localhost:3000"
muted " API Docs: http://localhost:8000/docs"
muted " Health: http://localhost:8000/api/health"
echo ""
muted " First-time setup: open /setup and create the initial admin account"
echo ""
if ! $no_open; then
open_url "http://localhost:3000"
fi
muted "Runtime tracking: $CONTAINER_TRACKING_DIR/latest.json"
muted "Run ID: $RUN_ID"
else
record_container_event "demo" "unhealthy" "one or more services failed health checks"
err "Some services failed to start. Run './run logs' to investigate."
fi
}
cmd_dev() {
info "Starting local development servers..."
echo ""
muted "Backend: http://localhost:8000 (uvicorn --reload)"
muted "Dashboard: http://localhost:3000 (next dev)"
echo ""
# Determine python executable
local python_cmd="python3"
if [[ -f "$SCRIPT_DIR/.venv/bin/python" ]]; then
python_cmd="$SCRIPT_DIR/.venv/bin/python"
fi
# Start backend in background
info "Starting backend..."
cd "$SCRIPT_DIR"
$python_cmd -m uvicorn server.main:app \
--reload \
--host 0.0.0.0 \
--port 8000 &
local backend_pid=$!
# Start dashboard in background
info "Starting dashboard..."
cd "$SCRIPT_DIR/dashboard"
npm run dev &
local dashboard_pid=$!
cd "$SCRIPT_DIR"
echo ""
info "Both servers running. Press Ctrl+C to stop."
muted "Backend PID: $backend_pid"
muted "Dashboard PID: $dashboard_pid"
echo ""
# Trap SIGINT/SIGTERM to kill both
trap 'echo ""; info "Shutting down..."; kill $backend_pid $dashboard_pid 2>/dev/null; wait $backend_pid $dashboard_pid 2>/dev/null; info "Stopped."; exit 0' INT TERM
# Wait for either to exit
wait -n $backend_pid $dashboard_pid 2>/dev/null || true
warn "A server exited. Stopping remaining processes..."
kill $backend_pid $dashboard_pid 2>/dev/null || true
wait $backend_pid $dashboard_pid 2>/dev/null || true
}
cmd_test() {
exec "$SCRIPT_DIR/test" "$@"
}
cmd_verify_formal_chaos() {
local mode="${1:-single}"
shift || true
local python_bin="python3"
if [[ -x "$SCRIPT_DIR/.venv/bin/python" ]]; then
python_bin="$SCRIPT_DIR/.venv/bin/python"
fi
local runner="$SCRIPT_DIR/scripts/run_chaos_verification.py"
if [[ ! -f "$runner" ]]; then
err "Chaos verification runner not found: $runner"
return 1
fi
case "$mode" in
single|parallel|custom)
info "Running chaos verification mode: $mode"
"$python_bin" "$runner" --mode "$mode" "$@"
;;
*)
err "Unknown chaos verification mode: $mode"
muted "Valid usage: ./run verify formal chaos [single|parallel|custom] [options]"
return 1
;;
esac
}
cmd_verify() {
local domain="formal"
local subcommand="latest"
local -a sub_args=()
if [[ $# -gt 0 ]]; then
case "$1" in
formal|mcp)
domain="$1"
shift
;;
esac
fi
if [[ $# -gt 0 ]]; then
subcommand="$1"
shift
fi
sub_args=("$@")
if [[ "$domain" == "mcp" ]]; then
cmd_verify_mcp "$subcommand" "${sub_args[@]}"
return
fi
local artifacts_dir="$SCRIPT_DIR/tests/artifacts"
local algorithm_dir="$artifacts_dir/algorithm"
local formal_dir="$algorithm_dir/formal_verification"
local latest_dir="$formal_dir/latest"
local history_dir="$formal_dir/history"
local legacy_latest_dir="$artifacts_dir/latest"
local legacy_history_dir="$artifacts_dir/history"
local latest_link_dir="$artifacts_dir/chaos_verification_latest"
local legacy_latest_link_dir="$artifacts_dir/chaos_latest"
local json_name="chaos_verification_results.json"
local legacy_json_name="chaos_campaign_results.json"
if [[ ! -d "$latest_dir" && -d "$legacy_latest_dir" ]]; then
latest_dir="$legacy_latest_dir"
fi
if [[ ! -d "$latest_dir" && -L "$latest_link_dir" ]]; then
latest_dir="$latest_link_dir"
fi
if [[ ! -d "$latest_dir" && -L "$legacy_latest_link_dir" ]]; then
latest_dir="$legacy_latest_link_dir"
fi
if [[ ! -d "$history_dir" && -d "$legacy_history_dir" ]]; then
history_dir="$legacy_history_dir"
fi
case "$subcommand" in
chaos)
cmd_verify_formal_chaos "${sub_args[@]}"
;;
latest)
if [[ ! -d "$latest_dir" ]]; then
err "Canonical latest verification artifacts not found."
muted "Run verification suite first (500K profile) to publish latest."
return 1
fi
info "Canonical latest verification artifacts"
muted "Directory: $latest_dir"
if [[ -f "$latest_dir/source_run.txt" ]]; then
muted "Source run: $(tr -d '\n' < "$latest_dir/source_run.txt")"
fi
echo ""
if [[ -f "$latest_dir/SUMMARY.txt" ]]; then
cat "$latest_dir/SUMMARY.txt"
else
warn "SUMMARY.txt is missing in canonical latest."
fi
;;
json)
if [[ ! -f "$latest_dir/$json_name" && ! -f "$latest_dir/$legacy_json_name" ]]; then
err "Canonical latest JSON results are missing."
return 1
fi
if [[ -f "$latest_dir/$json_name" ]]; then
python3 -m json.tool "$latest_dir/$json_name"
else
python3 -m json.tool "$latest_dir/$legacy_json_name"
fi
;;
history)
if [[ ! -d "$history_dir" ]]; then
warn "No history directory exists yet."
return 0
fi
info "Archived canonical latest snapshots"
find "$history_dir" -mindepth 1 -maxdepth 1 -type d \
| sort -r \
| head -n 20 \
| sed "s#^$SCRIPT_DIR/##"
;;
path)
echo "$latest_dir"
;;
run)
local python_bin="python3"
if [[ -x "$SCRIPT_DIR/.venv/bin/python" ]]; then
python_bin="$SCRIPT_DIR/.venv/bin/python"
fi
local runner="$SCRIPT_DIR/scripts/run_policy_governance_journey.py"
if [[ ! -f "$runner" ]]; then
err "Formal runtime forensic runner not found: $runner"
return 1
fi
info "Running formal runtime forensic campaign..."
"$python_bin" "$runner" "${sub_args[@]}"
;;
scrub)
local python_bin="python3"
if [[ -x "$SCRIPT_DIR/.venv/bin/python" ]]; then
python_bin="$SCRIPT_DIR/.venv/bin/python"
fi
local scrubber="$SCRIPT_DIR/scripts/scrub_formal_artifacts.py"
if [[ ! -f "$scrubber" ]]; then
err "Formal artifact scrubber not found: $scrubber"
return 1
fi
info "Scrubbing and verifying formal artifacts for sharing..."
"$python_bin" "$scrubber" "${sub_args[@]}"
;;
organize)
local python_bin="python3"
if [[ -x "$SCRIPT_DIR/.venv/bin/python" ]]; then
python_bin="$SCRIPT_DIR/.venv/bin/python"
fi
local organizer="$SCRIPT_DIR/scripts/organize_policy_governance_artifacts.py"
if [[ ! -f "$organizer" ]]; then
err "Artifact organizer not found: $organizer"
return 1
fi
info "Organizing policy-governance artifacts into canonical layout..."
"$python_bin" "$organizer" "${sub_args[@]}"
;;
report)
local python_bin="python3"
if [[ -x "$SCRIPT_DIR/.venv/bin/python" ]]; then
python_bin="$SCRIPT_DIR/.venv/bin/python"
fi
local reporter="$SCRIPT_DIR/scripts/generate_policy_governance_report.py"
if [[ ! -f "$reporter" ]]; then
err "Formal verification report generator not found: $reporter"
return 1
fi
info "Generating policy-governance formal verification report package..."
"$python_bin" "$reporter" "${sub_args[@]}"
;;
*)
err "Unknown verify subcommand: $subcommand"
muted "Valid usage: ./run verify formal [chaos|latest|json|history|path|run|scrub|organize|report]"
return 1
;;
esac
}
cmd_verify_mcp() {
local subcommand="${1:-policy-validation}"
shift || true
local python_bin="python3"
if [[ -x "$SCRIPT_DIR/.venv/bin/python" ]]; then
python_bin="$SCRIPT_DIR/.venv/bin/python"
fi
local validator="$SCRIPT_DIR/scripts/validate_policy_governance_adapter.py"
local artifacts_root="$SCRIPT_DIR/tests/artifacts/algorithm/policy_governance_validation"
local scrubber="$SCRIPT_DIR/scripts/scrub_formal_artifacts.py"
case "$subcommand" in
policy-validation|ground-truth)
if [[ ! -f "$validator" ]]; then
err "MCP policy-governance validator not found: $validator"
return 1
fi
info "Running MCP policy-governance validator..."
"$python_bin" "$validator" "$@"
;;
latest)
if [[ ! -d "$artifacts_root" ]]; then
err "No MCP policy-governance validation artifacts found."
return 1
fi
local latest_dir
latest_dir=$(find "$artifacts_root" -mindepth 1 -maxdepth 1 -type d | sort -r | head -n 1)
if [[ -z "$latest_dir" ]]; then
err "No MCP policy-governance validation artifacts found."
return 1
fi
info "Latest MCP policy-governance validation artifact"
muted "Directory: $latest_dir"
if [[ -f "$latest_dir/SUMMARY.txt" ]]; then
echo ""
cat "$latest_dir/SUMMARY.txt"
fi
;;
history)
if [[ ! -d "$artifacts_root" ]]; then
warn "No MCP policy-governance validation history directory exists yet."
return 0
fi
find "$artifacts_root" -mindepth 1 -maxdepth 1 -type d | sort -r | head -n 30
;;
scrub)
if [[ ! -f "$scrubber" ]]; then
err "Formal artifact scrubber not found: $scrubber"
return 1
fi
local -a mapped_args=()
local idx=1
local args=("$@")
while [[ $idx -le ${#args[@]} ]]; do
local arg="${args[$((idx-1))]}"
if [[ "$arg" == "--source" ]]; then
idx=$((idx + 1))
if [[ $idx -gt ${#args[@]} ]]; then
err "Missing value for --source"
return 1
fi
mapped_args+=("--source-dir" "${args[$((idx-1))]}")
idx=$((idx + 1))
continue
fi
mapped_args+=("$arg")
idx=$((idx + 1))
done
info "Scrubbing MCP artifacts before sharing..."
"$python_bin" "$scrubber" "${mapped_args[@]}"
;;
*)
err "Unknown MCP verify subcommand: $subcommand"
muted "Valid usage: ./run verify mcp [policy-validation|latest|history|scrub]"
return 1
;;
esac
}
cmd_preprod_mcp_gate() {
local env_name="${AGENTGATE_ENV:-development}"
local profile="${MCP_POLICY_VALIDATION_PROFILE:-${MCP_GROUND_TRUTH_PROFILE:-dev}}"
local count="${MCP_POLICY_VALIDATION_COUNT:-${MCP_GROUND_TRUTH_COUNT:-10000}}"
if [[ "$env_name" == "staging" ]]; then
profile="staging"
elif [[ "$env_name" == "production" ]]; then
profile="prod-like"