-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmc-ctl
More file actions
executable file
·1294 lines (1140 loc) · 45.7 KB
/
mc-ctl
File metadata and controls
executable file
·1294 lines (1140 loc) · 45.7 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
# mc-ctl — Mission Control admin CLI
set -euo pipefail
PROJECT_DIR="/root/claude/mission-control"
SERVICE_NAME="mission-control"
DB_PATH="${PROJECT_DIR}/data/mc.db"
API_URL="http://localhost:8080"
HINDSIGHT_URL="http://localhost:8888"
HINDSIGHT_CONTAINER="crm-hindsight"
LOG_LINES=50
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
die() { echo -e "${RED}Error:${NC} $*" >&2; exit 1; }
need_db() {
[ -f "$DB_PATH" ] || die "Database not found: ${DB_PATH}"
}
sql() {
sqlite3 -header -column "$DB_PATH" "$1"
}
sql_raw() {
sqlite3 "$DB_PATH" "$1"
}
api_key() {
local env_file="${PROJECT_DIR}/.env"
[ -f "$env_file" ] || die ".env not found"
grep -oP '(?<=MC_API_KEY=).*' "$env_file" | tr -d '"' | tr -d "'"
}
api() {
local method="$1" path="$2"
shift 2
local key
key=$(api_key)
curl -sf -X "$method" -H "X-Api-Key: ${key}" -H "Content-Type: application/json" \
"${API_URL}${path}" "$@"
}
color_status() {
local status="$1"
case "$status" in
completed) echo -e "${GREEN}${status}${NC}" ;;
running|classifying) echo -e "${CYAN}${status}${NC}" ;;
pending|queued) echo -e "${YELLOW}${status}${NC}" ;;
failed|cancelled|blocked) echo -e "${RED}${status}${NC}" ;;
*) echo "$status" ;;
esac
}
# ---------------------------------------------------------------------------
# Service lifecycle
# ---------------------------------------------------------------------------
cmd_status() {
echo -e "${BOLD}=== Mission Control Status ===${NC}"
echo ""
# Service status: check systemd first, then fall back to process detection
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
echo -e " Service: ${GREEN}active${NC} (systemd)"
local pid
pid=$(systemctl show -p MainPID --value "$SERVICE_NAME" 2>/dev/null || echo "?")
echo -e " PID: ${pid}"
local uptime
uptime=$(systemctl show -p ActiveEnterTimestamp --value "$SERVICE_NAME" 2>/dev/null || echo "?")
echo -e " Since: ${uptime}"
if [ "$pid" != "?" ] && [ "$pid" != "0" ]; then
local mem
mem=$(ps -p "$pid" -o rss= 2>/dev/null || echo "0")
echo -e " Memory: $(( mem / 1024 )) MB"
fi
elif pid=$(pgrep -f 'tsx.*src/index\.ts' 2>/dev/null | tail -1) && [ -n "$pid" ]; then
echo -e " Service: ${GREEN}active${NC} (manual tsx, PID ${pid})"
local mem
mem=$(ps -p "$pid" -o rss= 2>/dev/null || echo "0")
echo -e " Memory: $(( mem / 1024 )) MB"
local started
started=$(ps -p "$pid" -o lstart= 2>/dev/null || echo "?")
echo -e " Since: ${started}"
else
echo -e " Service: ${RED}inactive${NC}"
fi
# API health
echo ""
local health
if health=$(curl -sf --max-time 3 "${API_URL}/health" 2>/dev/null); then
local api_status db_status inf_status version
api_status=$(echo "$health" | grep -oP '"status"\s*:\s*"\K[^"]+' || echo "?")
db_status=$(echo "$health" | grep -oP '"db"\s*:\s*"\K[^"]+' || echo "?")
inf_status=$(echo "$health" | grep -oP '"inference"\s*:\s*"\K[^"]+' || echo "?")
version=$(echo "$health" | grep -oP '"version"\s*:\s*"\K[^"]+' || echo "?")
echo -e " API: ${GREEN}reachable${NC} (v${version})"
echo -e " DB: $([ "$db_status" = "ok" ] && echo -e "${GREEN}ok${NC}" || echo -e "${RED}${db_status}${NC}")"
echo -e " Inference: $([ "$inf_status" = "ok" ] && echo -e "${GREEN}ok${NC}" || echo -e "${YELLOW}${inf_status}${NC}")"
else
echo -e " API: ${RED}unreachable${NC}"
fi
# Hindsight
echo ""
if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "$HINDSIGHT_CONTAINER"; then
local hs_health
if hs_health=$(curl -sf --max-time 3 "${HINDSIGHT_URL}/health" 2>/dev/null); then
echo -e " Hindsight: ${GREEN}healthy${NC}"
else
echo -e " Hindsight: ${YELLOW}container up, API unhealthy${NC}"
fi
else
echo -e " Hindsight: ${DIM}not running${NC}"
fi
# DB size
if [ -f "$DB_PATH" ]; then
local size
size=$(du -sh "$DB_PATH" 2>/dev/null | cut -f1)
echo -e " DB size: ${size}"
fi
# Key metrics
if [ -f "$DB_PATH" ]; then
echo ""
echo -e "${BOLD} Quick Metrics${NC}"
local total running completed failed
total=$(sql_raw "SELECT COUNT(*) FROM tasks;" 2>/dev/null || echo "0")
running=$(sql_raw "SELECT COUNT(*) FROM tasks WHERE status = 'running';" 2>/dev/null || echo "0")
completed=$(sql_raw "SELECT COUNT(*) FROM tasks WHERE status = 'completed';" 2>/dev/null || echo "0")
failed=$(sql_raw "SELECT COUNT(*) FROM tasks WHERE status = 'failed';" 2>/dev/null || echo "0")
echo -e " Tasks: ${total} total, ${GREEN}${completed}${NC} completed, ${CYAN}${running}${NC} running, ${RED}${failed}${NC} failed"
fi
echo ""
}
cmd_start() {
systemctl start "$SERVICE_NAME"
sleep 2
systemctl --no-pager status "$SERVICE_NAME" | head -15
}
cmd_stop() {
systemctl stop "$SERVICE_NAME"
echo -e "${GREEN}Service stopped.${NC}"
}
cmd_restart() {
systemctl restart "$SERVICE_NAME"
sleep 2
systemctl --no-pager status "$SERVICE_NAME" | head -15
}
cmd_logs() {
local lines="${1:-$LOG_LINES}"
journalctl -u "$SERVICE_NAME" --no-pager -n "$lines"
}
cmd_follow() {
journalctl -fu "$SERVICE_NAME"
}
# ---------------------------------------------------------------------------
# Tasks
# ---------------------------------------------------------------------------
cmd_tasks() {
need_db
local status_filter="" limit=20
while [[ $# -gt 0 ]]; do
case "$1" in
--status=*) status_filter="${1#--status=}"; shift ;;
--limit=*) limit="${1#--limit=}"; shift ;;
*) shift ;;
esac
done
local where=""
if [ -n "$status_filter" ]; then
where="WHERE status = '${status_filter}'"
fi
echo -e "${BOLD}=== Tasks (newest first, limit ${limit}) ===${NC}"
echo ""
sql "SELECT task_id, substr(title,1,50) as title, status, agent_type,
ROUND(CAST(
(julianday(COALESCE(completed_at, datetime('now'))) - julianday(created_at)) * 86400
AS REAL), 0) as secs,
created_at
FROM tasks ${where}
ORDER BY created_at DESC LIMIT ${limit};"
}
cmd_task() {
need_db
local id="$1"
[ -n "$id" ] || die "Usage: mc-ctl task <task_id>"
echo -e "${BOLD}=== Task Detail ===${NC}"
echo ""
sql "SELECT task_id, title, status, priority, agent_type, classification,
progress, spawn_type, parent_task_id,
created_at, started_at, completed_at,
substr(COALESCE(error,''),1,200) as error
FROM tasks WHERE task_id = '${id}';"
echo ""
echo -e "${BOLD}--- Output ---${NC}"
sql_raw "SELECT COALESCE(output, '(none)') FROM tasks WHERE task_id = '${id}';" 2>/dev/null
echo ""
echo -e "${BOLD}--- Runs ---${NC}"
sql "SELECT run_id, agent_type, status, phase, duration_ms, created_at
FROM runs WHERE task_id = '${id}' ORDER BY created_at;"
echo ""
echo -e "${BOLD}--- Subtasks ---${NC}"
sql "SELECT task_id, substr(title,1,40) as title, status, agent_type
FROM tasks WHERE parent_task_id = '${id}';"
}
cmd_cancel() {
local id="$1"
[ -n "$id" ] || die "Usage: mc-ctl cancel <task_id>"
local result
if result=$(api POST "/api/tasks/${id}/cancel"); then
echo -e "${GREEN}Task ${id} cancelled.${NC}"
echo "$result" | python3 -m json.tool 2>/dev/null || echo "$result"
else
die "Failed to cancel task ${id}. Is the API running?"
fi
}
# ---------------------------------------------------------------------------
# Outcomes
# ---------------------------------------------------------------------------
cmd_outcomes() {
need_db
local days=7
while [[ $# -gt 0 ]]; do
case "$1" in
--days=*) days="${1#--days=}"; shift ;;
*) shift ;;
esac
done
echo -e "${BOLD}=== Outcome Stats (last ${days} days) ===${NC}"
echo ""
echo -e "${BOLD}By Runner:${NC}"
sql "SELECT ran_on, COUNT(*) as total,
SUM(success) as ok,
ROUND(AVG(success)*100, 1) as success_pct,
ROUND(AVG(duration_ms)) as avg_ms
FROM task_outcomes
WHERE created_at >= datetime('now', '-${days} days')
GROUP BY ran_on
ORDER BY total DESC;"
echo ""
echo -e "${BOLD}By Classification:${NC}"
sql "SELECT classified_as, COUNT(*) as total,
SUM(success) as ok,
ROUND(AVG(success)*100, 1) as success_pct
FROM task_outcomes
WHERE created_at >= datetime('now', '-${days} days')
GROUP BY classified_as
ORDER BY total DESC
LIMIT 15;"
}
# ---------------------------------------------------------------------------
# Reactions
# ---------------------------------------------------------------------------
cmd_reactions() {
need_db
echo -e "${BOLD}=== Reactions ===${NC}"
echo ""
sql "SELECT reaction_id, trigger_type, action, status, attempt, max_attempts,
source_task_id, created_at
FROM reactions
ORDER BY created_at DESC
LIMIT 20;"
}
# ---------------------------------------------------------------------------
# Schedules
# ---------------------------------------------------------------------------
cmd_schedules() {
need_db
echo -e "${BOLD}=== Active Schedules ===${NC}"
echo ""
sql "SELECT schedule_id, name, cron_expr, delivery, active,
last_run_at, created_at
FROM scheduled_tasks
WHERE active = 1
ORDER BY created_at;" 2>/dev/null || echo -e "${DIM}No scheduled_tasks table yet.${NC}"
}
cmd_schedule_delete() {
local id="$1"
[ -n "$id" ] || die "Usage: mc-ctl schedule-delete <schedule_id>"
need_db
local changes
changes=$(sql_raw "DELETE FROM scheduled_tasks WHERE schedule_id = '${id}'; SELECT changes();" 2>/dev/null)
if [ "$changes" = "1" ]; then
echo -e "${GREEN}Schedule ${id} deleted.${NC}"
else
die "Schedule ${id} not found."
fi
}
# ---------------------------------------------------------------------------
# Tools
# ---------------------------------------------------------------------------
cmd_tools() {
echo -e "${BOLD}=== Registered Tools ===${NC}"
echo ""
local result
if result=$(api GET "/api/tools/sources" 2>/dev/null); then
echo "$result" | python3 -m json.tool 2>/dev/null || echo "$result"
else
# Fallback: try health endpoint for basic info
echo -e "${YELLOW}Tool sources API not available. Checking health...${NC}"
cmd_tool_health
fi
}
cmd_tool_health() {
echo -e "${BOLD}=== Tool Source Health ===${NC}"
echo ""
local health
if health=$(curl -sf --max-time 3 "${API_URL}/health" 2>/dev/null); then
echo -e " API: ${GREEN}reachable${NC}"
echo "$health" | python3 -m json.tool 2>/dev/null || echo "$health"
else
echo -e " API: ${RED}unreachable${NC}"
fi
echo ""
echo -e "${BOLD}Hindsight:${NC}"
if curl -sf --max-time 3 "${HINDSIGHT_URL}/health" >/dev/null 2>&1; then
echo -e " Status: ${GREEN}healthy${NC}"
else
echo -e " Status: ${RED}unreachable${NC}"
fi
}
# ---------------------------------------------------------------------------
# Conversations & Memory
# ---------------------------------------------------------------------------
cmd_conversations() {
need_db
local limit="${1:-10}"
echo -e "${BOLD}=== Recent Conversations (limit ${limit}) ===${NC}"
echo ""
sql "SELECT id, bank, substr(content, 1, 80) as preview, created_at
FROM conversations
ORDER BY created_at DESC
LIMIT ${limit};"
}
cmd_memory() {
need_db
echo -e "${BOLD}=== Memory Status ===${NC}"
echo ""
local conv_count bank_count latest
conv_count=$(sql_raw "SELECT COUNT(*) FROM conversations;" 2>/dev/null || echo "0")
bank_count=$(sql_raw "SELECT COUNT(DISTINCT bank) FROM conversations;" 2>/dev/null || echo "0")
latest=$(sql_raw "SELECT MAX(created_at) FROM conversations;" 2>/dev/null || echo "none")
echo -e " Backend: SQLite (conversations table)"
echo -e " Conversations: ${conv_count}"
echo -e " Banks: ${bank_count}"
echo -e " Latest: ${latest}"
# Hindsight
echo ""
if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "$HINDSIGHT_CONTAINER"; then
if curl -sf --max-time 3 "${HINDSIGHT_URL}/health" >/dev/null 2>&1; then
echo -e " Hindsight: ${GREEN}healthy${NC} (${HINDSIGHT_URL})"
else
echo -e " Hindsight: ${YELLOW}container up, API unhealthy${NC}"
fi
else
echo -e " Hindsight: ${DIM}not running${NC}"
fi
echo ""
}
# ---------------------------------------------------------------------------
# Hindsight
# ---------------------------------------------------------------------------
cmd_hindsight_status() {
echo -e "${BOLD}=== Hindsight Status ===${NC}"
echo ""
if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "$HINDSIGHT_CONTAINER"; then
echo -e " Container: ${GREEN}running${NC}"
docker ps --filter "name=${HINDSIGHT_CONTAINER}" --format " Image: {{.Image}}\n Status: {{.Status}}\n Ports: {{.Ports}}" 2>/dev/null
else
echo -e " Container: ${RED}not running${NC}"
echo ""
echo -e " Start with: ${CYAN}cd ${PROJECT_DIR} && docker compose --profile hindsight up -d hindsight${NC}"
return
fi
echo ""
if curl -sf --max-time 3 "${HINDSIGHT_URL}/health" >/dev/null 2>&1; then
echo -e " API: ${GREEN}healthy${NC} (${HINDSIGHT_URL})"
else
echo -e " API: ${RED}unhealthy${NC}"
fi
echo ""
}
cmd_hindsight_restart() {
echo -e "${YELLOW}Restarting Hindsight container...${NC}"
docker restart "$HINDSIGHT_CONTAINER" 2>/dev/null || die "Failed to restart ${HINDSIGHT_CONTAINER}"
sleep 2
cmd_hindsight_status
}
cmd_hindsight_logs() {
local lines="${1:-$LOG_LINES}"
docker logs --tail "$lines" "$HINDSIGHT_CONTAINER" 2>&1
}
# ---------------------------------------------------------------------------
# Budget
# ---------------------------------------------------------------------------
cmd_budget() {
need_db
echo -e "${BOLD}=== Budget Status ===${NC}"
echo ""
# Check if cost_ledger table exists
local has_ledger
has_ledger=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='cost_ledger';" 2>/dev/null)
if [[ "$has_ledger" != "1" ]]; then
echo -e "${YELLOW}cost_ledger table not found — budget tracking not yet initialized.${NC}"
return
fi
echo -e "${BOLD}Daily Spend (last 24h):${NC}"
sql "SELECT ROUND(COALESCE(SUM(cost_usd), 0), 4) as spend_usd,
COUNT(*) as runs
FROM cost_ledger WHERE created_at >= datetime('now', '-1 day');"
echo ""
echo -e "${BOLD}By Runner:${NC}"
sql "SELECT agent_type,
COUNT(*) as runs,
ROUND(SUM(cost_usd), 4) as cost_usd,
SUM(prompt_tokens) as prompt_tok,
SUM(completion_tokens) as completion_tok
FROM cost_ledger
WHERE created_at >= datetime('now', '-1 day')
GROUP BY agent_type
ORDER BY cost_usd DESC;"
echo ""
echo -e "${BOLD}By Model:${NC}"
sql "SELECT model,
COUNT(*) as runs,
ROUND(SUM(cost_usd), 4) as cost_usd,
ROUND(AVG(cost_usd), 4) as avg_cost
FROM cost_ledger
WHERE created_at >= datetime('now', '-1 day')
GROUP BY model
ORDER BY cost_usd DESC;"
}
# ---------------------------------------------------------------------------
# Database
# ---------------------------------------------------------------------------
cmd_db() {
need_db
if [ $# -eq 0 ]; then
echo -e "${CYAN}Opening interactive SQLite shell...${NC}"
echo -e "${DIM}DB: ${DB_PATH}${NC}"
sqlite3 -header -column "$DB_PATH"
else
sql "$*"
fi
}
cmd_tool_chains() {
local days="${1:-7}"
[[ "$days" =~ ^[0-9]+$ ]] || die "days must be a number"
need_db
echo -e "${BOLD}=== Tool Chain Success Rates (last ${days} days) ===${NC}"
echo ""
sql "SELECT
tool_chain,
COUNT(*) as total,
SUM(CASE WHEN feedback_signal = 'positive' OR feedback_signal = 'implicit_positive' THEN 1 ELSE 0 END) as positive,
SUM(CASE WHEN feedback_signal IN ('negative', 'rephrase', 'implicit_rephrase') THEN 1 ELSE 0 END) as negative,
SUM(CASE WHEN feedback_signal IN ('none', 'neutral') THEN 1 ELSE 0 END) as no_signal
FROM scope_telemetry
WHERE tool_chain != ''
AND created_at > datetime('now', '-${days} days')
GROUP BY tool_chain
ORDER BY total DESC
LIMIT 20;"
echo ""
echo -e "${BOLD}Feedback signal distribution:${NC}"
sql "SELECT
feedback_signal,
COUNT(*) as count
FROM scope_telemetry
WHERE tool_chain != ''
AND created_at > datetime('now', '-${days} days')
GROUP BY feedback_signal
ORDER BY count DESC;"
}
cmd_stats() {
need_db
echo -e "${BOLD}=== Mission Control Stats ===${NC}"
echo ""
# Tasks
echo -e "${BOLD}Tasks:${NC}"
sql "SELECT status, COUNT(*) as count FROM tasks GROUP BY status ORDER BY count DESC;"
# Task outcomes (last 7 days)
echo ""
echo -e "${BOLD}Outcomes (last 7 days):${NC}"
sql "SELECT ran_on, COUNT(*) as total,
SUM(success) as ok,
ROUND(AVG(success)*100, 1) as success_pct,
ROUND(AVG(duration_ms)) as avg_ms
FROM task_outcomes
WHERE created_at >= datetime('now', '-7 days')
GROUP BY ran_on
ORDER BY total DESC;"
# Conversations
echo ""
echo -e "${BOLD}Conversations:${NC}"
sql "SELECT COUNT(*) as total, COUNT(DISTINCT bank) as banks, MAX(created_at) as latest
FROM conversations;"
# Events (top categories)
echo ""
echo -e "${BOLD}Events (top 10 categories):${NC}"
sql "SELECT category, COUNT(*) as count
FROM events
GROUP BY category
ORDER BY count DESC
LIMIT 10;" 2>/dev/null || echo -e "${DIM}No events table yet.${NC}"
# Reactions
echo ""
echo -e "${BOLD}Reactions:${NC}"
sql "SELECT action, status, COUNT(*) as count
FROM reactions
GROUP BY action, status
ORDER BY count DESC;" 2>/dev/null || echo -e "${DIM}No reactions table yet.${NC}"
# Schedules
echo ""
echo -e "${BOLD}Schedules:${NC}"
local active_schedules
active_schedules=$(sql_raw "SELECT COUNT(*) FROM scheduled_tasks WHERE active = 1;" 2>/dev/null || echo "0")
echo -e " Active: ${active_schedules}"
# Skills
echo ""
echo -e "${BOLD}Skills:${NC}"
local active_skills
active_skills=$(sql_raw "SELECT COUNT(*) FROM skills WHERE active = 1;" 2>/dev/null || echo "0")
local total_skills
total_skills=$(sql_raw "SELECT COUNT(*) FROM skills;" 2>/dev/null || echo "0")
echo -e " Active: ${active_skills} / ${total_skills} total"
# Learnings
echo ""
echo -e "${BOLD}Learnings:${NC}"
local learning_count
learning_count=$(sql_raw "SELECT COUNT(*) FROM learnings;" 2>/dev/null || echo "0")
echo -e " Total: ${learning_count}"
# DB size
echo ""
echo -e "${BOLD}Database:${NC}"
local size
size=$(du -sh "$DB_PATH" 2>/dev/null | cut -f1)
echo -e " Size: ${size}"
echo -e " Path: ${DB_PATH}"
echo ""
}
# ---------------------------------------------------------------------------
# Usage
# ---------------------------------------------------------------------------
usage() {
echo -e "${CYAN}mc-ctl${NC} — Mission Control Admin CLI"
echo ""
echo -e " ${BOLD}Service${NC}"
echo -e " ${GREEN}status${NC} System status, health, key metrics"
echo -e " ${GREEN}start${NC} Start mission-control service"
echo -e " ${GREEN}stop${NC} Stop mission-control service"
echo -e " ${GREEN}restart${NC} Restart mission-control service"
echo -e " ${GREEN}logs${NC} [N] Last N log lines (default ${LOG_LINES})"
echo -e " ${GREEN}follow${NC} Follow logs in real-time"
echo ""
echo -e " ${BOLD}Tasks${NC}"
echo -e " ${GREEN}tasks${NC} [--status=X] [--limit=N] List tasks (default 20)"
echo -e " ${GREEN}task${NC} <id> Full task detail + runs + subtasks"
echo -e " ${GREEN}cancel${NC} <id> Cancel task via API"
echo ""
echo -e " ${BOLD}Analytics${NC}"
echo -e " ${GREEN}outcomes${NC} [--days=N] Outcome stats by runner (default 7 days)"
echo -e " ${GREEN}reactions${NC} Recent reactions"
echo -e " ${GREEN}stats${NC} Full metrics dashboard"
echo ""
echo -e " ${BOLD}Schedules${NC}"
echo -e " ${GREEN}schedules${NC} Active scheduled tasks"
echo -e " ${GREEN}schedule-delete${NC} <id> Delete a schedule"
echo ""
echo -e " ${BOLD}Tools${NC}"
echo -e " ${GREEN}tools${NC} List registered tools"
echo -e " ${GREEN}tool-health${NC} Health check tool sources"
echo -e " ${GREEN}tool-chains${NC} [days] Tool chain success rates (default: 7 days)"
echo ""
echo -e " ${BOLD}Memory${NC}"
echo -e " ${GREEN}conversations${NC} [N] Last N conversations (default 10)"
echo -e " ${GREEN}memory${NC} Memory backend status"
echo ""
echo -e " ${BOLD}Hindsight${NC}"
echo -e " ${GREEN}hindsight-status${NC} Container + API health"
echo -e " ${GREEN}hindsight-restart${NC} Restart Hindsight container"
echo -e " ${GREEN}hindsight-logs${NC} [N] Container logs"
echo ""
echo -e " ${BOLD}Intelligence Depot${NC}"
echo -e " ${GREEN}intel${NC} status Source health + signal counts"
echo -e " ${GREEN}intel${NC} signals [hours] Recent signals (default 24h)"
echo -e " ${GREEN}intel${NC} deltas Active deltas above threshold"
echo -e " ${GREEN}intel${NC} counts Signal totals by source"
echo ""
echo -e " ${BOLD}Self-Tuning${NC}"
echo -e " ${GREEN}tuning${NC} status Latest tuning run summary"
echo -e " ${GREEN}tuning${NC} report [id] Full tuning report"
echo -e " ${GREEN}tuning${NC} promote [id] Show winning mutations as diffs"
echo ""
echo -e " ${BOLD}Monitoring${NC}"
echo -e " ${GREEN}monitoring${NC} up Start Prometheus + Grafana stack"
echo -e " ${GREEN}monitoring${NC} down Stop monitoring stack"
echo -e " ${GREEN}monitoring${NC} status Container status + scrape health"
echo ""
echo -e " ${BOLD}Database${NC}"
echo -e " ${GREEN}db${NC} [query] Interactive shell or run query"
echo ""
}
# ---------------------------------------------------------------------------
# Monitoring (Prometheus + Grafana)
# ---------------------------------------------------------------------------
cmd_monitoring() {
local subcmd="${1:-status}"
local compose_file="${PROJECT_DIR}/docker-compose.monitoring.yml"
if [ ! -f "$compose_file" ]; then
echo -e "${RED}Monitoring compose file not found:${NC} $compose_file"
exit 1
fi
case "$subcmd" in
up)
echo -e "${CYAN}Starting monitoring stack...${NC}"
docker compose -f "$compose_file" up -d
echo ""
echo -e "${GREEN}Prometheus:${NC} http://localhost:9090"
echo -e "${GREEN}Grafana:${NC} http://localhost:3001 (admin / \${GRAFANA_PASSWORD:-jarvis2026})"
;;
down)
echo -e "${CYAN}Stopping monitoring stack...${NC}"
docker compose -f "$compose_file" down
;;
status)
echo -e "${BOLD}Monitoring Stack${NC}"
echo ""
docker compose -f "$compose_file" ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}" 2>/dev/null || echo " (not running)"
echo ""
# Check Prometheus scrape health
local health
health=$(curl -sf http://localhost:9090/api/v1/targets 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); t=d['data']['activeTargets'][0]; print(t['health'])" 2>/dev/null)
if [ -n "$health" ]; then
if [ "$health" = "up" ]; then
echo -e " Prometheus scrape: ${GREEN}${health}${NC}"
else
echo -e " Prometheus scrape: ${RED}${health}${NC}"
fi
else
echo -e " Prometheus: ${RED}not reachable${NC}"
fi
# Check Grafana
local gf_health
gf_health=$(curl -sf http://localhost:3001/api/health 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('database','?'))" 2>/dev/null)
if [ "$gf_health" = "ok" ]; then
echo -e " Grafana: ${GREEN}ok${NC} (http://localhost:3001)"
else
echo -e " Grafana: ${RED}not reachable${NC}"
fi
;;
*)
echo -e "${RED}Unknown monitoring subcommand:${NC} $subcmd"
echo " Usage: mc-ctl monitoring [up|down|status]"
exit 1
;;
esac
}
# ---------------------------------------------------------------------------
# Self-Tuning
# ---------------------------------------------------------------------------
cmd_tuning() {
need_db
local subcmd="${1:-status}"
shift 2>/dev/null || true
case "$subcmd" in
status)
echo -e "\n${BOLD}TUNING STATUS${NC}\n"
local row
row=$(sqlite3 -separator '|' "$DB_PATH" \
"SELECT run_id, status, baseline_score, best_score, experiments_run, experiments_won, total_cost_usd, started_at, completed_at FROM tune_runs ORDER BY started_at DESC LIMIT 1" 2>/dev/null || echo "")
if [ -z "$row" ]; then
echo "No tuning runs found."
return
fi
IFS='|' read -r run_id status baseline best exp_run exp_won cost started completed <<< "$row"
echo -e " Run ID: ${CYAN}${run_id}${NC}"
echo -e " Status: ${status}"
echo -e " Baseline: ${baseline:-N/A}"
echo -e " Best Score: ${GREEN}${best:-N/A}${NC}"
echo -e " Experiments: ${exp_run} run, ${GREEN}${exp_won} wins${NC}"
echo -e " Cost: \$${cost}"
echo -e " Started: ${started}"
echo -e " Completed: ${completed:-running}"
echo ""
# Show recent experiments
echo -e "${BOLD}Recent experiments:${NC}"
sqlite3 -column -header "$DB_PATH" \
"SELECT experiment_id, surface, target, status,
ROUND(baseline_score, 1) as baseline,
ROUND(mutated_score, 1) as mutated,
SUBSTR(hypothesis, 1, 60) as hypothesis
FROM tune_experiments
WHERE run_id = '${run_id}'
ORDER BY created_at DESC LIMIT 10" 2>/dev/null || echo "No experiments found."
echo ""
;;
report)
local run_id="${1:-}"
local query
if [ -n "$run_id" ]; then
query="SELECT report FROM tune_runs WHERE run_id = '${run_id}'"
else
query="SELECT report FROM tune_runs ORDER BY started_at DESC LIMIT 1"
fi
local report
report=$(sqlite3 "$DB_PATH" "$query" 2>/dev/null || echo "")
if [ -z "$report" ]; then
echo "No report found."
else
echo "$report"
fi
;;
promote)
local run_id="${1:-}"
local query
if [ -n "$run_id" ]; then
query="SELECT surface, target, mutation_type, original_value, mutated_value, hypothesis FROM tune_experiments WHERE run_id = '${run_id}' AND status = 'passed' ORDER BY created_at"
else
query="SELECT e.surface, e.target, e.mutation_type, e.original_value, e.mutated_value, e.hypothesis FROM tune_experiments e INNER JOIN (SELECT run_id FROM tune_runs ORDER BY started_at DESC LIMIT 1) r ON e.run_id = r.run_id WHERE e.status = 'passed' ORDER BY e.created_at"
fi
echo -e "\n${BOLD}WINNING MUTATIONS TO PROMOTE${NC}\n"
local found=0
while IFS='|' read -r surface target mtype orig_val mut_val hyp; do
found=1
echo -e "${GREEN}─── ${surface}/${target} (${mtype}) ───${NC}"
echo -e "${DIM}Hypothesis: ${hyp}${NC}"
echo ""
echo -e "${RED}--- Original:${NC}"
echo "$orig_val" | head -10
echo ""
echo -e "${GREEN}+++ Mutation:${NC}"
echo "$mut_val" | head -20
echo ""
done < <(sqlite3 -separator '|' "$DB_PATH" "$query" 2>/dev/null)
if [ "$found" -eq 0 ]; then
echo "No winning mutations to promote."
else
echo -e "${YELLOW}Review the mutations above. Apply manually or via Claude Code.${NC}"
fi
echo ""
;;
*)
echo -e "${RED}Unknown tuning subcommand:${NC} ${subcmd}"
echo "Usage: mc-ctl tuning [status|report|promote] [run_id]"
;;
esac
}
# ---------------------------------------------------------------------------
# Intel commands (S6 Intelligence Depot)
# ---------------------------------------------------------------------------
cmd_intel() {
need_db
local subcmd="${1:-status}"
shift 2>/dev/null || true
case "$subcmd" in
status)
echo -e "${BOLD}=== Intelligence Depot Status ===${NC}"
echo ""
echo -e "${BOLD}Snapshots (last poll per source):${NC}"
sql "SELECT source, key, last_value_numeric, snapshot_at, run_count
FROM signal_snapshots
ORDER BY snapshot_at DESC
LIMIT 30;"
echo ""
echo -e "${BOLD}Signal counts (last 24h):${NC}"
sql "SELECT source, COUNT(*) as signals, MIN(collected_at) as oldest, MAX(collected_at) as newest
FROM signals
WHERE collected_at >= datetime('now', '-24 hours')
GROUP BY source
ORDER BY signals DESC;"
;;
signals)
local hours
hours=$(printf '%d' "${1:-24}" 2>/dev/null) || hours=24
echo -e "${BOLD}=== Signals (last ${hours}h) ===${NC}"
sql "SELECT id, source, domain, signal_type, key,
COALESCE(value_numeric, '') as val_num,
SUBSTR(COALESCE(value_text, ''), 1, 60) as val_text,
collected_at
FROM signals
WHERE collected_at >= datetime('now', '-${hours} hours')
ORDER BY collected_at DESC
LIMIT 50;"
;;
deltas)
echo -e "${BOLD}=== Active Deltas (from snapshots) ===${NC}"
echo ""
echo -e "Showing source+key pairs with recent updates:"
sql "SELECT s.source, s.key, s.last_value_numeric as current_val,
s.run_count, s.snapshot_at
FROM signal_snapshots s
WHERE s.snapshot_at >= datetime('now', '-1 hours')
ORDER BY s.snapshot_at DESC
LIMIT 30;"
;;
counts)
echo -e "${BOLD}=== Signal Totals ===${NC}"
sql "SELECT source, COUNT(*) as total,
SUM(CASE WHEN collected_at >= datetime('now', '-1 hours') THEN 1 ELSE 0 END) as last_1h,
SUM(CASE WHEN collected_at >= datetime('now', '-24 hours') THEN 1 ELSE 0 END) as last_24h
FROM signals
GROUP BY source
ORDER BY total DESC;"
;;
*)
echo -e "${RED}Unknown intel subcommand:${NC} ${subcmd}"
echo "Usage: mc-ctl intel [status|signals [hours]|deltas|counts]"
;;
esac
}
# ---------------------------------------------------------------------------
# V7 Validation Log
# ---------------------------------------------------------------------------
VALIDATION_LOG="${PROJECT_DIR}/data/v7-validation.log"
VALIDATION_START="2026-04-10"
cmd_validation() {
need_db
local subcmd="${1:-check}"
case "$subcmd" in
check)
local today
today=$(date +%Y-%m-%d)
local day_num
day_num=$(( ( $(date -d "$today" +%s) - $(date -d "$VALIDATION_START" +%s) ) / 86400 + 1 ))
echo -e "\n${BOLD}V7 VALIDATION — Day ${day_num}/30${NC} ($today)"
echo -e "${DIM}Started: ${VALIDATION_START} — Gate: 2026-05-10${NC}\n"
local pass=0 fail=0 warn=0
# 1. Service uptime
local active
active=$(systemctl is-active "$SERVICE_NAME" 2>/dev/null || echo "inactive")
if [ "$active" = "active" ]; then
local uptime_sec
uptime_sec=$(systemctl show "$SERVICE_NAME" --property=ActiveEnterTimestamp --value 2>/dev/null)
echo -e " ${GREEN}[PASS]${NC} Service active (since $uptime_sec)"
pass=$((pass+1))
else
echo -e " ${RED}[FAIL]${NC} Service not running"
fail=$((fail+1))
fi
# 2. Ritual completion (last 24h)
local rituals_expected=0 rituals_completed=0
# Check cron-scheduled rituals from schedule_runs in last 24h
rituals_expected=$(sql_raw "SELECT COUNT(DISTINCT schedule_id) FROM schedule_runs WHERE spawned_at >= datetime('now', '-24 hours');")
rituals_completed=$(sql_raw "SELECT COUNT(DISTINCT schedule_id) FROM schedule_runs WHERE spawned_at >= datetime('now', '-24 hours') AND status = 'completed';")
local rituals_missed=$((rituals_expected - rituals_completed))
if [ "$rituals_missed" -eq 0 ] && [ "$rituals_expected" -gt 0 ]; then
echo -e " ${GREEN}[PASS]${NC} Rituals: ${rituals_completed}/${rituals_expected} completed (24h)"
pass=$((pass+1))
elif [ "$rituals_expected" -eq 0 ]; then
echo -e " ${YELLOW}[WARN]${NC} No rituals fired in last 24h"
warn=$((warn+1))
else
echo -e " ${RED}[FAIL]${NC} Rituals: ${rituals_completed}/${rituals_expected} (${rituals_missed} missed)"
fail=$((fail+1))
fi
# 3. Message delivery (last 24h) — tasks from messaging
local total_msgs completed_msgs delivery_pct
total_msgs=$(sql_raw "SELECT COUNT(*) FROM tasks WHERE created_at >= datetime('now', '-24 hours');")
completed_msgs=$(sql_raw "SELECT COUNT(*) FROM tasks WHERE created_at >= datetime('now', '-24 hours') AND status IN ('completed', 'completed_with_concerns');")
if [ "$total_msgs" -gt 0 ]; then
delivery_pct=$((completed_msgs * 100 / total_msgs))
if [ "$delivery_pct" -ge 95 ]; then
echo -e " ${GREEN}[PASS]${NC} Task completion: ${delivery_pct}% (${completed_msgs}/${total_msgs})"
pass=$((pass+1))
else
echo -e " ${RED}[FAIL]${NC} Task completion: ${delivery_pct}% (${completed_msgs}/${total_msgs}) — below 95%"
fail=$((fail+1))
fi
else
echo -e " ${YELLOW}[WARN]${NC} No tasks in last 24h"
warn=$((warn+1))
fi
# 4. Hallucination / confirmation gate holds
local gate_violations
gate_violations=$(sql_raw "SELECT COUNT(*) FROM events WHERE type = 'confirmation_gate_bypass' AND created_at >= datetime('now', '-24 hours');" 2>/dev/null || echo "0")
if [ "$gate_violations" -eq 0 ]; then
echo -e " ${GREEN}[PASS]${NC} Confirmation gate: no violations (24h)"
pass=$((pass+1))
else
echo -e " ${RED}[FAIL]${NC} Confirmation gate: ${gate_violations} violations"
fail=$((fail+1))
fi
# 5. Context pressure — emergency compactions
local compactions
compactions=$(journalctl -u "$SERVICE_NAME" --since "24 hours ago" --no-pager 2>/dev/null | grep -c -E "emergency.*compact|CONTEXT_PRESSURE_CRITICAL" 2>/dev/null || true)
compactions="${compactions:-0}"; compactions="${compactions##*$'\n'}"
if [ "$compactions" -eq 0 ]; then
echo -e " ${GREEN}[PASS]${NC} Context pressure: no emergency compactions (24h)"