-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge_intelligence.py
More file actions
1683 lines (1423 loc) · 60.6 KB
/
bridge_intelligence.py
File metadata and controls
1683 lines (1423 loc) · 60.6 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
"""
Cortex Bridge - Intelligence Mixin
Context retrieval, recommendations, intelligence queries, specs,
feedback tracking, and analysis mode methods.
Split from bridge.py for maintainability (Feb 2026).
"""
import json
import sys
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
try:
from intelligence.adaptive_latency import AnalysisMode
except ImportError:
AnalysisMode = None
# Conditional imports needed by mixin methods
try:
from cortex.intelligence.models import IntelligenceQueryType
except ImportError:
IntelligenceQueryType = None
try:
from intelligence.context_optimizer import optimize_prompt_context
CONTEXT_OPTIMIZER_AVAILABLE = True
except ImportError:
CONTEXT_OPTIMIZER_AVAILABLE = False
optimize_prompt_context = None
try:
from intelligence.memory.tiered_memory import MemoryItem
TIERED_MEMORY_AVAILABLE = True
except ImportError:
TIERED_MEMORY_AVAILABLE = False
MemoryItem = None
try:
from synthetic.generator import SyntheticGenerator
from synthetic.schemas import GenerationRequest
SYNTHETIC_AVAILABLE = True
except ImportError:
SYNTHETIC_AVAILABLE = False
SyntheticGenerator = None
GenerationRequest = None
class IntelligenceMixin:
"""Intelligence-related methods for CortexBridge.
This mixin provides methods for context retrieval, recommendation
injection, intelligence queries, spec search, implicit feedback,
rule tracking, and adaptive analysis modes.
All methods access self.* attributes initialized by CortexBridgeBase.__init__.
"""
# --- 1. Context Bridge ---
def get_context(
self, query: str, limit: int = 5, project: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Get relevant context for a query from Knowledge Base and Project History.
Uses AI Engineering pipeline when available:
1. DefensivePrompting - Validate input
2. TieredMemory - Check session memory first
3. HybridRetriever - Semantic + keyword search
4. ContextIntelligence - Fallback to existing system
5. ContextOptimizer - Reorder for LLM attention
6. ImplicitFeedback - Track shown results
Args:
query: Natural language query
limit: Max results
project: Optional project filter
Returns:
List of context items with source metadata
"""
# 1. DefensivePrompting: Validate input
if self.defensive and self.config and self.config.defensive_prompting_enabled:
validation = self.defensive.validate_input(query)
if not validation.valid:
return [
{
"error": "Input validation failed",
"issues": validation.issues,
"source": "defensive_prompting",
}
]
query = validation.sanitized_input
results = []
# 2. TieredMemory: Check session memory first
if self.tiered_memory:
try:
memory_results = self.tiered_memory.query(query, limit=limit)
for item, score, tier in memory_results:
# Convert MemoryItem to context dict
if hasattr(item, "content"):
result = {
"title": item.content.get("title", item.id),
"type": item.content.get("type", "memory"),
"description": item.content.get("description", ""),
"confidence": min(score / 3.0, 1.0), # Normalize score
"file": item.content.get("file"),
"command": item.content.get("command"),
"source": f"tiered_memory:{tier}",
}
results.append(result)
except Exception:
pass # Fall through to other sources
# 3. HybridRetriever: Semantic + keyword search
if self.hybrid_retriever and len(results) < limit:
try:
remaining = limit - len(results)
hybrid_results = self.hybrid_retriever.search(query, limit=remaining, alpha=0.5)
for pattern, score in hybrid_results:
result = {
"title": pattern.title,
"type": "pattern",
"description": pattern.description,
"confidence": score,
"file": None,
"command": None,
"source": "hybrid_retriever",
}
results.append(result)
except Exception:
pass # Fall through to fallback
# 4. ContextIntelligence: Fallback to existing system
if len(results) < limit and self.context_intel:
try:
remaining = limit - len(results)
keywords = query.split() if " " in query else [query]
predictions = self.context_intel.predict_context(
current_project=project, keywords=keywords, limit=remaining
)
for p in predictions:
result = {
"title": p.title,
"type": p.context_type,
"description": p.description,
"confidence": p.confidence,
"file": str(p.file_path) if p.file_path else None,
"command": p.command,
"source": "context_intelligence",
}
results.append(result)
except Exception:
pass
# Handle no results case
if not results:
if not self.context_intel:
return [{"error": "ContextIntelligence not available", "source": "system"}]
return []
# 5. ContextOptimizer: Reorder for LLM attention (handled in get_optimized_context)
# Note: Direct get_context returns raw results; use get_optimized_context for LLM optimization
# 6. ImplicitFeedback: Track shown results
if self.implicit_feedback:
try:
for i, result in enumerate(results):
rec_id = f"context_{result.get('title', f'result_{i}')}_{i}"
self.implicit_feedback.track_recommendation_shown(
rec_id=rec_id,
recommendation={
"title": result.get("title", ""),
"source": result.get("source", "unknown"),
"position": i,
},
context={"query": query, "project": project},
)
except Exception:
pass # Non-critical
return results[:limit]
def get_optimized_context(
self,
query: str,
limit: int = 10,
project: Optional[str] = None,
max_tokens: Optional[int] = None,
strategy: str = "importance",
include_markers: bool = True,
) -> Dict[str, Any]:
"""
Get context optimized for LLM attention patterns.
Uses the ContextOptimizer to reorder context items based on importance,
applying the "lost-in-the-middle" optimization for better LLM attention.
Args:
query: Natural language query
limit: Max results to retrieve
project: Optional project filter
max_tokens: Optional token limit for context
strategy: Optimization strategy - "importance" or "category"
include_markers: Whether to add position markers like [IMPORTANT]
Returns:
Dict with:
- optimized_context: String ready for LLM prompt
- items: List of context items with metadata
- optimization_applied: Whether optimization was used
"""
# Get raw context items
raw_context = self.get_context(query, limit=limit, project=project)
# Check for errors
if raw_context and "error" in raw_context[0]:
return {"error": raw_context[0]["error"], "optimization_applied": False}
# If optimizer not available, return raw context as string
if not self.context_optimizer or not CONTEXT_OPTIMIZER_AVAILABLE:
context_str = "\n\n".join(
f"[{item.get('type', 'data')}] {item.get('title', '')}: {item.get('description', '')}"
for item in raw_context
)
return {
"optimized_context": context_str,
"items": raw_context,
"optimization_applied": False,
"reason": "ContextOptimizer not available",
}
# Convert to ContextItem format for optimizer
context_items = []
for item in raw_context:
# Map context types to categories
ctx_type = item.get("type", "data")
if ctx_type in ("instruction", "system"):
category = "instruction"
elif ctx_type in ("example", "pattern"):
category = "example"
elif ctx_type in ("history", "recent"):
category = "history"
else:
category = "data"
context_items.append(
{
"content": f"{item.get('title', '')}: {item.get('description', '')}",
"importance": item.get("confidence", 0.5),
"category": category,
"source": item.get("file"),
"metadata": {"original": item},
}
)
# Apply optimization
try:
optimized_str = optimize_prompt_context(
context_items,
max_tokens=max_tokens,
strategy=strategy,
include_markers=include_markers,
)
return {
"optimized_context": optimized_str,
"items": raw_context,
"optimization_applied": True,
"strategy": strategy,
"max_tokens": max_tokens,
}
except Exception as e:
# Fallback to raw context
context_str = "\n\n".join(
f"[{item.get('type', 'data')}] {item.get('title', '')}: {item.get('description', '')}"
for item in raw_context
)
return {
"optimized_context": context_str,
"items": raw_context,
"optimization_applied": False,
"error": str(e),
}
# --- 2. Strategy Bridge ---
def inject_recommendation(
self,
title: str,
rationale: str,
priority: str = "medium",
type: str = "ai_suggestion",
effort: str = "Unknown",
related_project: str = "",
) -> bool:
"""
Inject a strategic recommendation into Cortex.
Uses AI Engineering pipeline:
1. DefensivePrompting - Validate inputs
2. TieredMemory - Record for future recall
3. ImplicitFeedback - Track recommendation shown
Args:
title: Action title
rationale: Why this is important
priority: high/medium/low
type: Category of recommendation
effort: Estimated effort
related_project: Associated project
"""
# 1. DefensivePrompting: Validate inputs
if self.defensive and self.config and self.config.defensive_prompting_enabled:
# Validate title
title_validation = self.defensive.validate_input(title)
if not title_validation.valid:
print(
f"Bridge Error: Title validation failed: {title_validation.issues}",
file=sys.stderr,
)
return False
title = title_validation.sanitized_input
# Validate rationale
rationale_validation = self.defensive.validate_input(rationale)
if not rationale_validation.valid:
print(
f"Bridge Error: Rationale validation failed: {rationale_validation.issues}",
file=sys.stderr,
)
return False
rationale = rationale_validation.sanitized_input
rec_id = f"bridge_{uuid.uuid4().hex[:8]}"
rec_data = {
"id": rec_id,
"title": title,
"type": type,
"priority": priority,
"rationale": rationale,
"estimated_effort": effort,
"estimated_impact": priority,
"confidence": 0.95,
"related_projects": [related_project] if related_project else [],
"description": f"Injected via Cortex Bridge.\nRationale: {rationale}",
"created_at": datetime.now().isoformat(),
"source": "CortexBridge",
}
# root_dir may be the monorepo root (Dev/) or the cortex dir itself
if (self.root_dir / "bridge.py").exists():
external_file = self.root_dir / "external_recommendations.json"
else:
external_file = self.root_dir / "cortex" / "external_recommendations.json"
try:
# Atomic-ish read/modify/write
current_recs = []
if external_file.exists():
content = external_file.read_text()
if content.strip():
try:
current_recs = json.loads(content)
except json.JSONDecodeError:
current_recs = []
current_recs.append(rec_data)
external_file.write_text(json.dumps(current_recs, indent=2))
# 2. TieredMemory: Record for future recall
if self.tiered_memory and TIERED_MEMORY_AVAILABLE and MemoryItem:
try:
memory_item = MemoryItem(
id=rec_id,
content={
"title": title,
"type": type,
"description": rationale,
"priority": priority,
"project": related_project,
},
created_at=datetime.now(),
last_accessed=datetime.now(),
)
self.tiered_memory.record(memory_item)
except Exception:
pass # Non-critical
# 3. ImplicitFeedback: Track recommendation shown
if self.implicit_feedback:
try:
self.implicit_feedback.track_recommendation_shown(
rec_id=rec_id,
recommendation={
"title": title,
"rationale": rationale,
"priority": priority,
"type": type,
},
context={"project": related_project, "source": "inject_recommendation"},
)
except Exception:
pass # Non-critical
return True
except Exception as e:
print(f"Bridge Error (Inject): {e}", file=sys.stderr)
return False
# --- 3. Execution Bridge ---
def trigger_action(self, agent_id: str, payload: Dict[str, Any] = None) -> Dict[str, Any]:
"""
Trigger an automated agent via Local Orchestrator.
Args:
agent_id: ID of the agent to trigger
payload: Context dictionary
"""
if not self.orchestrator or not self.orchestrator.is_available():
return {"success": False, "error": "Local Orchestrator not connected"}
if not self.orchestrator.orchestrator:
return {"success": False, "error": "Orchestrator instance missing"}
try:
result = self.orchestrator.orchestrator.trigger_agent(
agent_id=agent_id, context=payload or {}
)
return {
"success": result.success,
"message": result.message,
"data": result.data,
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
return {"success": False, "error": str(e)}
# --- 4. Portfolio Bridge ---
def get_portfolio_context(self, project: str) -> Dict[str, Any]:
"""
Get comprehensive project context including patterns and lessons.
Args:
project: Project name (e.g., "vortex-backend")
Returns:
Dict with project, patterns, lessons, tech_stack, related
Example:
>>> bridge = CortexBridge()
>>> context = bridge.get_portfolio_context("vortex-backend")
>>> print(context["lessons"][0]["lesson"])
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
return self.portfolio.get_project_context(project)
except Exception as e:
return {"error": str(e)}
def get_patterns(self, pattern_type: Optional[str] = None) -> List[Dict[str, Any]]:
"""
Get cross-project patterns.
Args:
pattern_type: Optional pattern name filter
Returns:
List of pattern dicts
Example:
>>> bridge = CortexBridge()
>>> patterns = bridge.get_patterns("async_fastapi")
"""
if not self.portfolio:
return [{"error": "Portfolio memory not available"}]
try:
return self.portfolio.get_cross_project_patterns(pattern_type)
except Exception as e:
return [{"error": str(e)}]
def get_portfolio_patterns(self, pattern_type: Optional[str] = None) -> List[Dict[str, Any]]:
"""
Get cross-project patterns (alias for get_patterns for API compatibility).
Args:
pattern_type: Optional pattern category filter
Returns:
List of pattern dictionaries
Example:
>>> bridge = CortexBridge()
>>> patterns = bridge.get_portfolio_patterns(pattern_type="async_fastapi")
"""
return self.get_patterns(pattern_type=pattern_type)
def get_lessons(
self, project: Optional[str] = None, pattern: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Get lessons learned.
Args:
project: Filter by affected project
pattern: Filter by pattern type
Returns:
List of lesson dicts
Example:
>>> bridge = CortexBridge()
>>> lessons = bridge.get_lessons(project="vortex-backend")
"""
if not self.portfolio:
return [{"error": "Portfolio memory not available"}]
try:
return self.portfolio.get_lessons_learned(project=project, pattern=pattern)
except Exception as e:
return [{"error": str(e)}]
# --- Intelligence Enhancement Methods ---
def generate_synthetic(
self,
data_type: str = "profiles",
count: int = 100,
segment: Optional[str] = None,
province: Optional[str] = None,
risk_profile: Optional[str] = None,
min_quality: float = 0.7,
output_format: str = "jsonl",
) -> Dict[str, Any]:
"""
Generate synthetic Canadian FinServ data.
Args:
data_type: "profiles" or "transactions"
count: Number of records to generate
segment: Target customer segment (e.g., "mass_affluent")
province: Target province (e.g., "ON")
risk_profile: For transactions — "low", "medium", "high"
min_quality: Minimum quality score threshold (0.0-1.0)
output_format: "jsonl", "json", or "csv"
Returns:
Dict with generation results and metadata
"""
if not SYNTHETIC_AVAILABLE or not self.synthetic_generator:
return {"error": "Synthetic data engine not available", "available": False}
request = GenerationRequest(
data_type=data_type,
count=count,
segment=segment,
province=province,
risk_profile=risk_profile,
include_risk_flags=risk_profile is not None,
min_quality_score=min_quality,
output_format=output_format,
)
result = self.synthetic_generator.generate(request)
return {
"success": True,
"summary": result.summary(),
"records_generated": result.records_generated,
"records_passed": result.records_passed_quality,
"records_rejected": result.records_rejected,
"avg_quality": result.average_quality_score,
"quality_distribution": result.quality_distribution,
"output_path": result.output_path,
"flywheel_id": result.flywheel_id,
"generation_time_s": result.generation_time_seconds,
}
def query_intelligence(
self,
request: str,
project: str,
query_type: str = "spec",
use_cache: bool = True,
parallel: bool = True,
) -> Dict[str, Any]:
"""
Query unified intelligence API with enhanced features.
Uses AI Engineering pipeline:
1. DefensivePrompting - Validate input (already exists)
2. HybridRetriever - Add related patterns
3. ContextOptimizer - Optimize result context
4. TieredMemory - Record query for learning
Args:
request: User request (e.g., "enhance golden spec method")
project: Project name (e.g., "cortex")
query_type: Type of query ("spec", "impl", "analysis", "research")
use_cache: Whether to use query result cache (default: True)
parallel: Whether to query sources in parallel (default: True)
Returns:
Dict representation of IntelligenceResult with enhanced features:
- Ranked results by relevance
- Confidence scores for all components
- Detailed reasoning for results
- Overall confidence score
- related_patterns from hybrid retrieval (when available)
Example:
>>> bridge = CortexBridge()
>>> result = bridge.query_intelligence("enhance golden spec", "cortex")
>>> print(result["overall_confidence"]) # 0.85
>>> print(result["reasoning"]) # Detailed reasoning
"""
if not self.unified_intel:
return {"error": "Unified Intelligence not available"}
if not IntelligenceQueryType:
return {"error": "Intelligence models not available"}
# 1. DefensivePrompting: Apply defensive prompting if enabled
if self.config and self.config.defensive_prompting_enabled and self.defensive:
validation = self.defensive.validate_input(request)
if not validation.valid:
return {
"error": "Input validation failed",
"issues": validation.issues,
"severity": validation.severity,
}
request = validation.sanitized_input
try:
query_type_enum = IntelligenceQueryType(query_type)
result = self.unified_intel.query(
user_request=request,
project=project,
query_type=query_type_enum,
use_cache=use_cache,
parallel=parallel,
)
result_dict = result.to_dict()
# 1b. V2 Engine Enrichment: Add graph context from Signal Bus
if getattr(self, "signal_bus", None):
try:
v2_ctx = self.signal_bus.query(
context=request,
project=project,
tool_source="query_intelligence",
)
result_dict["v2_context"] = {
"graph_nodes": v2_ctx.get("graph_nodes", []),
"recent_signals": v2_ctx.get("recent_signals", []),
"cross_project_patterns": (
self.signal_bus.get_cross_project_patterns(project)
),
}
except Exception:
pass # V2 enrichment is non-critical
# 1c. V2 Signal Recording: Record this query as a workspace signal
if getattr(self, "signal_bus", None):
try:
from cortex.engines.workstream_orchestrator import (
WorkspaceSignal,
SignalSource,
WorkstreamPhase,
)
sig = WorkspaceSignal(
source=SignalSource.CLAUDE_CODE,
timestamp=datetime.now(),
project=project,
workstream=WorkstreamPhase.BUILD,
content_type=query_type,
content=request[:500],
)
self.signal_bus.absorb(sig)
except Exception:
pass # Signal recording is non-critical
# 2. HybridRetriever: Add related patterns
if self.hybrid_retriever:
try:
hybrid_results = self.hybrid_retriever.search(request, limit=3, alpha=0.5)
related_patterns = [
{
"title": pattern.title,
"description": pattern.description,
"score": score,
}
for pattern, score in hybrid_results
]
result_dict["related_patterns"] = related_patterns
except Exception:
pass # Non-critical
# 3. ContextOptimizer: Apply optimization info (if available)
if self.context_optimizer and CONTEXT_OPTIMIZER_AVAILABLE:
try:
result_dict["context_optimization"] = {
"strategy": "importance",
"applied": True,
}
except Exception:
pass
# 3b. V2 Reasoning: Synthesize retrieved context via LLM
try:
from cortex.intelligence.reasoning import ReasoningLayer, classify_query
tier = classify_query(request)
reasoner = ReasoningLayer()
result_dict["reasoning"] = reasoner.reason(request, result_dict, tier)
except Exception:
pass # Reasoning failure never blocks response
# 4. TieredMemory: Record query for learning
if self.tiered_memory and TIERED_MEMORY_AVAILABLE and MemoryItem:
try:
import uuid
query_id = f"intel_{uuid.uuid4().hex[:8]}"
memory_item = MemoryItem(
id=query_id,
content={
"type": "intelligence_query",
"title": f"Query: {request[:50]}...",
"description": request,
"project": project,
"query_type": query_type,
},
created_at=datetime.now(),
last_accessed=datetime.now(),
)
self.tiered_memory.record(memory_item)
except Exception:
pass # Non-critical
return result_dict
except Exception as e:
return {"error": str(e)}
def get_interventions(self, project: str, context: str = "") -> list:
"""Return proactive interventions from V2 reasoning layer."""
if not getattr(self, "synthesis", None):
return []
try:
from cortex.intelligence.v2_reasoning import V2ReasoningLayer
layer = V2ReasoningLayer(self.synthesis)
return layer.evaluate(context=context, project=project)
except Exception:
return []
def get_prompt_template(self, prompt_name: str, **variables) -> Optional[str]:
"""
Get a prompt template from registry with variables filled in.
Phase 1 Integration: Uses versioned prompt templates if enabled.
Args:
prompt_name: Name of prompt template
**variables: Variables to fill into template
Returns:
Rendered prompt string, or None if template not found
"""
if not self.config or not self.config.prompt_versioning_enabled or not self.prompt_registry:
return None
template = self.prompt_registry.get_prompt(prompt_name, version=self.config.prompt_version)
if not template:
return None
return template.render(**variables)
def find_similar_work(self, domain: str, project: str, limit: int = 5) -> List[Dict[str, Any]]:
"""
Find similar work across portfolio.
Args:
domain: Domain/topic (e.g., "wind forecasting ensemble")
project: Current project context
limit: Max results
Returns:
List of SimilarWork dicts
Example:
>>> bridge = CortexBridge()
>>> similar = bridge.find_similar_work("ensemble forecasting", "vortex-backend")
"""
if not self.spec_kb:
return [{"error": "Spec Knowledge Base not available"}]
try:
from dataclasses import asdict
similar = self.spec_kb.find_similar(domain, k=limit, project_filter=project)
return [asdict(s) for s in similar]
except Exception as e:
return [{"error": str(e)}]
def search_specs(
self, query: str, project: Optional[str] = None, limit: int = 5
) -> List[Dict[str, Any]]:
"""
Search indexed specifications (alias for find_similar_work for API compatibility).
Uses AI Engineering pipeline:
1. DefensivePrompting - Validate query
2. HybridRetriever - Hybrid search first
3. SpecKnowledgeBase - Fallback to existing system
4. ImplicitFeedback - Track results
Args:
query: Search query string
project: Optional project filter
limit: Maximum results
Returns:
List of matching specs with similarity scores
Example:
>>> bridge = CortexBridge()
>>> results = bridge.search_specs("API rate limiting", project="cortex", limit=5)
"""
# 1. DefensivePrompting: Validate query
if self.defensive and self.config and self.config.defensive_prompting_enabled:
validation = self.defensive.validate_input(query)
if not validation.valid:
return [
{
"error": "Query validation failed",
"issues": validation.issues,
}
]
query = validation.sanitized_input
results = []
# 2. HybridRetriever: Try hybrid search first
if self.hybrid_retriever:
try:
hybrid_results = self.hybrid_retriever.search(query, limit=limit, alpha=0.5)
for pattern, score in hybrid_results:
result = {
"spec_name": pattern.title,
"title": pattern.title,
"description": pattern.description,
"similarity": score,
"similarity_score": score,
"source": "hybrid_retriever",
}
results.append(result)
except Exception:
pass # Fall through to spec_kb
# 3. SpecKnowledgeBase: Fallback to existing system
if len(results) < limit and self.spec_kb:
try:
remaining = limit - len(results)
# Try intelligence version first (ChromaDB-based)
if hasattr(self.spec_kb, "find_similar"):
from dataclasses import asdict
similar = self.spec_kb.find_similar(query, k=remaining, project_filter=project)
# Transform SimilarWork dataclass to expected format
for s in similar:
result = asdict(s)
result["source"] = "spec_knowledge_base"
# Map 'title' to 'spec_name' for API compatibility
if "spec_name" not in result:
if "title" in result:
result["spec_name"] = result["title"]
elif "name" in result:
result["spec_name"] = result["name"]
# Ensure similarity_score is present
if "similarity" not in result and "similarity_score" in result:
result["similarity"] = result["similarity_score"]
results.append(result)
# Fallback to simple hash-based version
elif hasattr(self.spec_kb, "search"):
kb_results = self.spec_kb.search(query, project=project, limit=remaining)
for r in kb_results:
r["source"] = "spec_knowledge_base"
results.append(r)
except Exception as e:
if not results:
return [{"error": str(e)}]
# Handle no results
if not results:
if not self.spec_kb:
return [{"error": "Spec Knowledge Base not available"}]
return []
# 4. ImplicitFeedback: Track results
if self.implicit_feedback:
try:
for i, result in enumerate(results):
rec_id = f"spec_{result.get('spec_name', f'spec_{i}')}_{i}"
self.implicit_feedback.track_recommendation_shown(
rec_id=rec_id,
recommendation={
"spec_name": result.get("spec_name", ""),
"title": result.get("title", ""),
"source": result.get("source", "unknown"),
"position": i,
},
context={"query": query, "project": project},
)
except Exception:
pass # Non-critical
return results[:limit]
def get_session_context(self, format: str = "structured") -> Dict[str, Any]:
"""
Get current session context.
Args:
format: Output format ('terminal' or 'structured', default: 'structured')
Returns:
SessionContext dict or formatted string
Example:
>>> bridge = CortexBridge()
>>> context = bridge.get_session_context(format='structured')
"""
if not self.session_mgr:
return {"error": "Session Manager not available"}
try:
# Load SessionContext dataclass
from dataclasses import asdict
session_ctx = self.session_mgr.load_session_context()
if not session_ctx:
return {"error": "No session context available"}
if format == "terminal":
# Format for terminal display
context_dict = asdict(session_ctx)
# Build terminal-friendly format
lines = [
f"Project: {context_dict.get('project', 'unknown')}",
f"Focus: {context_dict.get('current_focus', 'unknown')}",
f"Goals: {', '.join(context_dict.get('active_goals', []))}",
]
return {"context": "\n".join(lines), "format": "terminal"}
else:
# Return structured dict with expected keys
context_dict = asdict(session_ctx)
# Map to expected format: project, git, goals
result = {
"project": {
"name": context_dict.get("project", "unknown"),
"path": context_dict.get("working_directory", ""),
},
"git": {"recent_commits": context_dict.get("recent_work", [])},
"goals": context_dict.get("active_goals", []),
"focus": context_dict.get("current_focus", "unknown"),
"working_directory": context_dict.get("working_directory", ""),
"last_updated": context_dict.get("last_updated", ""),
}
return result
except Exception as e:
return {"error": str(e)}
def index_spec(
self, spec_path: str, project: str, domain: Optional[str] = None
) -> Dict[str, Any]:
"""
Index a spec in knowledge base.
Args:
spec_path: Path to spec file
project: Project name