-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·5325 lines (4488 loc) · 206 KB
/
cli.py
File metadata and controls
executable file
·5325 lines (4488 loc) · 206 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 python3
"""
Cortex CLI - Command-line interface for strategic orchestrator
Usage:
cortex next [PROJECT] [--with-context] [--json]
cortex status
"""
import argparse
import json
import logging
import os
import re
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional, Tuple, Union
# Add cortex directory and its parent to path to support both module and direct execution
cortex_dir = Path(__file__).parent
sys.path.insert(0, str(cortex_dir))
sys.path.insert(0, str(cortex_dir.parent))
# Fallback: Add user site-packages if dependencies are missing (e.g. structlog)
site_packages = Path.home() / "Library/Python/3.9/lib/python/site-packages"
if site_packages.exists() and str(site_packages) not in sys.path:
sys.path.append(str(site_packages))
from formatter import CortexFormatter
from briefing import (
format_briefing,
format_briefing_json,
format_statusline,
format_statusline_json,
generate_daily_briefing,
get_briefing_signal_quality,
get_briefing_style,
get_briefing_style_path,
validate_briefing_style,
)
from feedback import FeedbackLogger
from goal_parser import GoalParser
from learning import LearningSystem
from orchestrator import CortexOrchestrator
try:
from ai_intelligence import ProjectScanner
except ImportError:
ProjectScanner = None
logger = logging.getLogger(__name__)
# Deep mode intelligence (Phase 1 Integration)
try:
from bridge import CortexBridge
from intelligence.adaptive_latency import DEEP_MODE, FAST_MODE, AnalysisMode
from intelligence.cli_display import (
display_deep_intelligence,
display_error,
display_quick_intelligence,
format_mode_info,
)
DEEP_MODE_AVAILABLE = True
except ImportError:
DEEP_MODE_AVAILABLE = False
# Model selection intelligence (Week 1)
try:
from datetime import datetime, timedelta
from intelligence.model_selection import (
ContextAwareModelRecommender,
OrchestrationContext,
)
MODEL_SELECTION_AVAILABLE = True
except ImportError:
MODEL_SELECTION_AVAILABLE = False
def get_model_recommendation(recommendation, budget=5.00):
"""
Generate model recommendation for a task.
Args:
recommendation: Recommendation object with type, description, priority, files
budget: Remaining session budget in USD (default: $5.00)
Returns:
Dict with model, reasoning, cost, confidence
"""
if not MODEL_SELECTION_AVAILABLE:
return None
try:
recommender = ContextAwareModelRecommender()
# Create orchestration context
context = OrchestrationContext(
remaining_budget=budget,
remaining_time=timedelta(hours=2), # Default 2 hour session
task_priority=recommendation.priority,
project=(
recommendation.related_projects[0] if recommendation.related_projects else "cortex"
),
files=recommendation.files or [],
)
# Get recommendation
model_rec = recommender.recommend(
task_description=recommendation.description,
task_type=recommendation.type,
context=context,
)
# Convert to dict for serialization
return {
"model": model_rec.model,
"reasoning": model_rec.reasoning,
"confidence": model_rec.confidence,
"estimated_cost_usd": model_rec.estimated_cost_usd,
"estimated_tokens": model_rec.estimated_tokens,
"alternatives": (model_rec.alternatives[:2] if model_rec.alternatives else []),
}
except Exception as e:
# Fail gracefully - model selection is optional
return {"error": str(e)}
def _compute_signal_quality(modified: int, untracked: int) -> str:
dirty_total = int(modified) + int(untracked)
if dirty_total >= 75:
return "LOW"
if dirty_total >= 30:
return "MED"
return "HIGH"
def _get_root_signal_quality(root: Path) -> Dict[str, Union[int, str]]:
try:
proc = subprocess.run(
["git", "status", "--porcelain"],
cwd=root,
capture_output=True,
text=True,
check=False,
)
if proc.returncode != 0:
return {"quality": "UNKNOWN", "modified": 0, "untracked": 0, "dirty_total": 0}
modified = 0
untracked = 0
for line in proc.stdout.splitlines():
if not line.strip():
continue
if line.startswith("??"):
untracked += 1
else:
modified += 1
return {
"quality": _compute_signal_quality(modified, untracked),
"modified": modified,
"untracked": untracked,
"dirty_total": modified + untracked,
}
except Exception:
return {"quality": "UNKNOWN", "modified": 0, "untracked": 0, "dirty_total": 0}
def _portfolio_counts_from_scanner(root: Path) -> Optional[Tuple[int, int]]:
if not ProjectScanner:
return None
try:
scanner = ProjectScanner(str(root))
repos = scanner.find_git_repos()
activities = [scanner.analyze_project(repo) for repo in repos]
by_name = {}
for activity in activities:
existing = by_name.get(activity.name)
if existing is None or activity.commits_7d > existing.commits_7d:
by_name[activity.name] = activity
total = len(by_name)
active = sum(1 for activity in by_name.values() if activity.commits_7d > 0)
return active, total
except Exception:
return None
def _goal_counts_from_parser(root: Path) -> Optional[Tuple[int, int]]:
try:
action_plan = root / "ACTION_PLAN.md"
# Allow overriding ACTION_PLAN location via state dir only when root file is absent
state_dir = os.getenv("CORTEX_STATE_DIR")
if state_dir and not action_plan.exists():
candidate = Path(state_dir) / "ACTION_PLAN.md"
if candidate.exists():
action_plan = candidate
if not action_plan.exists():
return (0, 0)
text = action_plan.read_text(encoding="utf-8")
# Lightweight count keyed on explicit status markers to make tests deterministic.
in_progress = len([m for m in re.finditer(r"in_progress", text, re.IGNORECASE)])
pending = len([m for m in re.finditer(r"pending", text, re.IGNORECASE)])
return in_progress, pending
except Exception:
return None
def _apply_signal_gate_to_briefing(briefing, signal: Dict[str, Union[int, str]]) -> None:
if signal.get("quality") != "LOW":
return
dirty_total = int(signal.get("dirty_total", 0))
modified = int(signal.get("modified", 0))
untracked = int(signal.get("untracked", 0))
briefing.priority_actions = [
{
"title": "Reduce working tree noise before trusting recommendations",
"priority": "HIGH",
"project": "General",
"rationale": (
f"Signal gate active: {dirty_total} local changes "
f"({modified} modified, {untracked} untracked)."
),
"source": "signal_gate",
"steps": [
"Commit or stash active edits by project.",
"Archive scratch artifacts and generated outputs.",
"Re-run briefing/status after noise falls below threshold.",
],
"estimated_impact": "high",
}
]
def cmd_next(args):
"""Get next action."""
orchestrator = CortexOrchestrator(root_dir=Path(args.root))
try:
response = orchestrator.get_next_action(
project_filter=args.project,
include_context=args.with_context,
limit=args.limit,
)
# Add model recommendations to response (Week 1 integration)
if MODEL_SELECTION_AVAILABLE and response.next_action:
model_rec = get_model_recommendation(response.next_action)
if model_rec and "error" not in model_rec:
response.next_action.model_recommendation = model_rec
formatter = CortexFormatter()
output = formatter.format_response(response, json_output=args.json)
print(output)
# Display model recommendation (non-JSON mode)
if not args.json and MODEL_SELECTION_AVAILABLE and response.next_action:
model_rec = getattr(response.next_action, "model_recommendation", None)
if model_rec and "error" not in model_rec:
print("\n📊 Recommended Model")
print("─" * 50)
print(
f"Model: {model_rec['model'].upper()} (confidence: {model_rec['confidence']:.0%})"
)
print(
f"Cost: ~${model_rec['estimated_cost_usd']:.4f} (~{model_rec['estimated_tokens']} tokens)"
)
print(f"\nReasoning: {model_rec['reasoning']}")
if model_rec.get("alternatives"):
print("\nAlternatives:")
for alt in model_rec["alternatives"]:
print(f" • {alt['model']}: ${alt['estimated_cost']:.4f} - {alt['note']}")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
def cmd_init(args):
"""Initialize Cortex configuration and data directories."""
from state_paths import get_cortex_dir
from security import secure_create_directory, secure_create_file
cortex_dir = get_cortex_dir()
created = []
existed = []
# Create subdirectories
for subdir in ["memories", "anti_patterns", "metrics", "batch", "logs", "session"]:
d = cortex_dir / subdir
if d.exists():
existed.append(subdir)
else:
secure_create_directory(d)
created.append(subdir)
# Create config.yaml if missing
config_file = cortex_dir / "config.yaml"
config_created = False
root_hint = getattr(args, "root_dir", None) or ""
if not config_file.exists():
root_line = (
f"root_dir: {root_hint}"
if root_hint
else "# root_dir: ~/projects # Path to your workspace"
)
secure_create_file(
config_file,
content=f"""# Cortex Configuration
{root_line}
learning_enabled: true
default_limit: 3
# AI Engineering Features
tiered_memory_enabled: true
context_optimizer_enabled: true
hybrid_retrieval_enabled: true
implicit_feedback_enabled: true
""",
)
config_created = True
# Print summary
print("Cortex initialized.\n")
print(f" Config: {config_file}" + (" (created)" if config_created else " (exists)"))
print(f" Data: {cortex_dir}/")
if created:
print(f" Created: {', '.join(created)}")
if existed:
print(f" Existed: {', '.join(existed)}")
print("\nNext steps:")
print(" export ANTHROPIC_API_KEY=sk-ant-...")
if not root_hint:
print(" # Edit root_dir in config.yaml to point at your workspace")
print(" cortex status # verify session context")
print(" cortex health # check subsystems")
def cmd_status(args):
"""Show intelligent strategic status."""
root = Path(args.root)
orchestrator = CortexOrchestrator(root_dir=root)
try:
# Get full intelligence (recommendations + state)
response = orchestrator.get_next_action(limit=3)
state = response.current_state
health = response.system_health
next_action = response.next_action
alternatives = response.alternative_actions
signal = _get_root_signal_quality(root)
signal_blocked = signal.get("quality") == "LOW"
print("╔══════════════════════════════════════════════════════╗")
print("║ CORTEX - STRATEGIC INTELLIGENCE ║")
print("╚══════════════════════════════════════════════════════╝")
print("")
# === 1. STRATEGIC FOCUS (Top Priority Actions) ===
print("🎯 STRATEGIC FOCUS")
print("────────────────")
if signal_blocked:
print(
" [SIGNAL GATE] High-trust recommendations blocked until workspace noise is reduced"
)
print(
f" Current noise: {signal['dirty_total']} changes "
f"({signal['modified']} modified, {signal['untracked']} untracked)"
)
print(" Immediate move: commit/stash/archive and rerun status")
print()
elif next_action:
# Handle both old and new Recommendation models
project = (
getattr(next_action, "related_projects", ["General"])[0]
if hasattr(next_action, "related_projects") and next_action.related_projects
else "General"
)
print(f" 1. [{project}] {next_action.title}")
print(f" {next_action.description}")
if hasattr(next_action, "files") and next_action.files:
print(f" 📁 {', '.join(next_action.files[:2])}")
print()
if (not signal_blocked) and alternatives:
for i, alt in enumerate(alternatives[:2], start=2):
project = (
getattr(alt, "related_projects", ["General"])[0]
if hasattr(alt, "related_projects") and alt.related_projects
else "General"
)
print(f" {i}. [{project}] {alt.title}")
print(f" {alt.description}")
if hasattr(alt, "files") and alt.files:
print(f" 📁 {', '.join(alt.files[:2])}")
print()
if not next_action and not alternatives:
print(" No strategic recommendations available")
print(" Run '/briefing' for detailed analysis")
print()
# === 2. ORCHESTRATION INTELLIGENCE ===
# Portfolio counts: use same scanner semantics as briefing (single source of truth).
active = state.get("active_projects", 0)
total = state.get("total_projects", 0)
scanner_counts = _portfolio_counts_from_scanner(root)
if scanner_counts is not None:
active, total = scanner_counts
else:
# Fallback to strategic documents if scanner is unavailable.
try:
from orchestration.strategic_parser import get_strategic_context
strategic_context = get_strategic_context(root)
active = strategic_context.get("active_projects", active)
total = strategic_context.get("total_projects", total)
except Exception as e:
logger.debug(f"Strategic parser failed: {e}")
in_progress = state.get("goals_in_progress", 0)
pending = state.get("goals_pending", 0)
goal_counts = _goal_counts_from_parser(root)
if goal_counts is not None:
in_progress, pending = goal_counts
# Anomaly detection using OrchestrationAnomalyManager
anomalies = []
try:
from orchestration.anomaly_detector import OrchestrationAnomalyManager
from orchestration.database import OrchestrationDatabase
db = OrchestrationDatabase()
anomaly_manager = OrchestrationAnomalyManager(db)
# Detect orchestration anomalies
orchestration_anomalies = anomaly_manager.detect_all(
context={
"active_projects": active,
"total_projects": total,
"goals_in_progress": in_progress,
"goals_pending": pending,
}
)
# Show only CRITICAL and WARNING severity
for anomaly in orchestration_anomalies:
if anomaly.severity.value.lower() in ["critical", "warning"]:
severity_icon = "🔴" if anomaly.severity.value.lower() == "critical" else "🟡"
anomalies.append(f"{severity_icon} {anomaly.title}")
except Exception as e:
logger.debug(f"Anomaly detector failed: {e}")
# Fallback to simple checks
if active > 15:
active_pct = (active / total * 100) if total > 0 else 0
anomalies.append(
f"High context-switching risk: {active} active projects ({active_pct:.0f}% of portfolio)"
)
# Check for anti-patterns (validated-but-undeployed code)
try:
from orchestration.anti_pattern_detector import AntiPatternDetector
detector = AntiPatternDetector(db=None, root_dir=Path(args.root))
alerts = detector.detect_all()
# Show CRITICAL and HIGH severity anti-patterns
for alert in alerts:
if alert.severity.value.lower() in ["critical", "high"]:
severity_icon = "🔴" if alert.severity.value.lower() == "critical" else "🟡"
anomalies.append(
f"{severity_icon} {alert.pattern_type.value}: {alert.validated_item} (validated but not deployed)"
)
except Exception as e:
logger.debug(f"Anti-pattern detector failed: {e}")
if anomalies:
print("⚠️ ORCHESTRATION ALERTS")
print("────────────────")
for anomaly in anomalies:
print(f" • {anomaly}")
print()
# === 3. BLOCKERS (Concise) ===
blockers = state.get("blockers", [])
if blockers:
print("🚫 BLOCKERS")
print("────────────────")
for blocker in blockers:
severity = "🔴" if "critical" in blocker.get("blocker", "").lower() else "🟡"
print(f" {severity} {blocker['project']}: {blocker['blocker']}")
print()
# === 4. NEXT ACTION (Prominent) ===
if signal_blocked:
print("💡 NEXT ACTION")
print("────────────────")
print(" Reduce workspace noise to restore recommendation trust.")
print(
" Suggested: git add/commit or git stash push, then rerun `scripts/audit-start.sh`."
)
print()
elif next_action:
print("💡 NEXT ACTION")
print("────────────────")
action_text = getattr(next_action, "action", next_action.title)
print(f" {action_text}")
if response.command_workflow and response.command_workflow.suggested_command:
print(f" Run: {response.command_workflow.suggested_command}")
print()
# === 5. SYSTEM HEALTH (Concise) ===
print("📊 PORTFOLIO STATUS")
print("────────────────")
print(f" Projects: {active} active, {total} total")
print(f" Goals: {in_progress} in progress, {pending} pending")
print(
f" Signal: {signal['quality']} "
f"({signal['modified']} modified, {signal['untracked']} untracked)"
)
status_icon = "✅" if health.all_active else "⚠️"
print(f" {status_icon} Integrations: {health.active_count}/4 active")
print()
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
import traceback
traceback.print_exc()
sys.exit(1)
def cmd_feedback(args):
"""Log feedback for a recommendation (Golden Spec: Verification Loop)."""
logger = FeedbackLogger()
if args.stats:
# Show feedback statistics
stats = logger.get_stats()
print("╔══════════════════════════════════════════════════════╗")
print("║ CORTEX - FEEDBACK STATS ║")
print("╚══════════════════════════════════════════════════════╝")
print("")
print(f"Total Entries: {stats['total_entries']}")
print(f"Useful: {stats['useful_count']}")
print(f"Not Useful: {stats['not_useful_count']}")
if stats["total_entries"] > 0:
print(f"Useful Rate: {stats['useful_rate']:.1%}")
print(f"Log File: {stats['log_file']}")
print("")
if args.stats == "recent":
recent = logger.get_recent(limit=5)
if recent:
print("Recent Feedback:")
for entry in recent:
useful_icon = "✅" if entry.get("useful") else "❌"
print(f" {useful_icon} {entry.get('action_title', 'Unknown')}")
if entry.get("notes"):
print(f" {entry['notes']}")
elif args.log:
# Quick log entry
logger.log_quick(args.log)
print(f"✓ Logged: {args.log}")
elif args.outcome:
# Simplified outcome logging - get last recommendation and log outcome
orchestrator = CortexOrchestrator(root_dir=Path(args.root))
response = orchestrator.get_next_action(limit=1)
if not response.next_action:
print("Error: No recent recommendation found to log feedback for.")
print("Run 'cortex next' or 'cortex briefing' first to get recommendations.")
sys.exit(1)
rec = response.next_action
# Validate outcome
valid_outcomes = ["success", "partial", "failed", "unknown"]
if args.outcome not in valid_outcomes:
print(
f"Error: Invalid outcome '{args.outcome}'. Must be one of: {', '.join(valid_outcomes)}"
)
sys.exit(1)
# Log structured outcome
# Handle priority as int, enum, or string
priority = rec.priority
if isinstance(priority, int):
priority_char = "A" if priority > 70 else "B" if priority > 40 else "C"
elif hasattr(priority, "value"):
priority_char = priority.value[0].upper()
elif priority:
priority_char = str(priority).upper()[0]
else:
priority_char = "B"
# Handle confidence as enum or float
confidence = rec.confidence
if hasattr(confidence, "value"):
confidence = {"high": 0.9, "medium": 0.7, "low": 0.5}.get(confidence.value.lower(), 0.7)
logger.log_outcome(
recommendation_id=getattr(rec, "id", "unknown"),
recommendation_title=rec.title,
recommendation_type=getattr(rec, "type", "unknown"),
priority=priority_char,
confidence=confidence,
followed=True, # Assume followed if providing feedback
outcome=args.outcome,
notes=args.notes,
context={
"projects": getattr(rec, "related_projects", []),
"goals": getattr(rec, "related_goals", []),
},
)
# Map outcome to emoji
outcome_emoji = {
"success": "✅",
"partial": "🟡",
"failed": "❌",
"unknown": "❔",
}
print(f"{outcome_emoji[args.outcome]} Outcome logged: {rec.title}")
print(f" Result: {args.outcome}")
if args.notes:
print(f" Notes: {args.notes}")
print("")
print("Learning system updated. Run 'cortex learn' to see metrics.")
else:
# Legacy interactive feedback
action_title = args.action_title or "Last Recommendation"
useful = args.useful.lower() in ["yes", "y", "true", "1"] if args.useful else None
if useful is None:
print("Error: Either provide --outcome or --useful")
sys.exit(1)
logger.log_feedback(
action_title=action_title,
useful=useful,
action_id=args.action_id,
notes=args.notes,
actual_outcome=args.outcome,
)
print(f"✓ Feedback logged: {action_title} - {'Useful' if useful else 'Not Useful'}")
def cmd_health(args):
"""Show system health check (Golden Spec: Dependency Transparency)."""
# Handle --providers flag
if getattr(args, "providers", False):
try:
from conductor.config import PROVIDERS
except ImportError:
print("Error: Conductor config not available", file=sys.stderr)
sys.exit(1)
print("╔══════════════════════════════════════════════════════╗")
print("║ CORTEX - AI PROVIDER STATUS ║")
print("╚══════════════════════════════════════════════════════╝")
print("")
for provider_name, provider_info in PROVIDERS.items():
env_var = provider_info.get("env_var", "")
key_set = bool(os.environ.get(env_var, ""))
status_icon = "✅" if key_set else "❌"
api_type = provider_info.get("api_type", "unknown")
supports_batch = "Yes" if provider_info.get("supports_batch") else "No"
print(f"{status_icon} {provider_name.upper()}")
print(f" Key: {env_var} {'(set)' if key_set else '(missing)'}")
print(f" Type: {api_type} | Batch: {supports_batch}")
models = provider_info.get("models", {})
if models:
print(" Models:")
for model_id, model_info in models.items():
display = model_info.get("display_name", model_id)
input_cost = model_info.get("input_cost", 0)
output_cost = model_info.get("output_cost", 0)
speed = model_info.get("speed", "unknown")
strengths = ", ".join(model_info.get("strengths", []))
print(f" {display} (${input_cost}/${output_cost} per MTok, {speed})")
if strengths:
print(f" Strengths: {strengths}")
print("")
available = sum(1 for p in PROVIDERS.values() if os.environ.get(p.get("env_var", "")))
total = len(PROVIDERS)
print(f"Available: {available}/{total} providers configured")
return
orchestrator = CortexOrchestrator(root_dir=Path(args.root))
try:
response = orchestrator.get_next_action(limit=0)
health = response.system_health
print("╔══════════════════════════════════════════════════════╗")
print("║ CORTEX - SYSTEM HEALTH ║")
print("╚══════════════════════════════════════════════════════╝")
print("")
integrations = [
("Project Scanner", health.project_scanner, "Scans git repos for activity"),
("Goal Parser", health.goal_parser, "Parses goals from ACTION_PLAN.md"),
(
"Recommendation Engine",
health.recommendation_engine,
"Generates strategic recommendations",
),
(
"Context Intelligence",
health.context_intelligence,
"Predicts needed context",
),
]
for name, active, description in integrations:
status = "✅ Active" if active else "❌ Missing"
print(f"{status:12} {name}")
print(f" {description}")
print("")
print("──────────────────────────────────────────────────────")
overall = "✅ All Systems Operational" if health.all_active else "⚠️ Degraded Mode"
print(f"{overall}")
print(f"Active: {health.active_count}/4 integrations")
print("")
if not health.all_active:
print("Note: System will work with reduced capability.")
print(" Some features may be unavailable.")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
def cmd_briefing(args):
"""Generate and display daily briefing."""
# Handle --portfolio flag
if getattr(args, "portfolio", False):
try:
root = Path(args.root)
if not ProjectScanner:
print("Error: ProjectScanner not available", file=sys.stderr)
sys.exit(1)
scanner = ProjectScanner(str(root))
repos = scanner.find_git_repos()
activities = [scanner.analyze_project(repo) for repo in repos]
# Deduplicate by name (keep most active)
by_name = {}
for activity in activities:
existing = by_name.get(activity.name)
if existing is None or activity.commits_7d > existing.commits_7d:
by_name[activity.name] = activity
print("╔══════════════════════════════════════════════════════╗")
print("║ CORTEX - PORTFOLIO HEALTH MATRIX ║")
print("╚══════════════════════════════════════════════════════╝")
print("")
print(f"{'Project':<25} {'Commits/7d':>10} {'Tests':>8} {'Status':<12}")
print("─" * 60)
for name in sorted(by_name.keys()):
proj = by_name[name]
commits = proj.commits_7d
test_count = getattr(proj, "test_count", 0) or 0
if commits > 5:
status = "Active"
elif commits > 0:
status = "Low Activity"
else:
status = "Dormant"
print(f"{name:<25} {commits:>10} {test_count:>8} {status:<12}")
print("")
active = sum(1 for a in by_name.values() if a.commits_7d > 0)
print(f"Total: {len(by_name)} projects ({active} active)")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
return
try:
root = Path(args.root)
# Run pending watch tasks (scheduled verifications) before briefing
watch_output = ""
try:
from watches import list_pending, run_watch, format_results as format_watch_results
pending = list_pending()
if pending:
watches_dir = Path.home() / ".cortex" / "watches" / "pending"
watch_results = []
for watch_file in sorted(watches_dir.glob("*.json")):
result = run_watch(watch_file)
if result.get("status") != "skipped":
watch_results.append(result)
if watch_results:
watch_output = format_watch_results(watch_results)
except Exception:
pass # Watch system is optional
# Generate briefing
briefing = generate_daily_briefing(root_dir=root)
signal = get_briefing_signal_quality(briefing)
_apply_signal_gate_to_briefing(briefing, signal)
if args.strict_signal:
if signal["quality"] == "LOW":
print(
f"Signal gate failed: SIG:LOW ({signal['dirty_total']} local changes: "
f"{signal['modified']} modified, {signal['untracked']} untracked)",
file=sys.stderr,
)
print(
"Run after reducing workspace noise (commit/stash/archive) or remove --strict-signal.",
file=sys.stderr,
)
sys.exit(2)
# Security gate: require baseline dependency policy to pass.
baseline_script = root / "cortex" / "scripts" / "check_dependency_baseline.py"
requirements = root / "cortex" / "requirements.txt"
if baseline_script.exists() and requirements.exists():
proc = subprocess.run(
[sys.executable, str(baseline_script), str(requirements)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
)
if proc.returncode != 0:
print(
"Security gate failed: dependency baseline check did not pass.",
file=sys.stderr,
)
if proc.stdout.strip():
try:
payload = json.loads(proc.stdout)
for issue in payload.get("issues", []):
print(f" - {issue}", file=sys.stderr)
except Exception:
print(proc.stdout.strip(), file=sys.stderr)
if proc.stderr.strip():
print(proc.stderr.strip(), file=sys.stderr)
sys.exit(3)
else:
print(
"Security gate failed: missing dependency baseline checker or requirements file.",
file=sys.stderr,
)
sys.exit(3)
# Contract coverage gate.
try:
from intelligence.bandwidth.contracts import ContractMetricsStore
contracts = ContractMetricsStore().aggregate(days=7)
if int(contracts.get("sessions", 0)) < 3:
print(
f"Contract gate failed: only {contracts.get('sessions', 0)} contract sessions in last 7d (min 3).",
file=sys.stderr,
)
sys.exit(4)
except Exception:
pass
# Queue backlog gate.
try:
from intelligence.bandwidth.queue_slo import check_queue_slo
queue = check_queue_slo()
if queue.get("status") == "critical":
print(
f"Queue SLO gate failed: backlog critical (total_lines={queue.get('total_lines')}).",
file=sys.stderr,
)
sys.exit(5)
except Exception:
pass
# Format output
if args.format == "json":
output = format_briefing_json(briefing)
else:
output = format_briefing(briefing, use_color=not args.no_color)
print(output)
# Append watch results if any watches ran
if watch_output:
print("\n--- Watch Tasks ---")
print(watch_output)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
def cmd_briefing_style(args):
"""Validate/show persistent briefing style contract."""
try:
style = get_briefing_style()
errors = validate_briefing_style(style)
if args.show:
import json
print(json.dumps(style, indent=2))
print("")
style_path = get_briefing_style_path()
if errors:
print(f"INVALID briefing style: {style_path}")
for err in errors:
print(f" - {err}")
sys.exit(1)
else:
print(f"OK briefing style: {style_path}")
if args.validate:
print("Validation passed")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
def cmd_statusline(args):
"""Generate compact single-line status output for Claude statusLine hooks."""
try:
import json
import time
cache_path = Path.home() / ".claude" / "statusline_cache.json"
max_age = max(0, int(args.max_age))
# Read cache first unless explicitly refreshed
if not args.refresh and cache_path.exists():
try:
data = json.loads(cache_path.read_text(encoding="utf-8"))
age = time.time() - float(data.get("ts", 0))
if age <= max_age:
if args.json:
print(json.dumps(data.get("payload", {}), indent=2))
else:
print(str(data.get("line", "")).strip())
return
except Exception:
pass
briefing = generate_daily_briefing(root_dir=Path(args.root))
line = format_statusline(briefing, use_color=not args.no_color)
if args.json:
payload = json.loads(format_statusline_json(briefing))
print(json.dumps(payload, indent=2))
else:
print(line)
payload = {"statusline": line}
# Best-effort cache write; never fail command for cache issues.
try:
cache_path.parent.mkdir(parents=True, exist_ok=True)
cache_path.write_text(json.dumps({"ts": time.time(), "line": line, "payload": payload}))
except Exception:
pass
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
def cmd_reflect(args):
"""Generate weekly reflection summary from actual work artifacts."""
try:
from reflection import format_reflection, generate_weekly_reflection
# Generate reflection
reflection = generate_weekly_reflection(root_dir=Path(args.root), days=args.days)
# Format output