-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge_system.py
More file actions
1648 lines (1345 loc) · 53.6 KB
/
bridge_system.py
File metadata and controls
1648 lines (1345 loc) · 53.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 - System Mixin
V2 Prime (graph, interventions, IAP), health monitoring, dependency analysis,
batch operations, planning, work absorption, warnings, and deep analysis.
Split from bridge.py for maintainability (Feb 2026).
"""
import json
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
# Conditional imports needed by mixin methods (status reporting)
try:
from intelligence.context_optimizer import ContextOptimizer
CONTEXT_OPTIMIZER_AVAILABLE = True
except ImportError:
CONTEXT_OPTIMIZER_AVAILABLE = False
ContextOptimizer = None
try:
from intelligence.feedback.implicit_collector import ImplicitFeedbackCollector
IMPLICIT_FEEDBACK_AVAILABLE = True
except ImportError:
IMPLICIT_FEEDBACK_AVAILABLE = False
ImplicitFeedbackCollector = None
try:
from intelligence.memory.tiered_memory import TieredMemory
TIERED_MEMORY_AVAILABLE = True
except ImportError:
TIERED_MEMORY_AVAILABLE = False
TieredMemory = None
try:
from intelligence.memory.hybrid_retriever import HybridRetriever
HYBRID_RETRIEVER_AVAILABLE = True
except ImportError:
HYBRID_RETRIEVER_AVAILABLE = False
HybridRetriever = None
class SystemMixin:
"""System-related methods for CortexBridge.
This mixin provides methods for V2 Prime engine operations,
portfolio health, dependency analysis, batch jobs, planning,
work absorption, warnings, and project profiling.
All methods access self.* attributes initialized by CortexBridgeBase.__init__.
"""
# --- V2 Prime: Graph Methods ---
def query_graph(self, node_type: str, filters: Optional[Dict] = None) -> List[Dict]:
"""
Query the context graph by node type.
Args:
node_type: Type of nodes to query (goal, project, pattern, lesson, etc.)
filters: Optional filters to apply
Returns:
List of matching node dictionaries
"""
if not self.synthesis:
return [{"error": "V2 Prime Synthesis Core not available"}]
try:
from cortex.engines.synthesis import NodeType
node_type_enum = NodeType(node_type)
nodes = self.synthesis.graph.get_nodes_by_type(node_type_enum)
return [n.to_dict() for n in nodes]
except ValueError:
return [{"error": f"Unknown node type: {node_type}"}]
except Exception as e:
return [{"error": str(e)}]
def get_related_nodes(self, node_id: str, edge_type: Optional[str] = None) -> List[Dict]:
"""
Get nodes related to a given node.
Args:
node_id: ID of the source node
edge_type: Optional edge type filter
Returns:
List of related node dictionaries
"""
if not self.synthesis:
return [{"error": "V2 Prime Synthesis Core not available"}]
try:
from cortex.engines.synthesis import EdgeType
edge_type_enum = EdgeType(edge_type) if edge_type else None
nodes = self.synthesis.graph.get_related(node_id, edge_type_enum)
return [n.to_dict() for n in nodes]
except ValueError:
return [{"error": f"Unknown edge type: {edge_type}"}]
except Exception as e:
return [{"error": str(e)}]
def add_graph_node(
self,
node_type: str,
name: str,
data: Dict[str, Any],
node_id: Optional[str] = None,
) -> Dict[str, Any]:
"""
Add a node to the context graph.
Args:
node_type: Type of node
name: Node name
data: Node data
node_id: Optional explicit ID
Returns:
Result with node_id
"""
if not self.synthesis:
return {"error": "V2 Prime Synthesis Core not available"}
try:
import uuid
from cortex.engines.synthesis import Node, NodeType
nid = node_id or f"{node_type}:{uuid.uuid4().hex[:8]}"
node = Node(
id=nid,
type=NodeType(node_type),
name=name,
data=data,
)
self.synthesis.graph.add_node(node)
return {"success": True, "node_id": nid}
except Exception as e:
return {"error": str(e)}
def add_graph_edge(
self, source_id: str, target_id: str, edge_type: str, weight: float = 1.0
) -> Dict[str, Any]:
"""
Add an edge to the context graph.
Args:
source_id: Source node ID
target_id: Target node ID
edge_type: Type of edge
weight: Edge weight (default 1.0)
Returns:
Result
"""
if not self.synthesis:
return {"error": "V2 Prime Synthesis Core not available"}
try:
from cortex.engines.synthesis import Edge, EdgeType
edge = Edge(
source_id=source_id,
target_id=target_id,
type=EdgeType(edge_type),
weight=weight,
)
self.synthesis.graph.add_edge(edge)
return {"success": True}
except Exception as e:
return {"error": str(e)}
def get_graph_stats(self) -> Dict[str, Any]:
"""Get context graph statistics."""
if not self.synthesis:
return {"error": "V2 Prime Synthesis Core not available"}
try:
return self.synthesis.graph.get_stats()
except Exception as e:
return {"error": str(e)}
# --- V2 Prime: Intervention Methods ---
def get_pending_interventions(self) -> List[Dict]:
"""
Get pending interventions.
Returns:
List of intervention dictionaries
"""
if not self.broker:
return [{"error": "V2 Prime Action Broker not available"}]
try:
return [i.to_dict() for i in self.broker.get_pending()]
except Exception as e:
return [{"error": str(e)}]
def acknowledge_intervention(self, intervention_id: str) -> Dict[str, Any]:
"""
Acknowledge an intervention.
Args:
intervention_id: ID of intervention to acknowledge
Returns:
Result
"""
if not self.broker:
return {"error": "V2 Prime Action Broker not available"}
try:
success = self.broker.acknowledge(intervention_id)
return {"success": success}
except Exception as e:
return {"error": str(e)}
def suppress_intervention(self, intervention_id: str, hours: int = 24) -> Dict[str, Any]:
"""
Suppress an intervention for a duration.
Args:
intervention_id: ID of intervention to suppress
hours: Hours to suppress (default 24)
Returns:
Result
"""
if not self.broker:
return {"error": "V2 Prime Action Broker not available"}
try:
success = self.broker.suppress(intervention_id, hours)
return {"success": success}
except Exception as e:
return {"error": str(e)}
def get_broker_status(self) -> Dict[str, Any]:
"""Get Action Broker status."""
if not self.broker:
return {"error": "V2 Prime Action Broker not available"}
try:
return self.broker.get_status()
except Exception as e:
return {"error": str(e)}
# --- V2 Prime: IAP Methods ---
def handle_iap_message(self, message_dict: Dict) -> Dict[str, Any]:
"""
Handle an Inter-Agent Protocol message.
Args:
message_dict: IAP message as dictionary
Returns:
Response message as dictionary
"""
if not self.iap:
return {"error": "V2 Prime IAP Handler not available"}
try:
from cortex.protocols.iap import IAPMessage
message = IAPMessage.from_dict(message_dict)
response = self.iap.handle_message(message)
return response.to_dict()
except Exception as e:
return {"error": str(e)}
def register_agent(
self, agent_id: str, role: str, capabilities: List[str] = None
) -> Dict[str, Any]:
"""
Register an agent for IAP communication.
Args:
agent_id: Agent identifier
role: Agent role (researcher, implementer, reviewer, etc.)
capabilities: List of agent capabilities
Returns:
Result
"""
if not self.iap:
return {"error": "V2 Prime IAP Handler not available"}
try:
from cortex.protocols.iap import Agent, AgentRole
agent = Agent(
id=agent_id,
role=AgentRole(role),
capabilities=capabilities or [],
)
self.iap.register_agent(agent)
return {"success": True, "agent_id": agent_id}
except Exception as e:
return {"error": str(e)}
def get_v2_status(self) -> Dict[str, Any]:
"""
Get V2 Prime system status.
Returns:
Status of all V2 Prime components
"""
return {
"v2_available": self.v2_available,
"absorber": self.absorber is not None,
"synthesis": self.synthesis is not None,
"broker": self.broker is not None,
"iap": self.iap is not None,
"graph_stats": self.get_graph_stats() if self.synthesis else None,
"broker_status": self.get_broker_status() if self.broker else None,
}
def get_ai_engineering_status(self) -> Dict[str, Any]:
"""
Get AI Engineering module status.
Returns:
Status of AI Engineering modules (Week 2 integrations)
"""
return {
"context_optimizer": {
"available": CONTEXT_OPTIMIZER_AVAILABLE,
"enabled": self.context_optimizer is not None,
},
"implicit_feedback": {
"available": IMPLICIT_FEEDBACK_AVAILABLE,
"enabled": self.implicit_feedback is not None,
"stats": (
self.implicit_feedback.get_session_stats() if self.implicit_feedback else None
),
},
"tiered_memory": {
"available": TIERED_MEMORY_AVAILABLE,
"enabled": self.tiered_memory is not None,
"stats": (self.tiered_memory.get_stats() if self.tiered_memory else None),
},
"hybrid_retriever": {
"available": HYBRID_RETRIEVER_AVAILABLE,
"enabled": self.hybrid_retriever is not None,
"pattern_count": (
len(self.hybrid_retriever.patterns) if self.hybrid_retriever else 0
),
},
"config_flags": {
"tiered_memory_enabled": (
self.config.tiered_memory_enabled if self.config else None
),
"context_optimizer_enabled": (
self.config.context_optimizer_enabled if self.config else None
),
"implicit_feedback_enabled": (
self.config.implicit_feedback_enabled if self.config else None
),
"hybrid_retrieval_enabled": (
self.config.hybrid_retrieval_enabled if self.config else None
),
},
}
def get_portfolio_stats(self, include_health: bool = True) -> Dict[str, Any]:
"""
Get portfolio statistics.
Args:
include_health: Include health summary (default: True)
Returns:
Dict with stats about projects, patterns, lessons, and health
Example:
>>> bridge = CortexBridge()
>>> stats = bridge.get_portfolio_stats()
>>> print(stats["total_projects"])
>>> print(stats["health"]["healthy_count"])
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
return self.portfolio.get_stats(include_health=include_health)
except Exception as e:
return {"error": str(e)}
def get_project_health(
self, project: str, days: int = 7, force_refresh: bool = False
) -> Dict[str, Any]:
"""
Get health score for a specific project.
Args:
project: Project name
days: Days to analyze (default: 7)
force_refresh: Force cache refresh
Returns:
Dict with health score, assessment, recommendations
Example:
>>> bridge = CortexBridge()
>>> health = bridge.get_project_health("cortex")
>>> print(health["health_score"])
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
return self.portfolio.get_project_health(project, days, force_refresh)
except Exception as e:
return {"error": str(e)}
def get_portfolio_health_summary(self, days: int = 7) -> Dict[str, Any]:
"""
Get health summary for all projects.
Args:
days: Days to analyze (default: 7)
Returns:
Dict with health scores for all projects
Example:
>>> bridge = CortexBridge()
>>> summary = bridge.get_portfolio_health_summary()
>>> print(summary["aggregate"]["healthy_projects"])
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
return self.portfolio.get_portfolio_health_summary(days)
except Exception as e:
return {"error": str(e)}
def get_project_health_trends(self, project: str) -> Dict[str, Any]:
"""
Get comprehensive health trends for a project.
Args:
project: Project name
Returns:
Dict with trends, insights, recommendations
Example:
>>> bridge = CortexBridge()
>>> trends = bridge.get_project_health_trends("cortex")
>>> print(trends["insights"])
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
return self.portfolio.get_project_health_trends(project)
except Exception as e:
return {"error": str(e)}
# --- Dependency Analysis Methods ---
def get_dependency_analysis(self, project: str) -> Dict[str, Any]:
"""
Get dependency analysis for a project.
Args:
project: Project name
Returns:
Dict with dependency analysis
Example:
>>> bridge = CortexBridge()
>>> deps = bridge.get_dependency_analysis("cortex")
>>> print(deps["external_deps"])
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
from cortex.agents.data_agent.analyzers.project_analyzer import (
ProjectAnalyzer,
)
analyzer = ProjectAnalyzer()
return analyzer.get_dependency_analysis(project)
except Exception as e:
return {"error": str(e)}
def get_dependency_health(self, project: str) -> Dict[str, Any]:
"""
Get dependency health score for a project.
Args:
project: Project name
Returns:
Dict with health score and breakdown
Example:
>>> bridge = CortexBridge()
>>> health = bridge.get_dependency_health("cortex")
>>> print(f"Score: {health['total_score']}/100")
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
from cortex.agents.data_agent.analyzers.project_analyzer import (
ProjectAnalyzer,
)
analyzer = ProjectAnalyzer()
return analyzer.get_dependency_health(project)
except Exception as e:
return {"error": str(e)}
def find_circular_dependencies(self, project: str) -> Dict[str, Any]:
"""
Find circular dependencies in a project.
Args:
project: Project name
Returns:
Dict with circular dependency analysis
Example:
>>> bridge = CortexBridge()
>>> circular = bridge.find_circular_dependencies("cortex")
>>> if circular["has_cycles"]:
>>> print(f"Found {circular['cycle_count']} cycles")
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
from cortex.agents.data_agent.analyzers.project_analyzer import (
ProjectAnalyzer,
)
analyzer = ProjectAnalyzer()
return analyzer.find_circular_dependencies(project)
except Exception as e:
return {"error": str(e)}
def export_dependency_graph(
self,
project: str,
format: str = "ascii",
include_stdlib: bool = False,
include_external: bool = True,
) -> Dict[str, Any]:
"""
Export dependency graph in specified format.
Args:
project: Project name
format: Output format ("ascii", "dot", or "mermaid")
include_stdlib: Whether to include standard library imports (for dot/mermaid)
include_external: Whether to include external dependencies (for dot/mermaid)
Returns:
Dict with graph data in requested format
Example:
>>> bridge = CortexBridge()
>>> graph = bridge.export_dependency_graph("cortex", format="mermaid")
>>> print(graph["graph"])
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
from cortex.agents.data_agent.analyzers.dependency_mapper import (
DependencyMapper,
)
from cortex.agents.data_agent.analyzers.project_analyzer import (
ProjectAnalyzer,
)
analyzer = ProjectAnalyzer()
project_path = analyzer.projects.get(project)
if not project_path:
return {"error": f"Project '{project}' not found"}
mapper = DependencyMapper(project_path)
if format == "dot":
graph = mapper.export_to_dot(
include_stdlib=include_stdlib, include_external=include_external
)
elif format == "mermaid":
graph = mapper.export_to_mermaid(
include_stdlib=include_stdlib, include_external=include_external
)
elif format == "ascii":
graph = mapper.generate_ascii_tree()
else:
return {"error": f"Unknown format '{format}'. Use: ascii, dot, or mermaid"}
return {
"success": True,
"project": project,
"format": format,
"graph": graph,
}
except Exception as e:
return {"error": str(e)}
def get_package_dependencies(self, project: str) -> Dict[str, Any]:
"""
Get declared dependencies from package manager files.
Args:
project: Project name
Returns:
Dict with package file parsing results
Example:
>>> bridge = CortexBridge()
>>> packages = bridge.get_package_dependencies("cortex")
>>> print(packages["all_packages"])
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
from cortex.agents.data_agent.analyzers.project_analyzer import (
ProjectAnalyzer,
)
analyzer = ProjectAnalyzer()
return analyzer.get_package_dependencies(project)
except Exception as e:
return {"error": str(e)}
def compare_package_dependencies(self, project: str) -> Dict[str, Any]:
"""
Compare declared vs actual dependencies.
Args:
project: Project name
Returns:
Dict with comparison results (declared, actual, unused, undeclared)
Example:
>>> bridge = CortexBridge()
>>> comparison = bridge.compare_package_dependencies("cortex")
>>> print(f"Undeclared: {comparison['undeclared_count']}")
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
from cortex.agents.data_agent.analyzers.project_analyzer import (
ProjectAnalyzer,
)
analyzer = ProjectAnalyzer()
return analyzer.compare_package_dependencies(project)
except Exception as e:
return {"error": str(e)}
def analyze_portfolio_dependencies(
self, project_filter: Optional[str] = None
) -> Dict[str, Any]:
"""
Analyze dependencies across entire portfolio.
Args:
project_filter: Optional project name to focus analysis on
Returns:
Dict with portfolio-wide dependency analysis
Example:
>>> bridge = CortexBridge()
>>> portfolio = bridge.analyze_portfolio_dependencies()
>>> print(f"Projects analyzed: {len(portfolio['projects_analyzed'])}")
"""
if not self.portfolio:
return {"error": "Portfolio memory not available"}
try:
from cortex.agents.data_agent.analyzers.project_analyzer import (
ProjectAnalyzer,
)
analyzer = ProjectAnalyzer()
return analyzer.analyze_portfolio_dependencies(project_filter=project_filter)
except Exception as e:
return {"error": str(e)}
# --- Batch API Methods ---
def submit_research_batch(self, research_items: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Submit a batch of research discovery requests.
Args:
research_items: List of research request dicts, each with:
- id: Unique identifier
- topic: Research topic
- context: Additional context
- priority: "high", "medium", "low"
Returns:
Dict with batch_id, submitted_count, completed_count, and results
Example:
>>> bridge = CortexBridge()
>>> items = [{"id": "1", "topic": "AI safety", "context": "...", "priority": "high"}]
>>> result = bridge.submit_research_batch(items)
"""
try:
from cortex.batch.research_batcher import ResearchBatcher
batcher = ResearchBatcher()
return batcher.process_batch(research_items)
except ImportError as e:
return {"error": f"ResearchBatcher not available: {e}"}
except Exception as e:
return {"error": str(e)}
def submit_briefing_batch(self, contexts: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Submit a batch of briefing generation requests.
Args:
contexts: List of briefing context dicts, each with:
- portfolio_pulse: Portfolio state dict
- system_health: System health dict
- execution_history: Execution history dict
- goals_context: Goals context dict
- context_id: Unique identifier
Returns:
Dict with batch_id, submitted_count, completed_count, and results
Example:
>>> bridge = CortexBridge()
>>> contexts = [{"context_id": "briefing_001", ...}]
>>> result = bridge.submit_briefing_batch(contexts)
"""
try:
from cortex.batch.briefing_batcher import (
BriefingContext,
RecommendationBatcher,
)
batcher = RecommendationBatcher(root_dir=self.root_dir)
# Convert dicts to BriefingContext objects
briefing_contexts = [
BriefingContext(
portfolio_pulse=ctx.get("portfolio_pulse", {}),
system_health=ctx.get("system_health", {}),
execution_history=ctx.get("execution_history", {}),
goals_context=ctx.get("goals_context", {}),
context_id=ctx.get("context_id", f"briefing_{i}"),
)
for i, ctx in enumerate(contexts)
]
return batcher.process_batch(briefing_contexts)
except ImportError as e:
return {"error": f"BriefingBatcher not available: {e}"}
except Exception as e:
return {"error": str(e)}
def submit_intelligence_briefing(self, tracks: Optional[List[Dict]] = None) -> Dict[str, Any]:
"""
Submit intelligence briefing research batch (7 tracks by default).
Uses BriefingResearcher to research AI engineering, agent orchestration,
Claude ecosystem, and Cortex-competitive landscape via Batch API.
Args:
tracks: Optional custom track list. Defaults to BRIEFING_TRACKS.
Returns:
{"batch_id": str, "submitted_count": int, "tracks": [str]}
Example:
>>> bridge = CortexBridge()
>>> result = bridge.submit_intelligence_briefing()
>>> # Later: bridge.collect_intelligence_briefing(result["batch_id"])
"""
try:
from cortex.batch.briefing_researcher import BriefingResearcher
researcher = BriefingResearcher(tracks=tracks)
return researcher.submit_briefing_batch()
except ImportError as e:
return {"error": f"BriefingResearcher not available: {e}"}
except Exception as e:
return {"error": str(e)}
def collect_intelligence_briefing(self, batch_id: str) -> Dict[str, Any]:
"""
Collect completed intelligence briefing and synthesize into markdown.
Args:
batch_id: From submit_intelligence_briefing().
Returns:
{"briefing_file": str, "tracks_completed": int, "summary": str}
"""
try:
from cortex.batch.briefing_researcher import BriefingResearcher
researcher = BriefingResearcher()
return researcher.collect_and_synthesize(batch_id)
except ImportError as e:
return {"error": f"BriefingResearcher not available: {e}"}
except Exception as e:
return {"error": str(e)}
def get_batch_status(self, batch_id: str) -> Dict[str, Any]:
"""
Get status of a batch operation.
Args:
batch_id: Batch ID from submit_research_batch or submit_briefing_batch
Returns:
Dict with batch status, progress, and request counts
Example:
>>> bridge = CortexBridge()
>>> status = bridge.get_batch_status("batch_123")
"""
try:
from cortex.batch.batch_api_client import BatchAPIClient
client = BatchAPIClient()
return client.get_batch_status(batch_id)
except ImportError as e:
return {"error": f"BatchAPIClient not available: {e}"}
except Exception as e:
return {"error": str(e)}
# --- 6. Planning Bridge ---
def create_plan(
self, project: str, title: str = None, auto_generate: bool = True
) -> Dict[str, Any]:
"""
Create an execution plan from recommendations.
Args:
project: Project name
title: Plan title (auto-generated if None)
auto_generate: Auto-generate recommendations
Returns:
Plan summary
"""
try:
from intelligence.planning import PlanPriority
from recommendation_engine import RecommendationEngine
# Initialize recommendation engine for the project
project_path = self.root_dir / project
if not project_path.exists():
project_path = self.root_dir # Fallback to root
engine = RecommendationEngine(project_path=project_path)
# Create plan
plan = engine.create_plan(
title=title, priority=PlanPriority.MEDIUM, auto_generate=auto_generate
)
return {
"success": True,
"plan_id": plan.id,
"title": plan.title,
"steps": len(plan.steps),
"estimated_time": plan.estimated_total_time,
"message": f"Plan created: {plan.id}",
}
except Exception as e:
return {"error": str(e)}
def list_plans(self, status: str = None) -> Dict[str, Any]:
"""
List all plans.
Args:
status: Optional status filter
Returns:
List of plans
"""
try:
from intelligence.planning import PlanExecutor, PlanStatus
executor = PlanExecutor()
status_filter = None
if status:
status_filter = PlanStatus(status)
plans = executor.list_plans(status_filter=status_filter)
return {"success": True, "plans": plans, "count": len(plans)}
except Exception as e:
return {"error": str(e)}
def get_plan(self, plan_id: str, format: str = "json") -> Dict[str, Any]:
"""
Get plan details.
Args:
plan_id: Plan identifier
format: Output format (json or markdown)
Returns:
Plan details
"""
try:
from intelligence.planning import PlanExecutor
executor = PlanExecutor()
plan = executor.load_plan(plan_id)
if format == "markdown":
return {"success": True, "markdown": plan.to_markdown()}
else:
return {"success": True, "plan": plan.to_dict()}
except Exception as e:
return {"error": str(e)}
def start_plan(self, plan_id: str) -> Dict[str, Any]:
"""
Start executing a plan.
Args:
plan_id: Plan identifier
Returns:
Success status
"""
try:
from intelligence.planning import PlanExecutor
executor = PlanExecutor()
plan = executor.load_plan(plan_id)
executor.start_plan(plan)
next_step = executor.get_next_step()
return {
"success": True,
"plan_id": plan.id,
"status": plan.status.value,
"next_step": (
{
"id": next_step.id,
"title": next_step.title,
"description": next_step.description,
}
if next_step
else None
),
}
except Exception as e:
return {"error": str(e)}
def complete_step(self, step_id: str, notes: str = "") -> Dict[str, Any]:
"""
Complete a plan step.
Args:
step_id: Step identifier
notes: Completion notes
Returns:
Success status with next step