contextsynapse 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (776) hide show
  1. contextsynapse/__init__.py +107 -0
  2. contextsynapse/__main__.py +9 -0
  3. contextsynapse/a2a/__init__.py +28 -0
  4. contextsynapse/a2a/client.py +120 -0
  5. contextsynapse/a2a/discovery.py +128 -0
  6. contextsynapse/a2a/handlers.py +164 -0
  7. contextsynapse/a2a/models.py +246 -0
  8. contextsynapse/a2a/streaming.py +92 -0
  9. contextsynapse/a2a/task_manager.py +275 -0
  10. contextsynapse/adapters/__init__.py +98 -0
  11. contextsynapse/adapters/_base.py +298 -0
  12. contextsynapse/adapters/autogen/__init__.py +4 -0
  13. contextsynapse/adapters/autogen/tools.py +34 -0
  14. contextsynapse/adapters/crewai/__init__.py +4 -0
  15. contextsynapse/adapters/crewai/tools.py +63 -0
  16. contextsynapse/adapters/langchain/__init__.py +19 -0
  17. contextsynapse/adapters/langchain/message_history.py +17 -0
  18. contextsynapse/adapters/langchain/retriever.py +158 -0
  19. contextsynapse/adapters/langchain/tools.py +43 -0
  20. contextsynapse/adapters/langgraph/__init__.py +21 -0
  21. contextsynapse/adapters/langgraph/checkpoint.py +223 -0
  22. contextsynapse/adapters/langgraph/context_tools.py +341 -0
  23. contextsynapse/adapters/langgraph/message_history.py +138 -0
  24. contextsynapse/adapters/langgraph/tools.py +43 -0
  25. contextsynapse/adapters/llamaindex/__init__.py +4 -0
  26. contextsynapse/adapters/llamaindex/tools.py +64 -0
  27. contextsynapse/adapters/openai/__init__.py +24 -0
  28. contextsynapse/adapters/openai/tools.py +206 -0
  29. contextsynapse/adapters/pydantic_ai/__init__.py +4 -0
  30. contextsynapse/adapters/pydantic_ai/tools.py +36 -0
  31. contextsynapse/adapters/swarm/__init__.py +4 -0
  32. contextsynapse/adapters/swarm/tools.py +44 -0
  33. contextsynapse/agents/__init__.py +6 -0
  34. contextsynapse/agents/auto_capture.py +80 -0
  35. contextsynapse/agents/dispatcher.py +299 -0
  36. contextsynapse/agents/notifications.py +112 -0
  37. contextsynapse/aiql/__init__.py +71 -0
  38. contextsynapse/aiql/cache.py +341 -0
  39. contextsynapse/aiql/compiler/__init__.py +62 -0
  40. contextsynapse/aiql/compiler/optimizer.py +126 -0
  41. contextsynapse/aiql/compiler/planner.py +366 -0
  42. contextsynapse/aiql/compiler/statistics.py +235 -0
  43. contextsynapse/aiql/compiler/validator.py +425 -0
  44. contextsynapse/aiql/engine/__init__.py +11 -0
  45. contextsynapse/aiql/engine/chunk_storage.py +2584 -0
  46. contextsynapse/aiql/engine/executor.py +7737 -0
  47. contextsynapse/aiql/engine/extraction_integration.py +442 -0
  48. contextsynapse/aiql/engine/graph_builder.py +405 -0
  49. contextsynapse/aiql/engine/node_creation_from_normalized.py +691 -0
  50. contextsynapse/aiql/engine/performance_monitor.py +289 -0
  51. contextsynapse/aiql/engine/postprocessing.py +365 -0
  52. contextsynapse/aiql/engine/ray_stage_executors.py +918 -0
  53. contextsynapse/aiql/engine/redis_cache.py +106 -0
  54. contextsynapse/aiql/engine/streaming_json.py +366 -0
  55. contextsynapse/aiql/engine/streaming_parquet.py +568 -0
  56. contextsynapse/aiql/engine/streaming_ray_chunking.py +419 -0
  57. contextsynapse/aiql/grammar/__init__.py +14 -0
  58. contextsynapse/aiql/grammar/aiql_grammar.py +1822 -0
  59. contextsynapse/aiql/grammar/base.py +71 -0
  60. contextsynapse/aiql/parser/__init__.py +46 -0
  61. contextsynapse/aiql/parser/aiql_parser.py +11330 -0
  62. contextsynapse/aiql/parser/base_parser.py +47 -0
  63. contextsynapse/api/__init__.py +5 -0
  64. contextsynapse/api/a2a_router.py +233 -0
  65. contextsynapse/api/admin_router.py +140 -0
  66. contextsynapse/api/agent_worker_router.py +978 -0
  67. contextsynapse/api/algorithms_router.py +317 -0
  68. contextsynapse/api/api.py +4144 -0
  69. contextsynapse/api/audit.py +204 -0
  70. contextsynapse/api/auth.py +441 -0
  71. contextsynapse/api/auth_router.py +537 -0
  72. contextsynapse/api/billing.py +261 -0
  73. contextsynapse/api/billing_router.py +275 -0
  74. contextsynapse/api/boundary_router.py +452 -0
  75. contextsynapse/api/cognition_router.py +116 -0
  76. contextsynapse/api/connector_router.py +237 -0
  77. contextsynapse/api/context_router.py +1619 -0
  78. contextsynapse/api/dashboard_router.py +11367 -0
  79. contextsynapse/api/errors.py +183 -0
  80. contextsynapse/api/events.py +88 -0
  81. contextsynapse/api/experiment_bootstrap.py +321 -0
  82. contextsynapse/api/experiment_orchestrator.py +1078 -0
  83. contextsynapse/api/experiment_router.py +2089 -0
  84. contextsynapse/api/feature_gate.py +89 -0
  85. contextsynapse/api/federation_router.py +108 -0
  86. contextsynapse/api/integrations.py +567 -0
  87. contextsynapse/api/integrations_router.py +461 -0
  88. contextsynapse/api/intelligence_router.py +1028 -0
  89. contextsynapse/api/metering.py +155 -0
  90. contextsynapse/api/metrics.py +112 -0
  91. contextsynapse/api/models.py +38 -0
  92. contextsynapse/api/monitoring_router.py +174 -0
  93. contextsynapse/api/pipeline_router.py +1437 -0
  94. contextsynapse/api/playground_conn.py +116 -0
  95. contextsynapse/api/projects_router.py +131 -0
  96. contextsynapse/api/queries_router.py +282 -0
  97. contextsynapse/api/quota.py +95 -0
  98. contextsynapse/api/rate_limit.py +64 -0
  99. contextsynapse/api/search_router.py +261 -0
  100. contextsynapse/api/shield_router.py +447 -0
  101. contextsynapse/api/tenant_guard.py +103 -0
  102. contextsynapse/api/tenant_quotas.py +231 -0
  103. contextsynapse/api/tenants.py +305 -0
  104. contextsynapse/api/users.py +646 -0
  105. contextsynapse/api/v1.py +167 -0
  106. contextsynapse/api/vertical_builder_router.py +387 -0
  107. contextsynapse/benchmark/__init__.py +15 -0
  108. contextsynapse/benchmark/__main__.py +64 -0
  109. contextsynapse/benchmark/agents.py +338 -0
  110. contextsynapse/benchmark/live_ab.py +338 -0
  111. contextsynapse/benchmark/reporter.py +149 -0
  112. contextsynapse/benchmark/runner.py +264 -0
  113. contextsynapse/benchmark/savings.py +266 -0
  114. contextsynapse/benchmark/token_counter.py +212 -0
  115. contextsynapse/benchmark/workloads.py +289 -0
  116. contextsynapse/buffer/__init__.py +154 -0
  117. contextsynapse/buffer/base.py +257 -0
  118. contextsynapse/buffer/duckdb_buffer.py +246 -0
  119. contextsynapse/buffer/file_buffer.py +229 -0
  120. contextsynapse/buffer/lmdb_buffer.py +286 -0
  121. contextsynapse/buffer/local_buffer.py +154 -0
  122. contextsynapse/buffer/redis_buffer.py +211 -0
  123. contextsynapse/buffer/sqlite_buffer.py +266 -0
  124. contextsynapse/cache.py +2 -0
  125. contextsynapse/cli/__init__.py +40 -0
  126. contextsynapse/cli/cli.py +475 -0
  127. contextsynapse/cli/config_cli.py +177 -0
  128. contextsynapse/cli/scaffold.py +465 -0
  129. contextsynapse/cognition/__init__.py +31 -0
  130. contextsynapse/cognition/derivation.py +55 -0
  131. contextsynapse/cognition/events.py +135 -0
  132. contextsynapse/cognition/feedback.py +52 -0
  133. contextsynapse/cognition/hallucination.py +90 -0
  134. contextsynapse/cognition/invalidation.py +70 -0
  135. contextsynapse/cognition/read_tracker.py +50 -0
  136. contextsynapse/collaboration.py +2 -0
  137. contextsynapse/comparison.py +2 -0
  138. contextsynapse/config/__init__.py +10 -0
  139. contextsynapse/config/connectors/amfi_nav.yaml +18 -0
  140. contextsynapse/config/connectors/auto_sector.yaml +20 -0
  141. contextsynapse/config/connectors/banking_sector.yaml +20 -0
  142. contextsynapse/config/connectors/energy_sector.yaml +20 -0
  143. contextsynapse/config/connectors/fmcg_sector.yaml +20 -0
  144. contextsynapse/config/connectors/nsdl_fpi.yaml +9 -0
  145. contextsynapse/config/connectors/nse_price.yaml +61 -0
  146. contextsynapse/config/connectors/pharma_sector.yaml +20 -0
  147. contextsynapse/config/connectors/rbi_dbie.yaml +12 -0
  148. contextsynapse/config/context_presets/ai_research.json +25 -0
  149. contextsynapse/config/context_presets/chatgpt_conversations.json +19 -0
  150. contextsynapse/config/context_presets/claude_conversations.json +19 -0
  151. contextsynapse/config/context_presets/legal_compliance.json +21 -0
  152. contextsynapse/config/context_presets/meeting_notes.json +21 -0
  153. contextsynapse/config/context_presets/slack_engineering.json +21 -0
  154. contextsynapse/config/context_presets/tech_climate.json +24 -0
  155. contextsynapse/config/context_presets/toi_politics.json +25 -0
  156. contextsynapse/config/database_config.py +453 -0
  157. contextsynapse/config/deployment.py +221 -0
  158. contextsynapse/config/gpt_action_schema.json +164 -0
  159. contextsynapse/config/indicators/india_macro.yaml +213 -0
  160. contextsynapse/config/logging_config.py +88 -0
  161. contextsynapse/config/mode_config.py +223 -0
  162. contextsynapse/config/schemas/api_spec.yaml +48 -0
  163. contextsynapse/config/schemas/architecture_doc.yaml +51 -0
  164. contextsynapse/config/schemas/chat_history.yaml +90 -0
  165. contextsynapse/config/schemas/chatgpt_conversation.yaml +101 -0
  166. contextsynapse/config/schemas/claude_conversation.yaml +148 -0
  167. contextsynapse/config/schemas/contract.yaml +48 -0
  168. contextsynapse/config/schemas/conversation.yaml +167 -0
  169. contextsynapse/config/schemas/database.yaml +74 -0
  170. contextsynapse/config/schemas/decision.yaml +72 -0
  171. contextsynapse/config/schemas/ecommerce.yaml +56 -0
  172. contextsynapse/config/schemas/education.yaml +42 -0
  173. contextsynapse/config/schemas/healthcare.yaml +133 -0
  174. contextsynapse/config/schemas/hr_document.yaml +48 -0
  175. contextsynapse/config/schemas/invoice.yaml +40 -0
  176. contextsynapse/config/schemas/knowledge_base.yaml +75 -0
  177. contextsynapse/config/schemas/legal.yaml +42 -0
  178. contextsynapse/config/schemas/marketing_content.yaml +48 -0
  179. contextsynapse/config/schemas/meeting_notes.yaml +51 -0
  180. contextsynapse/config/schemas/news_article.yaml +61 -0
  181. contextsynapse/config/schemas/real_estate.yaml +49 -0
  182. contextsynapse/config/schemas/requirements_doc.yaml +48 -0
  183. contextsynapse/config/schemas/research_paper.yaml +56 -0
  184. contextsynapse/config/schemas/resume.yaml +49 -0
  185. contextsynapse/config/schemas/retail.yaml +42 -0
  186. contextsynapse/config/schemas/rule_meta.yaml +173 -0
  187. contextsynapse/config/schemas/rules.yaml +72 -0
  188. contextsynapse/config/schemas/screener_meta.yaml +236 -0
  189. contextsynapse/config/schemas/sdlc.yaml +103 -0
  190. contextsynapse/config/schemas/session_graph.yaml +172 -0
  191. contextsynapse/config/schemas/support_ticket.yaml +48 -0
  192. contextsynapse/config/schemas/web.yaml +64 -0
  193. contextsynapse/config/sensors/earnings_calendar.yaml +52 -0
  194. contextsynapse/config/sensors/global_risk.yaml +53 -0
  195. contextsynapse/config/sensors/government_policy.yaml +54 -0
  196. contextsynapse/config/sensors/supply_chain.yaml +50 -0
  197. contextsynapse/config/sensors/templates/behavioral.yaml +56 -0
  198. contextsynapse/config/sensors/templates/equity_sentiment.yaml +48 -0
  199. contextsynapse/config/sensors/templates/global_macro.yaml +47 -0
  200. contextsynapse/config/sensors/templates/market_data.yaml +118 -0
  201. contextsynapse/config/sensors/templates/sector_technical.yaml +47 -0
  202. contextsynapse/config/sensors/weather.yaml +52 -0
  203. contextsynapse/config/storage_strategy.py +202 -0
  204. contextsynapse/config/templates/competitive_intel.yaml +39 -0
  205. contextsynapse/config/templates/geopolitical_risk.yaml +46 -0
  206. contextsynapse/config/templates/market_analysis.yaml +58 -0
  207. contextsynapse/connectors/__init__.py +15 -0
  208. contextsynapse/connectors/api_router.py +121 -0
  209. contextsynapse/connectors/base.py +357 -0
  210. contextsynapse/connectors/financial/audio.py +170 -0
  211. contextsynapse/connectors/financial/youtube.py +272 -0
  212. contextsynapse/connectors/github.py +164 -0
  213. contextsynapse/connectors/jira.py +120 -0
  214. contextsynapse/connectors/kafka_connector.py +124 -0
  215. contextsynapse/connectors/pipeline_connector.py +747 -0
  216. contextsynapse/connectors/registry.py +116 -0
  217. contextsynapse/connectors/scheduler.py +87 -0
  218. contextsynapse/connectors/universal.py +360 -0
  219. contextsynapse/context/__init__.py +96 -0
  220. contextsynapse/context/__main__.py +4 -0
  221. contextsynapse/context/acl.py +125 -0
  222. contextsynapse/context/agent_card.py +201 -0
  223. contextsynapse/context/agent_memory.py +814 -0
  224. contextsynapse/context/agents.py +472 -0
  225. contextsynapse/context/agents_redis.py +391 -0
  226. contextsynapse/context/assembled.py +204 -0
  227. contextsynapse/context/attribution.py +113 -0
  228. contextsynapse/context/blob.py +184 -0
  229. contextsynapse/context/boundaries.py +187 -0
  230. contextsynapse/context/boundary.py +507 -0
  231. contextsynapse/context/bundle.py +155 -0
  232. contextsynapse/context/cli.py +519 -0
  233. contextsynapse/context/collaboration.py +165 -0
  234. contextsynapse/context/compiler.py +604 -0
  235. contextsynapse/context/composite.py +536 -0
  236. contextsynapse/context/compression.py +147 -0
  237. contextsynapse/context/context_manager.py +888 -0
  238. contextsynapse/context/context_schema.py +90 -0
  239. contextsynapse/context/context_schema.yaml +105 -0
  240. contextsynapse/context/context_units.py +891 -0
  241. contextsynapse/context/conversation.py +488 -0
  242. contextsynapse/context/dedup.py +207 -0
  243. contextsynapse/context/document_processor.py +698 -0
  244. contextsynapse/context/embedding_hooks.py +338 -0
  245. contextsynapse/context/execution_schema.py +274 -0
  246. contextsynapse/context/fan_out.py +138 -0
  247. contextsynapse/context/frozen.py +80 -0
  248. contextsynapse/context/gravity.py +227 -0
  249. contextsynapse/context/hub.py +1401 -0
  250. contextsynapse/context/ingest.py +391 -0
  251. contextsynapse/context/injection.py +226 -0
  252. contextsynapse/context/interaction_graphifier.py +562 -0
  253. contextsynapse/context/layers.py +574 -0
  254. contextsynapse/context/projection.py +1195 -0
  255. contextsynapse/context/promotion.py +634 -0
  256. contextsynapse/context/proof.py +131 -0
  257. contextsynapse/context/propagation.py +577 -0
  258. contextsynapse/context/pubsub.py +135 -0
  259. contextsynapse/context/quality.py +1054 -0
  260. contextsynapse/context/quality_tracker.py +270 -0
  261. contextsynapse/context/scoping.py +370 -0
  262. contextsynapse/context/seed.py +992 -0
  263. contextsynapse/context/session.py +1142 -0
  264. contextsynapse/context/session_graph.py +593 -0
  265. contextsynapse/context/session_memory.py +309 -0
  266. contextsynapse/context/session_resolver.py +111 -0
  267. contextsynapse/context/skill_learning.py +237 -0
  268. contextsynapse/context/smart_budget.py +129 -0
  269. contextsynapse/context/source_policy.py +242 -0
  270. contextsynapse/context/store_factory.py +53 -0
  271. contextsynapse/context/sync.py +648 -0
  272. contextsynapse/context/token.py +236 -0
  273. contextsynapse/context/vector_integration.py +297 -0
  274. contextsynapse/context/webhooks.py +194 -0
  275. contextsynapse/context/working_memory.py +224 -0
  276. contextsynapse/core/__init__.py +18 -0
  277. contextsynapse/core/archiver.py +237 -0
  278. contextsynapse/core/change_stream.py +282 -0
  279. contextsynapse/core/checkpoint.py +310 -0
  280. contextsynapse/core/cloud_storage.py +387 -0
  281. contextsynapse/core/context_state.py +651 -0
  282. contextsynapse/core/cron.py +324 -0
  283. contextsynapse/core/datasource.py +643 -0
  284. contextsynapse/core/db.py +289 -0
  285. contextsynapse/core/federation.py +283 -0
  286. contextsynapse/core/graph_coordinator.py +201 -0
  287. contextsynapse/core/graph_intelligence.py +388 -0
  288. contextsynapse/core/graph_structures.py +106 -0
  289. contextsynapse/core/graph_sync.py +157 -0
  290. contextsynapse/core/hybrid_graph_storage.py +2998 -0
  291. contextsynapse/core/lifecycle.py +691 -0
  292. contextsynapse/core/multiworker.py +378 -0
  293. contextsynapse/core/pruning.py +312 -0
  294. contextsynapse/core/redis_registry.py +524 -0
  295. contextsynapse/core/registry.py +1043 -0
  296. contextsynapse/core/registry_factory.py +51 -0
  297. contextsynapse/core/registry_metadata.py +294 -0
  298. contextsynapse/core/replay.py +354 -0
  299. contextsynapse/core/replication.py +339 -0
  300. contextsynapse/core/time_travel.py +260 -0
  301. contextsynapse/core/write_behind.py +152 -0
  302. contextsynapse/core/write_context.py +39 -0
  303. contextsynapse/db/__init__.py +1 -0
  304. contextsynapse/db/postgres.py +267 -0
  305. contextsynapse/db/profile.py +236 -0
  306. contextsynapse/db/rules.py +328 -0
  307. contextsynapse/demo/__init__.py +0 -0
  308. contextsynapse/demo/report.py +147 -0
  309. contextsynapse/demo/runner.py +520 -0
  310. contextsynapse/demo/scenario.py +165 -0
  311. contextsynapse/demo/session_demo.py +280 -0
  312. contextsynapse/demo/session_report.py +143 -0
  313. contextsynapse/demo/universal_runner.py +257 -0
  314. contextsynapse/engine/__init__.py +15 -0
  315. contextsynapse/engine/core.py +555 -0
  316. contextsynapse/extraction/__init__.py +69 -0
  317. contextsynapse/extraction/cli.py +274 -0
  318. contextsynapse/extraction/config.py +107 -0
  319. contextsynapse/extraction/examples/example_usage.py +118 -0
  320. contextsynapse/extraction/examples/sample_manifest.json +53 -0
  321. contextsynapse/extraction/examples/sample_normalized.json +185 -0
  322. contextsynapse/extraction/extract_engine.py +440 -0
  323. contextsynapse/extraction/extractors/__init__.py +37 -0
  324. contextsynapse/extraction/extractors/chat_export_extractor.py +189 -0
  325. contextsynapse/extraction/extractors/csv_extractor.py +83 -0
  326. contextsynapse/extraction/extractors/docx_extractor.py +129 -0
  327. contextsynapse/extraction/extractors/excel_extractor.py +152 -0
  328. contextsynapse/extraction/extractors/html_extractor.py +146 -0
  329. contextsynapse/extraction/extractors/pdf_extractor.py +635 -0
  330. contextsynapse/extraction/extractors/pdf_extractor_layoutparser.py +408 -0
  331. contextsynapse/extraction/extractors/register_extractors.py +63 -0
  332. contextsynapse/extraction/extractors/text_extractor.py +65 -0
  333. contextsynapse/extraction/extractors/txt_extractor.py +120 -0
  334. contextsynapse/extraction/extractors/website_extractor.py +246 -0
  335. contextsynapse/extraction/fact_extractor.py +236 -0
  336. contextsynapse/extraction/file_manager.py +353 -0
  337. contextsynapse/extraction/hierarchy.py +239 -0
  338. contextsynapse/extraction/id_generator.py +450 -0
  339. contextsynapse/extraction/layout_detector.py +409 -0
  340. contextsynapse/extraction/llm_entity_extractor.py +301 -0
  341. contextsynapse/extraction/normalized_store.py +480 -0
  342. contextsynapse/extraction/normalizer.py +594 -0
  343. contextsynapse/extraction/parquet_writer.py +598 -0
  344. contextsynapse/extraction/post_processors/__init__.py +40 -0
  345. contextsynapse/extraction/post_processors/column_reorganizer.py +507 -0
  346. contextsynapse/extraction/ray_normalization.py +233 -0
  347. contextsynapse/extraction/ray_runner.py +207 -0
  348. contextsynapse/extraction/redis_schema_registry.py +222 -0
  349. contextsynapse/extraction/registry.py +204 -0
  350. contextsynapse/extraction/schema_loader.py +663 -0
  351. contextsynapse/extraction/schema_registry.py +230 -0
  352. contextsynapse/extraction/semantic_normalizer.py +245 -0
  353. contextsynapse/extraction/version_manager.py +314 -0
  354. contextsynapse/gateway/__init__.py +24 -0
  355. contextsynapse/gateway/action_emitter.py +212 -0
  356. contextsynapse/gateway/cost_tracker.py +508 -0
  357. contextsynapse/gateway/gateway.py +377 -0
  358. contextsynapse/gateway/policy.py +303 -0
  359. contextsynapse/governance/__init__.py +13 -0
  360. contextsynapse/governance/layer.py +513 -0
  361. contextsynapse/ingestion/__init__.py +15 -0
  362. contextsynapse/ingestion/amplifier.py +288 -0
  363. contextsynapse/ingestion/async_ingest.py +463 -0
  364. contextsynapse/ingestion/chunker.py +303 -0
  365. contextsynapse/ingestion/chunking.py +58 -0
  366. contextsynapse/ingestion/cleaner.py +190 -0
  367. contextsynapse/ingestion/cleanse.py +252 -0
  368. contextsynapse/ingestion/connectors/__init__.py +38 -0
  369. contextsynapse/ingestion/connectors/base.py +300 -0
  370. contextsynapse/ingestion/connectors/chatgpt_memory.py +247 -0
  371. contextsynapse/ingestion/connectors/claude_memory.py +274 -0
  372. contextsynapse/ingestion/connectors/sap_ingestor.py +208 -0
  373. contextsynapse/ingestion/content_detector.py +80 -0
  374. contextsynapse/ingestion/content_monitor.py +502 -0
  375. contextsynapse/ingestion/dedup.py +106 -0
  376. contextsynapse/ingestion/feed.py +640 -0
  377. contextsynapse/ingestion/filters.py +461 -0
  378. contextsynapse/ingestion/graph_builder.py +705 -0
  379. contextsynapse/ingestion/input_classifier.py +307 -0
  380. contextsynapse/ingestion/job_manager.py +571 -0
  381. contextsynapse/ingestion/llm_extractor.py +610 -0
  382. contextsynapse/ingestion/orchestrator.py +116 -0
  383. contextsynapse/ingestion/parsers/__init__.py +19 -0
  384. contextsynapse/ingestion/parsers/graph_parser_registry.py +103 -0
  385. contextsynapse/ingestion/parsers/graphml_parser.py +141 -0
  386. contextsynapse/ingestion/parsers/jsonld_parser.py +171 -0
  387. contextsynapse/ingestion/parsers/rdf_parser.py +150 -0
  388. contextsynapse/ingestion/pipeline_context.py +228 -0
  389. contextsynapse/ingestion/pipeline_store.py +1195 -0
  390. contextsynapse/ingestion/queue.py +133 -0
  391. contextsynapse/ingestion/reprocess.py +179 -0
  392. contextsynapse/ingestion/scenario_router.py +224 -0
  393. contextsynapse/ingestion/schema_extractor.py +759 -0
  394. contextsynapse/ingestion/schema_validator.py +274 -0
  395. contextsynapse/ingestion/sdlc_ingest.py +87 -0
  396. contextsynapse/ingestion/smart_ingest.py +2451 -0
  397. contextsynapse/ingestion/source_connector.py +171 -0
  398. contextsynapse/ingestion/stage_executor.py +2095 -0
  399. contextsynapse/ingestion/stages/__init__.py +9 -0
  400. contextsynapse/ingestion/stages/tabular_to_graph.py +289 -0
  401. contextsynapse/ingestion/strategies.py +386 -0
  402. contextsynapse/ingestion/universal/__init__.py +4 -0
  403. contextsynapse/ingestion/universal/_operator_registry.py +59 -0
  404. contextsynapse/ingestion/universal/ingest_content.py +32 -0
  405. contextsynapse/ingestion/universal/operators/__init__.py +1 -0
  406. contextsynapse/ingestion/universal/operators/base.py +19 -0
  407. contextsynapse/ingestion/universal/operators/build_edges.py +75 -0
  408. contextsynapse/ingestion/universal/operators/cluster_topics.py +397 -0
  409. contextsynapse/ingestion/universal/operators/deduplicate.py +45 -0
  410. contextsynapse/ingestion/universal/operators/detect_signals.py +90 -0
  411. contextsynapse/ingestion/universal/operators/embed.py +80 -0
  412. contextsynapse/ingestion/universal/operators/extract_entities.py +253 -0
  413. contextsynapse/ingestion/universal/operators/extract_preferences.py +117 -0
  414. contextsynapse/ingestion/universal/operators/filter_content.py +69 -0
  415. contextsynapse/ingestion/universal/operators/index_bm25.py +52 -0
  416. contextsynapse/ingestion/universal/operators/infer_domains.py +69 -0
  417. contextsynapse/ingestion/universal/operators/link_cross_reference.py +210 -0
  418. contextsynapse/ingestion/universal/operators/parse_records.py +66 -0
  419. contextsynapse/ingestion/universal/operators/resolve_entities.py +261 -0
  420. contextsynapse/ingestion/universal/operators/scanners/__init__.py +16 -0
  421. contextsynapse/ingestion/universal/operators/scanners/edges.py +173 -0
  422. contextsynapse/ingestion/universal/operators/scanners/git.py +187 -0
  423. contextsynapse/ingestion/universal/operators/scanners/github.py +135 -0
  424. contextsynapse/ingestion/universal/operators/scanners/github_api.py +509 -0
  425. contextsynapse/ingestion/universal/operators/scanners/helpers.py +67 -0
  426. contextsynapse/ingestion/universal/operators/scanners/jira.py +65 -0
  427. contextsynapse/ingestion/universal/operators/scanners/llm_enrichment.py +82 -0
  428. contextsynapse/ingestion/universal/operators/scanners/repo.py +149 -0
  429. contextsynapse/ingestion/universal/operators/sdlc_scan.py +213 -0
  430. contextsynapse/ingestion/universal/operators/spec_scanner.py +149 -0
  431. contextsynapse/ingestion/universal/operators/store_documents.py +72 -0
  432. contextsynapse/ingestion/universal/operators/synthesize_cu.py +180 -0
  433. contextsynapse/ingestion/universal/operators/validate_gate.py +65 -0
  434. contextsynapse/ingestion/universal/parsers/__init__.py +5 -0
  435. contextsynapse/ingestion/universal/parsers/record_parser.py +203 -0
  436. contextsynapse/ingestion/universal/parsers/turn_parser.py +329 -0
  437. contextsynapse/ingestion/universal/shared_signals.py +161 -0
  438. contextsynapse/ingestion/universal/stage_executor.py +219 -0
  439. contextsynapse/ingestion/web_crawler.py +265 -0
  440. contextsynapse/intelligence/__init__.py +53 -0
  441. contextsynapse/intelligence/alerts.py +198 -0
  442. contextsynapse/intelligence/collector.py +655 -0
  443. contextsynapse/intelligence/comparison.py +198 -0
  444. contextsynapse/intelligence/config.py +56 -0
  445. contextsynapse/intelligence/conflict_detector.py +182 -0
  446. contextsynapse/intelligence/context_gaps.py +192 -0
  447. contextsynapse/intelligence/context_radar.py +135 -0
  448. contextsynapse/intelligence/correlation_engine.py +416 -0
  449. contextsynapse/intelligence/correlation_template.py +120 -0
  450. contextsynapse/intelligence/dedup.py +296 -0
  451. contextsynapse/intelligence/event_bus.py +91 -0
  452. contextsynapse/intelligence/feedback_loop.py +101 -0
  453. contextsynapse/intelligence/freshness.py +307 -0
  454. contextsynapse/intelligence/fundamental_feed.py +551 -0
  455. contextsynapse/intelligence/geo_data.py +170 -0
  456. contextsynapse/intelligence/geo_reference.py +112 -0
  457. contextsynapse/intelligence/graph_fusion.py +465 -0
  458. contextsynapse/intelligence/heuristics.py +176 -0
  459. contextsynapse/intelligence/impact_tracker.py +336 -0
  460. contextsynapse/intelligence/macro_indicators.py +319 -0
  461. contextsynapse/intelligence/ocr.py +104 -0
  462. contextsynapse/intelligence/persistence.py +267 -0
  463. contextsynapse/intelligence/pipeline_health.py +130 -0
  464. contextsynapse/intelligence/price_feed.py +221 -0
  465. contextsynapse/intelligence/rate_limiter.py +130 -0
  466. contextsynapse/intelligence/reactive.py +411 -0
  467. contextsynapse/intelligence/runtime_context.py +390 -0
  468. contextsynapse/intelligence/sentiment_decay.py +426 -0
  469. contextsynapse/intelligence/session.py +277 -0
  470. contextsynapse/intelligence/signal_hierarchy.py +438 -0
  471. contextsynapse/intelligence/signals.py +185 -0
  472. contextsynapse/intelligence/source_watcher.py +132 -0
  473. contextsynapse/intelligence/table_enricher.py +256 -0
  474. contextsynapse/intelligence/tagger.py +319 -0
  475. contextsynapse/intelligence/timeseries.py +209 -0
  476. contextsynapse/intelligence/tracker.py +318 -0
  477. contextsynapse/intelligence/watchdog.py +392 -0
  478. contextsynapse/intelligence/watchdog_manager.py +263 -0
  479. contextsynapse/intelligence/webhook_receiver.py +165 -0
  480. contextsynapse/intelligence/weight_learner.py +234 -0
  481. contextsynapse/llm/__init__.py +8 -0
  482. contextsynapse/llm/client.py +348 -0
  483. contextsynapse/llm/rate_limiter.py +166 -0
  484. contextsynapse/logging_config.py +2 -0
  485. contextsynapse/marketplace/__init__.py +7 -0
  486. contextsynapse/marketplace/registry.py +173 -0
  487. contextsynapse/mcp/__init__.py +11 -0
  488. contextsynapse/mcp/__main__.py +4 -0
  489. contextsynapse/mcp/auth_middleware.py +212 -0
  490. contextsynapse/mcp/connection_pool.py +128 -0
  491. contextsynapse/mcp/server.py +986 -0
  492. contextsynapse/mcp/session_context.py +67 -0
  493. contextsynapse/memory/__init__.py +34 -0
  494. contextsynapse/memory/engine.py +475 -0
  495. contextsynapse/memory/temporal.py +327 -0
  496. contextsynapse/metadata/__init__.py +12 -0
  497. contextsynapse/metadata/metadata_db.py +272 -0
  498. contextsynapse/metadata/metadata_query_tool.py +300 -0
  499. contextsynapse/metadata/metadata_tracker.py +425 -0
  500. contextsynapse/models/__init__.py +27 -0
  501. contextsynapse/models/embedding_service.py +360 -0
  502. contextsynapse/models/model_registry.py +228 -0
  503. contextsynapse/multiworker.py +2 -0
  504. contextsynapse/pipelines/__init__.py +1 -0
  505. contextsynapse/pipelines/executor.py +851 -0
  506. contextsynapse/pipelines/filters.py +189 -0
  507. contextsynapse/pipelines/models.py +176 -0
  508. contextsynapse/pipelines/scheduler.py +268 -0
  509. contextsynapse/playground/__init__.py +1 -0
  510. contextsynapse/playground/templates.py +85 -0
  511. contextsynapse/plugins/__init__.py +43 -0
  512. contextsynapse/plugins/api.py +66 -0
  513. contextsynapse/plugins/base.py +350 -0
  514. contextsynapse/plugins/domain_interface.py +508 -0
  515. contextsynapse/plugins/domain_loader.py +241 -0
  516. contextsynapse/plugins/loader.py +148 -0
  517. contextsynapse/plugins/registry.py +265 -0
  518. contextsynapse/project/__init__.py +11 -0
  519. contextsynapse/project/code_context.py +807 -0
  520. contextsynapse/project/connectors/__init__.py +4 -0
  521. contextsynapse/project/connectors/github_connector.py +113 -0
  522. contextsynapse/project/connectors/jira_connector.py +160 -0
  523. contextsynapse/project/graph.py +1023 -0
  524. contextsynapse/project/project_context.py +545 -0
  525. contextsynapse/project/scanner_registry.py +61 -0
  526. contextsynapse/project/schema_manager.py +322 -0
  527. contextsynapse/project/schemas/knowledge.yaml +59 -0
  528. contextsynapse/project/schemas/sdlc.yaml +369 -0
  529. contextsynapse/project/sdlc_schema.py +172 -0
  530. contextsynapse/project/spec_parser.py +85 -0
  531. contextsynapse/project/task_lock.py +181 -0
  532. contextsynapse/project/task_stream.py +203 -0
  533. contextsynapse/project/team_tools.py +537 -0
  534. contextsynapse/py.typed +0 -0
  535. contextsynapse/realtime/__init__.py +6 -0
  536. contextsynapse/realtime/collaboration.py +147 -0
  537. contextsynapse/rules/__init__.py +10 -0
  538. contextsynapse/rules/engine.py +116 -0
  539. contextsynapse/rules/evaluators/__init__.py +6 -0
  540. contextsynapse/rules/evaluators/aggregate.py +205 -0
  541. contextsynapse/rules/evaluators/custom.py +170 -0
  542. contextsynapse/rules/evaluators/pre_action.py +125 -0
  543. contextsynapse/rules/evaluators/temporal.py +129 -0
  544. contextsynapse/rules/loader.py +52 -0
  545. contextsynapse/rules/models.py +124 -0
  546. contextsynapse/rules/universal.py +393 -0
  547. contextsynapse/scheduler.py +229 -0
  548. contextsynapse/schema/__init__.py +42 -0
  549. contextsynapse/schema/compiler.py +252 -0
  550. contextsynapse/schema/composer.py +158 -0
  551. contextsynapse/schema/dedup.py +73 -0
  552. contextsynapse/schema/derivation.py +172 -0
  553. contextsynapse/schema/sdl.py +326 -0
  554. contextsynapse/schema/validation_gate.py +124 -0
  555. contextsynapse/sdk/__init__.py +63 -0
  556. contextsynapse/sdk/agent.py +214 -0
  557. contextsynapse/sdk/client.py +269 -0
  558. contextsynapse/sdk/exceptions.py +23 -0
  559. contextsynapse/sdk/models.py +78 -0
  560. contextsynapse/sdk/session.py +408 -0
  561. contextsynapse/sdk/tracked.py +218 -0
  562. contextsynapse/sdk/worker.py +266 -0
  563. contextsynapse/sdk/workspace_client.py +98 -0
  564. contextsynapse/sdk/ws.py +41 -0
  565. contextsynapse/search/__init__.py +20 -0
  566. contextsynapse/search/embedding_cache.py +140 -0
  567. contextsynapse/search/enhanced_search.py +152 -0
  568. contextsynapse/search/fulltext.py +130 -0
  569. contextsynapse/search/graph_search.py +634 -0
  570. contextsynapse/search/lmdb_index.py +1218 -0
  571. contextsynapse/search/nl_to_aiql.py +199 -0
  572. contextsynapse/search/rag.py +1346 -0
  573. contextsynapse/search/rag_cache.py +167 -0
  574. contextsynapse/search/reasoning_chain.py +231 -0
  575. contextsynapse/search/redis_search.py +207 -0
  576. contextsynapse/search/retrieval_quality.py +314 -0
  577. contextsynapse/search/semantic_query.py +455 -0
  578. contextsynapse/search/text_resolver.py +159 -0
  579. contextsynapse/search/whoosh_search.py +373 -0
  580. contextsynapse/security/__init__.py +17 -0
  581. contextsynapse/security/audit.py +297 -0
  582. contextsynapse/security/audit_logger.py +97 -0
  583. contextsynapse/security/audit_trail.py +270 -0
  584. contextsynapse/security/auth_unified.py +284 -0
  585. contextsynapse/security/auto_tagger.py +230 -0
  586. contextsynapse/security/data_security.py +218 -0
  587. contextsynapse/security/encryption.py +207 -0
  588. contextsynapse/security/identity.py +447 -0
  589. contextsynapse/security/jwt_identity.py +59 -0
  590. contextsynapse/security/middleware.py +336 -0
  591. contextsynapse/security/pii.py +233 -0
  592. contextsynapse/security/rbac.py +96 -0
  593. contextsynapse/security/rls.py +205 -0
  594. contextsynapse/security/sanitize.py +233 -0
  595. contextsynapse/security/scoped_encryption.py +131 -0
  596. contextsynapse/security/tenant.py +401 -0
  597. contextsynapse/shield/__init__.py +21 -0
  598. contextsynapse/shield/anomaly.py +56 -0
  599. contextsynapse/shield/permissions.py +99 -0
  600. contextsynapse/shield/profile.py +103 -0
  601. contextsynapse/shield/shield.py +108 -0
  602. contextsynapse/shield/trust_engine.py +69 -0
  603. contextsynapse/skills/__init__.py +14 -0
  604. contextsynapse/skills/engine.py +233 -0
  605. contextsynapse/skills/loader.py +59 -0
  606. contextsynapse/skills/models.py +139 -0
  607. contextsynapse/storage/__init__.py +7 -0
  608. contextsynapse/storage/cache.py +208 -0
  609. contextsynapse/storage/columnar_store_v2.py +178 -0
  610. contextsynapse/storage/csr_graph_storage.py +587 -0
  611. contextsynapse/storage/csr_store.py +388 -0
  612. contextsynapse/storage/document_store.py +491 -0
  613. contextsynapse/storage/hnsw_index.py +294 -0
  614. contextsynapse/storage/hybrid_store_v2.py +278 -0
  615. contextsynapse/storage/lmdb_graph_storage.py +366 -0
  616. contextsynapse/storage/migration.py +279 -0
  617. contextsynapse/storage/namespace_store.py +346 -0
  618. contextsynapse/storage/pure_graph_storage.py +185 -0
  619. contextsynapse/storage/redis_graph_adapter.py +186 -0
  620. contextsynapse/storage/redis_graph_storage.py +375 -0
  621. contextsynapse/storage/router/__init__.py +29 -0
  622. contextsynapse/storage/router/duckdb_store.py +398 -0
  623. contextsynapse/storage/router/factory.py +83 -0
  624. contextsynapse/storage/router/interface.py +125 -0
  625. contextsynapse/storage/router/postgres_store.py +339 -0
  626. contextsynapse/storage/router/resolver.py +192 -0
  627. contextsynapse/storage/router/router.py +300 -0
  628. contextsynapse/storage/single_file_storage.py +391 -0
  629. contextsynapse/storage/storage_manager.py +214 -0
  630. contextsynapse/storage/storage_query_optimizer.py +314 -0
  631. contextsynapse/storage/wal.py +359 -0
  632. contextsynapse/temporal/__init__.py +0 -0
  633. contextsynapse/temporal/storage.py +106 -0
  634. contextsynapse/tests/__init__.py +11 -0
  635. contextsynapse/tests/regression/__init__.py +1 -0
  636. contextsynapse/tests/regression/add_metadata.py +395 -0
  637. contextsynapse/tests/regression/add_skip_flags.py +85 -0
  638. contextsynapse/tests/regression/cases/test_basic_create_node.yaml +20 -0
  639. contextsynapse/tests/regression/cases/test_basic_select.yaml +21 -0
  640. contextsynapse/tests/regression/cases/test_blockchain_audit_trail.yaml +37 -0
  641. contextsynapse/tests/regression/cases/test_blockchain_audit_trail_filtered.yaml +39 -0
  642. contextsynapse/tests/regression/cases/test_blockchain_blocks_range.yaml +39 -0
  643. contextsynapse/tests/regression/cases/test_blockchain_get_block.yaml +35 -0
  644. contextsynapse/tests/regression/cases/test_blockchain_latest_block.yaml +35 -0
  645. contextsynapse/tests/regression/cases/test_blockchain_length.yaml +37 -0
  646. contextsynapse/tests/regression/cases/test_blockchain_merkle_root.yaml +37 -0
  647. contextsynapse/tests/regression/cases/test_blockchain_verify.yaml +35 -0
  648. contextsynapse/tests/regression/cases/test_blockchain_verify_block.yaml +35 -0
  649. contextsynapse/tests/regression/cases/test_create_edge.yaml +28 -0
  650. contextsynapse/tests/regression/cases/test_delete_edge_basic.yaml +29 -0
  651. contextsynapse/tests/regression/cases/test_delete_node_basic.yaml +29 -0
  652. contextsynapse/tests/regression/cases/test_evaluation_mrr.yaml +40 -0
  653. contextsynapse/tests/regression/cases/test_evaluation_ndcg.yaml +40 -0
  654. contextsynapse/tests/regression/cases/test_evaluation_precision.yaml +40 -0
  655. contextsynapse/tests/regression/cases/test_evaluation_recall.yaml +40 -0
  656. contextsynapse/tests/regression/cases/test_group_by_basic.yaml +56 -0
  657. contextsynapse/tests/regression/cases/test_match_node_basic.yaml +29 -0
  658. contextsynapse/tests/regression/cases/test_match_node_with_order_limit.yaml +31 -0
  659. contextsynapse/tests/regression/cases/test_namespace_switch.yaml +18 -0
  660. contextsynapse/tests/regression/cases/test_pipeline_cascaded.yaml +61 -0
  661. contextsynapse/tests/regression/cases/test_pipeline_fixed_size_chunking.yaml +48 -0
  662. contextsynapse/tests/regression/cases/test_pipeline_gpt4_chunking.yaml +54 -0
  663. contextsynapse/tests/regression/cases/test_pipeline_hybrid_indexing.yaml +57 -0
  664. contextsynapse/tests/regression/cases/test_pipeline_large_embedding.yaml +52 -0
  665. contextsynapse/tests/regression/cases/test_pipeline_paragraph_chunking.yaml +49 -0
  666. contextsynapse/tests/regression/cases/test_pipeline_recursive_chunking.yaml +47 -0
  667. contextsynapse/tests/regression/cases/test_pipeline_run_pipeline.yaml +56 -0
  668. contextsynapse/tests/regression/cases/test_pipeline_section_based_chunking.yaml +53 -0
  669. contextsynapse/tests/regression/cases/test_pipeline_semantic_chunking.yaml +51 -0
  670. contextsynapse/tests/regression/cases/test_pipeline_with_entity_extraction.yaml +57 -0
  671. contextsynapse/tests/regression/cases/test_pipeline_with_relationships.yaml +62 -0
  672. contextsynapse/tests/regression/cases/test_rag_evaluation.yaml +38 -0
  673. contextsynapse/tests/regression/cases/test_rag_graph_bfs_with_eval.yaml +48 -0
  674. contextsynapse/tests/regression/cases/test_rag_graph_centrality.yaml +40 -0
  675. contextsynapse/tests/regression/cases/test_rag_graph_centrality_eval.yaml +35 -0
  676. contextsynapse/tests/regression/cases/test_rag_graph_community.yaml +40 -0
  677. contextsynapse/tests/regression/cases/test_rag_graph_community_eval.yaml +35 -0
  678. contextsynapse/tests/regression/cases/test_rag_graph_dfs_with_eval.yaml +35 -0
  679. contextsynapse/tests/regression/cases/test_rag_graph_multi_hop_eval.yaml +35 -0
  680. contextsynapse/tests/regression/cases/test_rag_graph_path.yaml +40 -0
  681. contextsynapse/tests/regression/cases/test_rag_graph_search_basic.yaml +38 -0
  682. contextsynapse/tests/regression/cases/test_rag_graph_search_bfs.yaml +52 -0
  683. contextsynapse/tests/regression/cases/test_rag_graph_search_dfs.yaml +41 -0
  684. contextsynapse/tests/regression/cases/test_rag_graph_search_multi_hop.yaml +43 -0
  685. contextsynapse/tests/regression/cases/test_rag_graph_search_shortest_path.yaml +41 -0
  686. contextsynapse/tests/regression/cases/test_rag_graph_search_weighted.yaml +43 -0
  687. contextsynapse/tests/regression/cases/test_rag_graph_shortest_path_eval.yaml +35 -0
  688. contextsynapse/tests/regression/cases/test_rag_graph_traversal.yaml +30 -0
  689. contextsynapse/tests/regression/cases/test_rag_graph_weighted_eval.yaml +35 -0
  690. contextsynapse/tests/regression/cases/test_rag_hybrid_search.yaml +33 -0
  691. contextsynapse/tests/regression/cases/test_rag_hybrid_with_prompt_embedding.yaml +44 -0
  692. contextsynapse/tests/regression/cases/test_rag_keyword_search.yaml +32 -0
  693. contextsynapse/tests/regression/cases/test_rag_multi_hop_graph.yaml +32 -0
  694. contextsynapse/tests/regression/cases/test_rag_path_based.yaml +34 -0
  695. contextsynapse/tests/regression/cases/test_rag_profile_based.yaml +32 -0
  696. contextsynapse/tests/regression/cases/test_rag_vector_search.yaml +32 -0
  697. contextsynapse/tests/regression/cases/test_rag_weighted_graph.yaml +34 -0
  698. contextsynapse/tests/regression/cases/test_rag_weighted_hybrid.yaml +31 -0
  699. contextsynapse/tests/regression/cases/test_semantic_boundary_chunking.yaml +57 -0
  700. contextsynapse/tests/regression/cases/test_semantic_boundary_detection.yaml +33 -0
  701. contextsynapse/tests/regression/cases/test_semantic_hash_function.yaml +30 -0
  702. contextsynapse/tests/regression/cases/test_semantic_hash_with_model.yaml +31 -0
  703. contextsynapse/tests/regression/cases/test_tcs_ingestion_fixed_size.yaml +44 -0
  704. contextsynapse/tests/regression/cases/test_tcs_ingestion_recursive.yaml +46 -0
  705. contextsynapse/tests/regression/cases/test_tcs_ingestion_section.yaml +46 -0
  706. contextsynapse/tests/regression/cases/test_tcs_ingestion_semantic.yaml +44 -0
  707. contextsynapse/tests/regression/cases/test_time_travel_as_of.yaml +35 -0
  708. contextsynapse/tests/regression/cases/test_time_travel_at_commit.yaml +33 -0
  709. contextsynapse/tests/regression/cases/test_time_travel_at_timestamp.yaml +33 -0
  710. contextsynapse/tests/regression/cases/test_time_travel_for_system_time_all.yaml +37 -0
  711. contextsynapse/tests/regression/cases/test_time_travel_versions_between.yaml +39 -0
  712. contextsynapse/tests/regression/cases/test_traverse_basic.yaml +31 -0
  713. contextsynapse/tests/regression/cases/test_traverse_max_depth.yaml +34 -0
  714. contextsynapse/tests/regression/cases/test_update_edge_basic.yaml +29 -0
  715. contextsynapse/tests/regression/evaluation_metrics.py +227 -0
  716. contextsynapse/tests/regression/regression_runner.py +1081 -0
  717. contextsynapse/tests/regression/setup_regression_data.py +212 -0
  718. contextsynapse/tests/regression/test_basic_only.py +84 -0
  719. contextsynapse/tests/regression/test_namespace_creation.py +29 -0
  720. contextsynapse/tests/regression/test_single_fix.py +61 -0
  721. contextsynapse/tests/regression/test_single_query.py +20 -0
  722. contextsynapse/tests/regression/validate_test_syntax.py +179 -0
  723. contextsynapse/tests/test_advanced_features.py +347 -0
  724. contextsynapse/tests/test_aiql_summary.py +283 -0
  725. contextsynapse/tests/test_all_aiql_queries.py +948 -0
  726. contextsynapse/tests/test_all_create_queries.py +213 -0
  727. contextsynapse/tests/test_api_vs_native.py +280 -0
  728. contextsynapse/tests/test_chunking_dedup.py +199 -0
  729. contextsynapse/tests/test_connectors.py +171 -0
  730. contextsynapse/tests/test_edges_and_match.py +202 -0
  731. contextsynapse/tests/test_extraction_pipeline_integration.py +581 -0
  732. contextsynapse/tests/test_name_property.py +224 -0
  733. contextsynapse/tests/test_node_edge_metadata.py +250 -0
  734. contextsynapse/tests/test_playground_conn.py +114 -0
  735. contextsynapse/tests/test_query_cache.py +213 -0
  736. contextsynapse/tests/test_source_policy_auth.py +348 -0
  737. contextsynapse/tests/test_temporal_and_domain.py +224 -0
  738. contextsynapse/tests/test_time_travel_e2e.py +571 -0
  739. contextsynapse/tests/test_traversal_and_aggregation.py +275 -0
  740. contextsynapse/tools/__init__.py +36 -0
  741. contextsynapse/tools/a2a_tools.py +106 -0
  742. contextsynapse/tools/cognition_tools.py +118 -0
  743. contextsynapse/tools/context.py +905 -0
  744. contextsynapse/tools/formatting.py +92 -0
  745. contextsynapse/tools/gateway_tools.py +186 -0
  746. contextsynapse/tools/graph.py +1700 -0
  747. contextsynapse/tools/intelligence.py +235 -0
  748. contextsynapse/tools/memory.py +118 -0
  749. contextsynapse/tools/registry.py +373 -0
  750. contextsynapse/tools/shield_tools.py +159 -0
  751. contextsynapse/tools/tasks.py +341 -0
  752. contextsynapse/tools/workspace_tools.py +124 -0
  753. contextsynapse/utils/__init__.py +15 -0
  754. contextsynapse/utils/config_loader.py +198 -0
  755. contextsynapse/utils/env_loader.py +156 -0
  756. contextsynapse/utils/file_utils.py +288 -0
  757. contextsynapse/utils/logging_optimizer.py +119 -0
  758. contextsynapse/vector/__init__.py +30 -0
  759. contextsynapse/vector/chroma_vector_store.py +152 -0
  760. contextsynapse/vector/custom_vector_store.py +537 -0
  761. contextsynapse/vector/faiss_vector_store.py +296 -0
  762. contextsynapse/vector/qdrant_vector_store.py +163 -0
  763. contextsynapse/vector/vector_db.py +953 -0
  764. contextsynapse/vector/vector_db_manager.py +197 -0
  765. contextsynapse/workspace/__init__.py +27 -0
  766. contextsynapse/workspace/base.py +94 -0
  767. contextsynapse/workspace/git.py +228 -0
  768. contextsynapse/workspace/github.py +78 -0
  769. contextsynapse/workspace/local.py +73 -0
  770. contextsynapse/workspace/tools.py +222 -0
  771. contextsynapse-1.0.0.dist-info/METADATA +847 -0
  772. contextsynapse-1.0.0.dist-info/RECORD +776 -0
  773. contextsynapse-1.0.0.dist-info/WHEEL +5 -0
  774. contextsynapse-1.0.0.dist-info/entry_points.txt +4 -0
  775. contextsynapse-1.0.0.dist-info/licenses/LICENSE +200 -0
  776. contextsynapse-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,4144 @@
1
+ """
2
+ AIContextDB FastAPI Server - Comprehensive Graph Database API
3
+ Supports all AIContextDB features including AIQL, enhanced search, and more.
4
+ """
5
+
6
+ from pathlib import Path as _Path
7
+
8
+ # Load .env file before anything reads os.environ
9
+ def _load_dotenv():
10
+ env_path = _Path(__file__).resolve().parents[2] / ".env"
11
+ if env_path.exists():
12
+ for line in env_path.read_text().splitlines():
13
+ line = line.strip()
14
+ if not line or line.startswith("#"):
15
+ continue
16
+ key, _, value = line.partition("=")
17
+ key, value = key.strip(), value.strip()
18
+ if key and key not in os.environ:
19
+ os.environ[key] = value
20
+
21
+ import os
22
+ _load_dotenv()
23
+
24
+ from fastapi import FastAPI, HTTPException, Depends, Query, Body, Request, Header
25
+ from fastapi.middleware.cors import CORSMiddleware
26
+ from fastapi.middleware.gzip import GZipMiddleware
27
+ from fastapi.responses import JSONResponse, HTMLResponse
28
+ from fastapi.staticfiles import StaticFiles
29
+ from pydantic import BaseModel, Field
30
+ from contextlib import asynccontextmanager
31
+ from typing import Dict, List, Any, Optional, Union, Tuple
32
+ import asyncio
33
+ import threading
34
+ import time
35
+ import json
36
+ import logging
37
+ from datetime import datetime
38
+ import networkx as nx
39
+
40
+ # Custom exception classes for better error handling
41
+ class DuplicateNodeError(Exception):
42
+ """Raised when trying to create a duplicate node."""
43
+ def __init__(self, message: str, node_type: str = None, duplicate_field: str = None):
44
+ self.message = message
45
+ self.node_type = node_type
46
+ self.duplicate_field = duplicate_field
47
+ super().__init__(self.message)
48
+
49
+ class DuplicateEdgeError(Exception):
50
+ """Raised when trying to create a duplicate edge."""
51
+ def __init__(self, message: str, edge_type: str = None, duplicate_field: str = None):
52
+ self.message = message
53
+ self.edge_type = edge_type
54
+ self.duplicate_field = duplicate_field
55
+ super().__init__(self.message)
56
+
57
+ # Core imports
58
+ from ..core.hybrid_graph_storage import AIContextDB
59
+ from ..core.graph_structures import GraphNode
60
+ from ..aiql.parser import AIQLParser
61
+ from ..aiql.engine import AIQLExecutor
62
+ from ..core.registry import GraphRegistry
63
+
64
+ # Alias for backward compatibility
65
+ # Legacy alias for backward compatibility
66
+ QGraphDB = AIContextDB
67
+
68
+ # Optional imports with fallbacks
69
+ try:
70
+ from ..llm.openai_embedding_service import OpenAIEmbeddingService
71
+ OPENAI_EMBEDDING_AVAILABLE = True
72
+ except ImportError:
73
+ OPENAI_EMBEDDING_AVAILABLE = False
74
+ OpenAIEmbeddingService = None
75
+
76
+ try:
77
+ from .storage.wal import WALManager, WALConfig
78
+ WAL_AVAILABLE = True
79
+ except ImportError:
80
+ WAL_AVAILABLE = False
81
+ WALManager = None
82
+ WALConfig = None
83
+
84
+ # Metadata tracking
85
+ try:
86
+ from ..metadata.metadata_tracker import get_metadata_tracker
87
+ METADATA_TRACKING_AVAILABLE = True
88
+ except ImportError:
89
+ METADATA_TRACKING_AVAILABLE = False
90
+ def get_metadata_tracker():
91
+ return None
92
+
93
+ # Set LLM_AVAILABLE based on OpenAI embedding service
94
+ LLM_AVAILABLE = OPENAI_EMBEDDING_AVAILABLE
95
+
96
+ # Set QGRAQL_AVAILABLE to False since we're using AIQL now
97
+ QGRAQL_AVAILABLE = False
98
+
99
+ # Set ENHANCED_SEARCH_AVAILABLE to False since we don't have enhanced search
100
+ ENHANCED_SEARCH_AVAILABLE = False
101
+
102
+ # Configure structured logging (JSON in prod, colored console in dev)
103
+ from ..logging_config import setup_logging
104
+ setup_logging()
105
+ logger = logging.getLogger(__name__)
106
+
107
+ # Lifespan context manager
108
+ @asynccontextmanager
109
+ async def lifespan(app: FastAPI):
110
+ """Manage application lifespan."""
111
+ # Startup
112
+ global current_graph
113
+ logger.info("[START] AIContextDB API starting up...")
114
+
115
+ # Security checks
116
+ if not os.environ.get("CONTEXTSYNAPSE_JWT_SECRET") or os.environ.get("AICONTEXTDB_JWT_SECRET") and not os.environ.get("CONTEXTSYNAPSE_ADMIN_KEY") or os.environ.get("AICONTEXTDB_ADMIN_KEY"):
117
+ logger.warning("⚠️ AICONTEXTDB_JWT_SECRET is not set — JWTs are signed with an insecure default!")
118
+ if _cors_origins == ["http://localhost:3000"]:
119
+ logger.info("CORS origins defaulting to http://localhost:3000. Set AICONTEXTDB_CORS_ORIGINS for production.")
120
+
121
+ # Load existing graphs from disk
122
+ logger.info("[FILE] Loading existing graphs from disk...")
123
+ try:
124
+ # Try to load the default graph
125
+ default_graph = graph_registry.get_graph("default", load_if_missing=True)
126
+ if default_graph:
127
+ current_graph = default_graph
128
+ logger.info(f"[EMOJI] Loaded default graph with {len(default_graph.node_index)} nodes")
129
+ else:
130
+ # Create default graph if none exists
131
+ current_graph = graph_registry.create_graph("default")
132
+ logger.info("[EMOJI] Created new default graph")
133
+ except Exception as e:
134
+ logger.error(f"[EMOJI] Error loading graphs: {e}")
135
+ # Fallback: create new default graph
136
+ current_graph = graph_registry.create_graph("default")
137
+ logger.info("[EMOJI] Created fallback default graph")
138
+
139
+ # Enable multi-worker Redis bridges (when running with --workers N)
140
+ try:
141
+ from ..multiworker import enable_multiworker
142
+ enable_multiworker()
143
+ except Exception as e:
144
+ logger.debug("Multi-worker init: %s", e)
145
+
146
+ # Start job queue workers (optional module)
147
+ try:
148
+ from ..jobs.queue import job_queue
149
+ job_queue.start()
150
+ logger.info("Job queue started")
151
+ except ImportError:
152
+ pass # jobs module removed — not needed for core functionality
153
+ except Exception as e:
154
+ logger.warning(f"Job queue error: {e}")
155
+
156
+ # Start intelligence engine
157
+ try:
158
+ from ..intelligence import start_intelligence
159
+ start_intelligence(graph_registry=graph_registry)
160
+ logger.info("[INTELLIGENCE] Context Intelligence Engine started")
161
+ except Exception as e:
162
+ logger.warning("[INTELLIGENCE] Failed to start: %s", e)
163
+
164
+ # Warm up embedding model + pre-open active vector collections
165
+ try:
166
+ from ..context.vector_integration import get_session_vector_store
167
+ svs = get_session_vector_store()
168
+ if svs.available:
169
+ logger.info("[EMBED] Embedding model warmed up (dim=%d)", svs._dimension)
170
+ # Pre-warm vector stores for graphs that have Qdrant collections
171
+ try:
172
+ import redis as _redis
173
+ r = _redis.Redis.from_url(
174
+ os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL", "redis://localhost:6379/0"),
175
+ decode_responses=True,
176
+ )
177
+ # Find active graph namespaces from provenance keys
178
+ prov_keys = r.keys("contextcore:provenance:ctx_*")
179
+ active_graphs = []
180
+ for pk in prov_keys[:5]: # warm top 5
181
+ ns = pk.split(":")[-1]
182
+ active_graphs.append(ns)
183
+ try:
184
+ svs._get_store(ns)
185
+ logger.info("[EMBED] Pre-warmed vector store: %s", ns)
186
+ except Exception:
187
+ pass
188
+ except Exception:
189
+ active_graphs = []
190
+ except Exception as e:
191
+ logger.debug("[EMBED] Warmup skipped: %s", e)
192
+ active_graphs = []
193
+
194
+ # Pre-build keyword + BM25 indexes for active graphs (so first search is fast)
195
+ try:
196
+ import threading
197
+ def _prebuild_indexes():
198
+ from ..search.rag import _build_keyword_index, _get_bm25_engine
199
+ for ns in active_graphs[:3]:
200
+ try:
201
+ db = graph_registry.get_graph_for_request(ns)
202
+ if db:
203
+ _build_keyword_index(db, ns)
204
+ _get_bm25_engine(db, ns)
205
+ logger.info("[SEARCH] Pre-built keyword + BM25 indexes: %s", ns)
206
+ except Exception:
207
+ pass
208
+ # Run in background so server starts immediately
209
+ t = threading.Thread(target=_prebuild_indexes, daemon=True)
210
+ t.start()
211
+ logger.info("[SEARCH] Index pre-build started in background for %d graphs", len(active_graphs[:3]))
212
+ except Exception as e:
213
+ logger.debug("[SEARCH] Index pre-build skipped: %s", e)
214
+
215
+ # Start write-behind flusher (async disk persistence)
216
+ try:
217
+ from ..core.write_behind import get_write_behind
218
+ wb = get_write_behind(graph_registry)
219
+ if wb:
220
+ logger.info("[WB] Write-behind persistence started")
221
+ except Exception as e:
222
+ logger.debug("[WB] Write-behind not available: %s", e)
223
+
224
+ # Start cross-worker graph sync (Redis pub/sub)
225
+ try:
226
+ from ..core.graph_sync import get_graph_sync
227
+ sync = get_graph_sync(graph_registry)
228
+ if sync:
229
+ logger.info("[SYNC] Cross-worker graph sync started")
230
+ except Exception as e:
231
+ logger.debug("[SYNC] Graph sync not available: %s", e)
232
+
233
+ # Start pruning scheduler
234
+ try:
235
+ from ..core.pruning import PruningScheduler
236
+ _pruning_scheduler = PruningScheduler(graph_registry)
237
+ _pruning_scheduler.start()
238
+ except Exception as e:
239
+ logger.warning("Pruning scheduler not started: %s", e)
240
+
241
+ # Start pipeline ingestion scheduler
242
+ try:
243
+ from ..pipelines.scheduler import PipelineScheduler
244
+ from ..pipelines.models import PipelineStore
245
+ import os as _os_pipe
246
+ _pipe_redis = _os_pipe.environ.get("AICONTEXTDB_REDIS_URL")
247
+ _pipeline_store = PipelineStore(redis_url=_pipe_redis)
248
+ _pipeline_scheduler = PipelineScheduler(store=_pipeline_store)
249
+ _pipeline_scheduler.start()
250
+ logger.info("Pipeline ingestion scheduler started")
251
+ except Exception as e:
252
+ logger.warning("Pipeline ingestion scheduler not started: %s", e)
253
+
254
+ # NOTE: ContextPipelineScheduler is started at module level (below) using the
255
+ # same context_manager instance shared with the dashboard router.
256
+
257
+ # Start stock market realtime engine (auto-polls during market hours)
258
+ try:
259
+ from plugins.stock_analysis.realtime import RealtimeEngine
260
+ _realtime_engine = RealtimeEngine(graph_registry=graph_registry)
261
+ _realtime_engine.start(interval_seconds=300) # 5-minute intervals
262
+ logger.info("[REALTIME] Market hours price engine started (5m interval)")
263
+ except ImportError:
264
+ logger.debug("[REALTIME] Stock plugin not installed — skipped")
265
+ except Exception as e:
266
+ logger.warning("[REALTIME] Failed to start: %s", e)
267
+
268
+ # Pre-warm + continuously refresh sensor fusion cache for all tracked stocks.
269
+ # Runs every REFRESH_INTERVAL seconds so the cache is always hot; TTL is set
270
+ # to 2× the interval so a slightly-late refresh never leaves users with a cold hit.
271
+ try:
272
+ import threading as _fuse_thread
273
+ import json as _fuse_json
274
+ import os as _fuse_os
275
+
276
+ _FUSION_REFRESH_INTERVAL = int(_fuse_os.environ.get("FUSION_REFRESH_INTERVAL", "300")) # 5 min
277
+ _FUSION_CACHE_TTL = _FUSION_REFRESH_INTERVAL * 2 # 10 min — buffer so cache survives a slow cycle
278
+
279
+ def _fusion_refresh_loop():
280
+ import time as _time
281
+ import sys as _sys
282
+ from pathlib import Path as _fpath
283
+ # Ensure project root is on sys.path so plugins package is importable
284
+ _proj_root = str(_fpath(__file__).parent.parent.parent)
285
+ if _proj_root not in _sys.path:
286
+ _sys.path.insert(0, _proj_root)
287
+
288
+ # Use orjson for numpy/float32 safe serialization; fallback to stdlib
289
+ try:
290
+ import orjson as _orjson
291
+ def _dumps(obj):
292
+ return _orjson.dumps(obj, option=_orjson.OPT_NON_STR_KEYS | _orjson.OPT_SERIALIZE_NUMPY).decode()
293
+ except ImportError:
294
+ import json as _json_fb
295
+ def _dumps(obj):
296
+ return _json_fb.dumps(obj, default=lambda x: float(x) if hasattr(x, '__float__') else str(x))
297
+
298
+ _time.sleep(5) # let server finish startup first
299
+ try:
300
+ import redis as _redis
301
+ _r = _redis.Redis.from_url(
302
+ _fuse_os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL", "redis://localhost:6379/0"),
303
+ socket_connect_timeout=1,
304
+ )
305
+ _r.ping() # verify connection
306
+ except Exception as _re:
307
+ logger.warning("[FUSION] Redis unavailable, cache loop not started: %s", _re)
308
+ return
309
+
310
+ try:
311
+ from plugins.stock_analysis.sensor_fusion import SensorFusionEngine
312
+ from plugins.stock_analysis.config import TICKERS
313
+ except Exception as _ie:
314
+ logger.warning("[FUSION] Plugin import failed, cache loop not started: %s", _ie)
315
+ return
316
+
317
+ logger.info("[FUSION] Cache refresh loop running (interval=%ds, %d stocks, sequential)",
318
+ _FUSION_REFRESH_INTERVAL, len(TICKERS))
319
+
320
+ engine = SensorFusionEngine(graph_registry)
321
+
322
+ while True:
323
+ cycle_start = _time.monotonic()
324
+ warmed = 0
325
+ for company_name, info in TICKERS.items():
326
+ try:
327
+ result = engine.fuse(company_name, days=7)
328
+ payload = _dumps(result.to_dict())
329
+ _r.setex(f"fusion:{company_name.lower()}:7", _FUSION_CACHE_TTL, payload)
330
+ ticker = (info.get("ticker") or "").replace(".NS", "").replace(".BO", "").lower()
331
+ if ticker and ticker != company_name.lower():
332
+ _r.setex(f"fusion:{ticker}:7", _FUSION_CACHE_TTL, payload)
333
+ warmed += 1
334
+ except Exception as _e:
335
+ logger.warning("[FUSION] Refresh skipped %s: %s", company_name, _e)
336
+ _time.sleep(0.1) # yield between stocks so API requests aren't starved
337
+
338
+ elapsed = _time.monotonic() - cycle_start
339
+ logger.info("[FUSION] Cache refresh cycle: %d/%d stocks in %.1fs",
340
+ warmed, len(TICKERS), elapsed)
341
+ sleep_for = max(30, _FUSION_REFRESH_INTERVAL - elapsed)
342
+ _time.sleep(sleep_for)
343
+
344
+ _fuse_thread.Thread(target=_fusion_refresh_loop, daemon=True, name="fusion-cache-refresher").start()
345
+ logger.info("[FUSION] Cache refresh loop started (interval=%ds, TTL=%ds)",
346
+ _FUSION_REFRESH_INTERVAL, _FUSION_CACHE_TTL)
347
+ except Exception as e:
348
+ logger.warning("[FUSION] Cache refresh loop init failed: %s", e)
349
+
350
+ # Start silent prediction engine — ticks every 30 min during market hours
351
+ try:
352
+ import threading as _threading
353
+ from plugins.stock_analysis.silent_prediction import SilentPredictionEngine
354
+ _pred_engine = SilentPredictionEngine(graph_registry=graph_registry)
355
+
356
+ def _prediction_tick_loop():
357
+ import time as _time
358
+ while True:
359
+ try:
360
+ result = _pred_engine.tick()
361
+ if result.get("predicted") or result.get("verified"):
362
+ logger.info("[PREDICT] tick: %d predicted, %d verified, %d anomalies",
363
+ result.get("predicted", 0), result.get("verified", 0), result.get("anomalies", 0))
364
+ except Exception as _e:
365
+ logger.warning("[PREDICT] tick error: %s", _e)
366
+ _time.sleep(1800) # 30 minutes
367
+
368
+ _pred_thread = _threading.Thread(target=_prediction_tick_loop, daemon=True, name="prediction-tick")
369
+ _pred_thread.start()
370
+ logger.info("[PREDICT] Silent prediction engine started (30m tick)")
371
+ except ImportError:
372
+ logger.debug("[PREDICT] Stock plugin not installed — skipped")
373
+ except Exception as e:
374
+ logger.warning("[PREDICT] Failed to start: %s", e)
375
+
376
+ logger.info("[EMOJI] AIContextDB API started successfully")
377
+
378
+ # Warmup: pre-initialize lazy components so first dashboard request is fast
379
+ try:
380
+ import threading
381
+ def _warmup():
382
+ try:
383
+ from .integrations import IntegrationRegistry
384
+ IntegrationRegistry()
385
+ except Exception:
386
+ pass
387
+ try:
388
+ from .metering import UsageMeter
389
+ UsageMeter()
390
+ except Exception:
391
+ pass
392
+ threading.Thread(target=_warmup, daemon=True).start()
393
+ except Exception:
394
+ pass
395
+
396
+ # ── Plugin system: discover and start vertical plugins ──
397
+ try:
398
+ from ..plugins.registry import get_plugin_registry
399
+ plugin_registry = get_plugin_registry()
400
+ n_plugins = plugin_registry.discover_and_register()
401
+ if n_plugins > 0:
402
+ await plugin_registry.startup_all(graph_registry)
403
+ # Mount plugin API routers
404
+ for plugin_name, route in plugin_registry.all_api_routers():
405
+ prefix = route.prefix or f"/{plugin_name}"
406
+ if not prefix.startswith("/"):
407
+ prefix = f"/{prefix}"
408
+ app.include_router(
409
+ route.router,
410
+ prefix=f"/v1{prefix}",
411
+ tags=route.tags or [plugin_name],
412
+ )
413
+ logger.info(f"Loaded {n_plugins} plugin(s): {', '.join(plugin_registry.plugins.keys())}")
414
+ else:
415
+ logger.info("No vertical plugins installed")
416
+ except Exception as e:
417
+ logger.warning(f"Plugin system init: {e}")
418
+
419
+ yield
420
+
421
+ # Shutdown
422
+ logger.info("[EMOJI] AIContextDB API shutting down...")
423
+
424
+ # Shutdown plugins first
425
+ try:
426
+ from ..plugins.registry import get_plugin_registry
427
+ await get_plugin_registry().shutdown_all()
428
+ except Exception:
429
+ pass
430
+
431
+ # Save current graph
432
+ if current_graph:
433
+ logger.info(f"[EMOJI] Saving current graph '{current_graph.name}' to disk...")
434
+ try:
435
+ success = graph_registry.save_graph(current_graph.name)
436
+ if success:
437
+ logger.info(f"[EMOJI] Successfully saved graph '{current_graph.name}'")
438
+ else:
439
+ logger.error(f"[EMOJI] Failed to save graph '{current_graph.name}'")
440
+ except Exception as e:
441
+ logger.error(f"[EMOJI] Error saving graph: {e}")
442
+
443
+ # Stop job queue (optional)
444
+ try:
445
+ from ..jobs.queue import job_queue
446
+ await job_queue.stop()
447
+ except ImportError:
448
+ pass # optional
449
+ except Exception:
450
+ pass # optional
451
+
452
+ # Cleanup WAL and buffer threads for all active graphs
453
+ try:
454
+ for name, graph in list(graph_registry.graphs.items()):
455
+ # Stop WAL sync thread
456
+ if hasattr(graph, 'wal') and graph.wal:
457
+ try:
458
+ graph.wal.running = False
459
+ if graph.wal.wal_file:
460
+ graph.wal.wal_file.flush()
461
+ graph.wal.wal_file.close()
462
+ except Exception:
463
+ pass # optional
464
+ # Stop buffer auto-flush
465
+ if hasattr(graph, 'buffer_manager') and graph.buffer_manager:
466
+ try:
467
+ if hasattr(graph.buffer_manager, '_flush_task') and graph.buffer_manager._flush_task:
468
+ graph.buffer_manager._flush_task.cancel()
469
+ except Exception:
470
+ pass # optional
471
+ except Exception:
472
+ pass # optional
473
+
474
+ # Flush write-behind buffer before saving
475
+ try:
476
+ from ..core.write_behind import shutdown_write_behind
477
+ shutdown_write_behind()
478
+ except Exception:
479
+ pass # optional
480
+
481
+ # Save all graphs to disk before shutdown
482
+ try:
483
+ saved = 0
484
+ for name in list(graph_registry.graphs.keys()):
485
+ try:
486
+ graph_registry.save_graph(name, create_checkpoint=False)
487
+ saved += 1
488
+ except Exception:
489
+ pass # optional
490
+ logger.info("Saved %d graphs to disk", saved)
491
+ except Exception:
492
+ pass # optional
493
+
494
+ # Close database connection pools
495
+ try:
496
+ from ..core.db import close_all
497
+ close_all()
498
+ except Exception:
499
+ pass
500
+
501
+ logger.info("AIContextDB API shutdown complete")
502
+
503
+ # Initialize FastAPI app
504
+ app = FastAPI(
505
+ title="ContextCore API",
506
+ description="Graph RAG + Agentic AI Native GraphDB Package - Comprehensive API",
507
+ version="1.0.0",
508
+ docs_url="/docs",
509
+ redoc_url="/redoc",
510
+ lifespan=lifespan
511
+ )
512
+
513
+ # Add middleware
514
+ _cors_origins = [o.strip() for o in os.environ.get("CONTEXTSYNAPSE_CORS_ORIGINS") or os.environ.get("AICONTEXTDB_CORS_ORIGINS", "http://localhost:3000").split(",") if o.strip()]
515
+ app.add_middleware(
516
+ CORSMiddleware,
517
+ allow_origins=_cors_origins,
518
+ allow_credentials=True,
519
+ allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
520
+ allow_headers=["Authorization", "Content-Type", "X-Request-ID", "X-Admin-Key"],
521
+ )
522
+
523
+ app.add_middleware(GZipMiddleware, minimum_size=1000)
524
+
525
+ # Standardized error responses + request-id middleware
526
+ from .errors import install_error_handlers
527
+ install_error_handlers(app)
528
+
529
+ # Rate limiting
530
+ from .rate_limit import install_rate_limiter
531
+ install_rate_limiter(app)
532
+
533
+ # Prometheus metrics middleware + /metrics endpoint
534
+ try:
535
+ from .metrics import mount_metrics
536
+ mount_metrics(app)
537
+ except Exception as _metrics_err:
538
+ logging.getLogger(__name__).warning(f"Metrics not loaded: {_metrics_err}")
539
+
540
+ # Global graph registry — Redis if available, file-based fallback
541
+ try:
542
+ from ..core.registry_factory import create_graph_registry
543
+ graph_registry = create_graph_registry()
544
+ except Exception:
545
+ graph_registry = GraphRegistry()
546
+ current_graph = None
547
+
548
+ # Event bus for real-time notifications
549
+ from .events import event_bus
550
+
551
+ # ── Event handlers — react to graph/context changes across the system ──
552
+ def _on_graph_deleted(data):
553
+ """When a graph is deleted: clean metadata + cascade to context."""
554
+ name = data.get("name", "")
555
+ if not name:
556
+ return
557
+ # Clean registry metadata
558
+ if name in graph_registry.metadata:
559
+ del graph_registry.metadata[name]
560
+ graph_registry._save_metadata()
561
+ if name in graph_registry.graphs:
562
+ del graph_registry.graphs[name]
563
+ # Cascade: delete any context using this graph namespace
564
+ try:
565
+ from .dashboard_router import context_manager
566
+ if context_manager:
567
+ row = context_manager._conn.execute(
568
+ "SELECT context_id FROM contexts WHERE graph_namespace = ? AND status != 'deleted'",
569
+ (name,),
570
+ ).fetchone()
571
+ if row:
572
+ context_manager._conn.execute(
573
+ "UPDATE contexts SET status = 'deleted' WHERE graph_namespace = ?", (name,),
574
+ )
575
+ context_manager._conn.commit()
576
+ except Exception:
577
+ pass # optional
578
+
579
+ def _on_context_deleted(data):
580
+ """When a context is deleted: clean its graph from registry."""
581
+ context_id = data.get("context_id", "")
582
+ if not context_id:
583
+ return
584
+ # Find the graph namespace for this context
585
+ try:
586
+ from .dashboard_router import context_manager
587
+ if context_manager:
588
+ ctx = context_manager._conn.execute(
589
+ "SELECT graph_namespace FROM contexts WHERE context_id = ?", (context_id,),
590
+ ).fetchone()
591
+ if ctx and ctx["graph_namespace"]:
592
+ ns = ctx["graph_namespace"]
593
+ if ns in graph_registry.metadata:
594
+ del graph_registry.metadata[ns]
595
+ graph_registry._save_metadata()
596
+ if ns in graph_registry.graphs:
597
+ del graph_registry.graphs[ns]
598
+ except Exception:
599
+ pass # optional
600
+
601
+ event_bus.on("graph_deleted", _on_graph_deleted)
602
+ event_bus.on("context_deleted", _on_context_deleted)
603
+
604
+ # Wire webhook dispatching — fire outbound HTTP POSTs on key events
605
+ try:
606
+ from ..context.webhooks import WebhookRegistry
607
+ _webhook_registry = WebhookRegistry()
608
+
609
+ _WEBHOOK_EVENTS = {
610
+ "context_attached", "context_created", "context_deleted",
611
+ "pipeline_completed", "task_completed", "agent_joined",
612
+ "graph_created", "graph_deleted",
613
+ "nodes_archived", "archive_restored",
614
+ "session_created", "session_deleted",
615
+ "agent_left", "task_claimed", "task_failed",
616
+ }
617
+
618
+ def _dispatch_webhook(event_data):
619
+ """Fire webhooks for matching event types (background thread)."""
620
+ import threading
621
+ event_type = event_data.get("type") or event_data.get("event_type", "")
622
+ if event_type not in _WEBHOOK_EVENTS:
623
+ return
624
+ event_data["event_type"] = event_type
625
+ # Dispatch to all tenants (in production, scope by tenant_id from event)
626
+ def _do_dispatch():
627
+ try:
628
+ for tenant in tenant_registry.list_tenants():
629
+ _webhook_registry.dispatch(tenant.tenant_id, event_data)
630
+ except Exception:
631
+ pass # optional
632
+ threading.Thread(target=_do_dispatch, daemon=True).start()
633
+
634
+ event_bus.on("*", _dispatch_webhook)
635
+ logging.getLogger(__name__).info("Webhook dispatcher wired to event_bus")
636
+ except Exception as _wh_err:
637
+ logging.getLogger(__name__).debug("Webhook dispatcher not loaded: %s", _wh_err)
638
+
639
+ # WebSocket endpoint for live events
640
+ from fastapi import WebSocket, WebSocketDisconnect
641
+
642
+ @app.websocket("/ws/events")
643
+ async def ws_events(websocket: WebSocket, token: str = None):
644
+ """Stream real-time events to authenticated clients.
645
+
646
+ Authenticate via query param: ``ws://host/ws/events?token=<jwt>``
647
+ """
648
+ from .auth import verify_jwt
649
+ await websocket.accept()
650
+ if not token or verify_jwt(token) is None:
651
+ await websocket.close(code=4001, reason="Authentication required")
652
+ return
653
+ queue = event_bus.subscribe()
654
+ try:
655
+ # Send recent history on connect
656
+ for evt in event_bus.recent(10):
657
+ await websocket.send_json(evt)
658
+ # Stream new events
659
+ while True:
660
+ event = await queue.get()
661
+ await websocket.send_json(event)
662
+ except WebSocketDisconnect:
663
+ pass # optional
664
+ except Exception:
665
+ pass # optional
666
+ finally:
667
+ event_bus.unsubscribe(queue)
668
+
669
+ # ── Tenant registry & auth ───────────────────────────────────────────
670
+ from .tenants import TenantRegistry
671
+ from .auth import TenantAuth, AdminAuth
672
+
673
+ tenant_registry = TenantRegistry()
674
+ tenant_auth = TenantAuth(tenant_registry)
675
+
676
+ # REST endpoint for recent events (fallback for non-WS clients)
677
+ async def _require_jwt(authorization: str = Header(None)):
678
+ """Lightweight auth: any valid JWT."""
679
+ from .auth import verify_jwt
680
+ if not authorization:
681
+ raise HTTPException(401, "Authentication required.")
682
+ token = authorization.removeprefix("Bearer ").strip()
683
+ if not verify_jwt(token):
684
+ raise HTTPException(403, "Invalid or expired credentials.")
685
+
686
+ @app.get("/events/recent")
687
+ async def get_recent_events(_=Depends(_require_jwt)):
688
+ return {"events": event_bus.recent(20)}
689
+
690
+ # Mount plugin management router
691
+ try:
692
+ from ..plugins.api import create_plugin_router
693
+ app.include_router(create_plugin_router())
694
+ except Exception as _plugin_err:
695
+ logging.getLogger(__name__).warning(f"Plugin router not loaded: {_plugin_err}")
696
+
697
+ # Mount vertical builder router
698
+ try:
699
+ from .vertical_builder_router import create_vertical_builder_router
700
+ app.include_router(create_vertical_builder_router())
701
+ except Exception as _vb_err:
702
+ logging.getLogger(__name__).warning(f"Vertical builder router not loaded: {_vb_err}")
703
+
704
+ # Mount admin router (tenant management, protected by AICONTEXTDB_ADMIN_KEY)
705
+ try:
706
+ from .admin_router import create_admin_router
707
+ app.include_router(create_admin_router(tenant_registry))
708
+ except Exception as _admin_err:
709
+ logging.getLogger(__name__).warning(f"Admin router not loaded: {_admin_err}")
710
+
711
+ # Mount user auth router (signup, login, profile)
712
+ try:
713
+ from .users import UserRegistry
714
+ from .auth_router import create_auth_router
715
+
716
+ user_registry = UserRegistry()
717
+ # Seed default admin on first run
718
+ _admin = user_registry.ensure_admin()
719
+ if _admin:
720
+ try:
721
+ _at, _ak = tenant_registry.create("Admin Workspace")
722
+ user_registry.link_tenant(_admin.user_id, _at.tenant_id, role="owner")
723
+ logger.info("Admin workspace created (tenant: %s)", _at.tenant_id)
724
+ except Exception:
725
+ pass
726
+ app.include_router(create_auth_router(user_registry, tenant_registry))
727
+ except Exception as _auth_err:
728
+ logging.getLogger(__name__).warning(f"Auth router not loaded: {_auth_err}")
729
+ user_registry = None
730
+
731
+ # ── Usage metering ──────────────────────────────────────────────────
732
+ try:
733
+ from .metering import UsageMeter
734
+ usage_meter = UsageMeter()
735
+ except Exception as _meter_err:
736
+ logging.getLogger(__name__).warning(f"Usage meter not loaded: {_meter_err}")
737
+ usage_meter = None
738
+
739
+ # Mount user dashboard router
740
+ try:
741
+ from .dashboard_router import create_dashboard_router
742
+
743
+ # Try to get agent registry and session manager for context features
744
+ _agent_reg = None
745
+ _session_mgr = None
746
+ try:
747
+ from ..context.store_factory import create_agent_registry
748
+ _agent_reg = create_agent_registry()
749
+ except Exception:
750
+ pass # optional
751
+ try:
752
+ from ..context.session import ContextSessionManager
753
+ _session_mgr = ContextSessionManager(graph_registry=graph_registry)
754
+ except Exception:
755
+ pass # optional
756
+
757
+ _context_mgr = None
758
+ try:
759
+ from ..context.context_manager import ContextManager
760
+ _context_mgr = ContextManager(graph_registry=graph_registry)
761
+ # One-time migration: disabled — sessions and contexts are now separate concepts.
762
+ # Sessions (boundaries) = execution scopes. Contexts = knowledge stores.
763
+ # They link via ATTACHED_TO edges, not by duplicating data.
764
+ except Exception:
765
+ pass # optional
766
+
767
+ # Audit log
768
+ _audit_log = None
769
+ try:
770
+ from .audit import AuditLog
771
+ _audit_log = AuditLog()
772
+ except Exception:
773
+ pass # optional
774
+
775
+ if True: # always mount dashboard — auth handled per-endpoint
776
+ if not user_registry:
777
+ from .auth import UserRegistry
778
+ user_registry = UserRegistry()
779
+ if not usage_meter:
780
+ usage_meter = UsageMeter()
781
+ app.include_router(create_dashboard_router(
782
+ user_registry=user_registry,
783
+ tenant_registry=tenant_registry,
784
+ graph_registry=graph_registry,
785
+ usage_meter=usage_meter,
786
+ agent_registry=_agent_reg,
787
+ session_manager=_session_mgr,
788
+ context_manager=_context_mgr,
789
+ audit_log=_audit_log,
790
+ ))
791
+ except Exception as _dash_err:
792
+ logging.getLogger(__name__).warning(f"Dashboard router not loaded: {_dash_err}")
793
+
794
+ # Mount experiment router (multi-agent simulation)
795
+ try:
796
+ from .experiment_router import create_experiment_router
797
+ from .auth import UserAuth
798
+ _exp_user_auth = UserAuth(user_registry)
799
+ _exp_require_member = _exp_user_auth # same auth for now
800
+ app.include_router(create_experiment_router(
801
+ graph_registry=graph_registry,
802
+ agent_registry=_agent_reg,
803
+ user_auth=_exp_user_auth,
804
+ require_member=_exp_require_member,
805
+ session_manager=_session_mgr,
806
+ ), prefix="/dashboard")
807
+ logger.info("Experiment router mounted")
808
+ except Exception as _exp_err:
809
+ logging.getLogger(__name__).warning(f"Experiment router not loaded: {_exp_err}")
810
+
811
+ # Start promotion sweeper (auto-promotes agent findings from runtime to atomic)
812
+ try:
813
+ from ..context.promotion import PromotionSweeper
814
+ _promotion_sweeper = PromotionSweeper(graph_registry, _session_mgr, interval_s=300)
815
+ _promotion_sweeper.start()
816
+ except Exception as _ps_err:
817
+ logging.getLogger(__name__).warning("Promotion sweeper not started: %s", _ps_err)
818
+
819
+ # Mount projects router (software development workflow)
820
+ try:
821
+ from .projects_router import create_projects_router
822
+ app.include_router(create_projects_router())
823
+ except Exception as _proj_err:
824
+ logging.getLogger(__name__).warning(f"Projects router not loaded: {_proj_err}")
825
+
826
+ # ── Billing & quota ─────────────────────────────────────────────────
827
+ billing_manager = None
828
+ quota_enforcer = None
829
+ feature_gate = None
830
+ try:
831
+ from .billing import BillingManager
832
+ from .quota import QuotaEnforcer
833
+ from .feature_gate import FeatureGate
834
+ from .billing_router import create_billing_router
835
+
836
+ billing_manager = BillingManager()
837
+ feature_gate = FeatureGate(billing_manager)
838
+ if usage_meter:
839
+ quota_enforcer = QuotaEnforcer(billing_manager, usage_meter)
840
+
841
+ if user_registry:
842
+ app.include_router(create_billing_router(
843
+ user_registry=user_registry,
844
+ tenant_registry=tenant_registry,
845
+ billing_manager=billing_manager,
846
+ usage_meter=usage_meter,
847
+ ))
848
+ logging.getLogger(__name__).info("Billing + quota + feature gates initialized")
849
+ except Exception as _bill_err:
850
+ logging.getLogger(__name__).warning(f"Billing router not loaded: {_bill_err}")
851
+
852
+ # ── Integrations hub ──────────────────────────────────────────────────
853
+ try:
854
+ from .integrations import IntegrationRegistry
855
+ from .integrations_router import create_integrations_router
856
+
857
+ integration_registry = IntegrationRegistry()
858
+ if user_registry:
859
+ app.include_router(create_integrations_router(
860
+ user_registry=user_registry,
861
+ tenant_registry=tenant_registry,
862
+ integration_registry=integration_registry,
863
+ ))
864
+ except Exception as _int_err:
865
+ logging.getLogger(__name__).warning(f"Integrations router not loaded: {_int_err}")
866
+
867
+ # ── Query workspace ──────────────────────────────────────────────────
868
+ try:
869
+ from .queries_router import create_queries_router
870
+
871
+ if user_registry:
872
+ app.include_router(create_queries_router(
873
+ user_registry=user_registry,
874
+ tenant_registry=tenant_registry,
875
+ graph_registry=graph_registry,
876
+ usage_meter=usage_meter,
877
+ ))
878
+ except Exception as _q_err:
879
+ logging.getLogger(__name__).warning(f"Queries router not loaded: {_q_err}")
880
+
881
+ # ── Pipelines ───────────────────────────────────────────────────────
882
+ try:
883
+ from .pipeline_router import create_pipeline_router
884
+
885
+ if user_registry:
886
+ app.include_router(create_pipeline_router(
887
+ user_registry=user_registry,
888
+ tenant_registry=tenant_registry,
889
+ graph_registry=graph_registry,
890
+ usage_meter=usage_meter,
891
+ ))
892
+ except Exception as _pipe_err:
893
+ logging.getLogger(__name__).warning(f"Pipeline router not loaded: {_pipe_err}")
894
+
895
+ # ── Search & RAG ─────────────────────────────────────────────────────
896
+ try:
897
+ from .search_router import create_search_router
898
+
899
+ if user_registry:
900
+ app.include_router(create_search_router(
901
+ user_registry=user_registry,
902
+ tenant_registry=tenant_registry,
903
+ graph_registry=graph_registry,
904
+ ))
905
+ except Exception as _s_err:
906
+ logging.getLogger(__name__).warning(f"Search router not loaded: {_s_err}")
907
+
908
+ # ── Pipeline Scheduler ────────────────────────────────────────────────
909
+ pipeline_scheduler = None
910
+ try:
911
+ from ..scheduler import PipelineScheduler
912
+ _redis_url = os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL", "redis://localhost:6379/0")
913
+ pipeline_scheduler = PipelineScheduler(redis_url=_redis_url)
914
+ pipeline_scheduler.start()
915
+ logging.getLogger(__name__).info("Pipeline scheduler started")
916
+ except Exception as _sched_err:
917
+ logging.getLogger(__name__).debug("Pipeline scheduler not started: %s", _sched_err)
918
+
919
+ # ── Context Pipeline Scheduler ────────────────────────────────────────
920
+ _ctx_pipeline_scheduler = None
921
+ try:
922
+ from ..pipelines.scheduler import ContextPipelineScheduler
923
+ if _context_mgr is not None:
924
+ _ctx_pipeline_scheduler = ContextPipelineScheduler(
925
+ context_manager=_context_mgr,
926
+ graph_registry=graph_registry,
927
+ )
928
+ _ctx_pipeline_scheduler.start()
929
+ logging.getLogger(__name__).info("Context pipeline scheduler started")
930
+ else:
931
+ logging.getLogger(__name__).warning("Context pipeline scheduler not started: context_manager unavailable")
932
+ except Exception as _ctx_sched_err:
933
+ logging.getLogger(__name__).warning("Context pipeline scheduler not started: %s", _ctx_sched_err)
934
+
935
+ # ── Breaking News Watchdog (auto-start if sources configured) ────────
936
+ try:
937
+ from ..intelligence.watchdog import BreakingNewsWatchdog
938
+ from ..intelligence.persistence import IntelligencePersistence
939
+
940
+ _watchdog = BreakingNewsWatchdog(watchdog_context="Global Macro")
941
+
942
+ # Load persisted sources
943
+ if _context_mgr is not None:
944
+ _wd_store = IntelligencePersistence(_context_mgr)
945
+ _wd_store.load_watchdog_config(_watchdog)
946
+
947
+ if _watchdog._sources:
948
+ _watchdog.start(interval_seconds=60)
949
+ logging.getLogger(__name__).info(
950
+ "Watchdog started: %d sources, polling every 60s",
951
+ len(_watchdog._sources),
952
+ )
953
+ else:
954
+ logging.getLogger(__name__).info("Watchdog not started: no sources configured. Add via /intelligence/watchdog/source")
955
+ except Exception as _wd_err:
956
+ logging.getLogger(__name__).warning("Watchdog not started: %s", _wd_err)
957
+
958
+ # ── Monitoring ────────────────────────────────────────────────────────
959
+ try:
960
+ from .monitoring_router import create_monitoring_router
961
+
962
+ if user_registry:
963
+ app.include_router(create_monitoring_router(
964
+ user_registry=user_registry,
965
+ tenant_registry=tenant_registry,
966
+ graph_registry=graph_registry,
967
+ agent_registry=_agent_reg,
968
+ usage_meter=usage_meter,
969
+ ))
970
+ except Exception as _m_err:
971
+ logging.getLogger(__name__).warning(f"Monitoring router not loaded: {_m_err}")
972
+
973
+ # ── Job queue endpoints ──────────────────────────────────────────────
974
+ # NOTE: Job endpoints are served by the dashboard_router (/dashboard/jobs,
975
+ # /dashboard/ingest/jobs) which reads from _ingest_jobs — the actual job
976
+ # store. The previous app-level routes here imported a non-existent
977
+ # jobs.queue module, silently returning {"jobs": []} and shadowing the
978
+ # working dashboard_router endpoints. Removed to fix the "running jobs
979
+ # not showing" bug.
980
+
981
+ # ── Graph algorithms ─────────────────────────────────────────────────
982
+ try:
983
+ from .algorithms_router import create_algorithms_router
984
+
985
+ if user_registry:
986
+ app.include_router(create_algorithms_router(
987
+ user_registry=user_registry,
988
+ tenant_registry=tenant_registry,
989
+ graph_registry=graph_registry,
990
+ ))
991
+ except Exception as _algo_err:
992
+ logging.getLogger(__name__).warning(f"Algorithms router not loaded: {_algo_err}")
993
+
994
+ # ── OpenTelemetry tracing (optional) ──────────────────────────────
995
+ try:
996
+ if os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") or os.environ.get("CONTEXTSYNAPSE_ENABLE_TRACING") or os.environ.get("AICONTEXTDB_ENABLE_TRACING"):
997
+ from opentelemetry import trace
998
+ from opentelemetry.sdk.trace import TracerProvider
999
+ from opentelemetry.sdk.trace.export import BatchSpanExporter, ConsoleSpanExporter
1000
+ from opentelemetry.sdk.resources import Resource
1001
+ from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
1002
+
1003
+ resource = Resource.create({"service.name": "contextsynapse", "service.version": "1.0.0"})
1004
+ provider = TracerProvider(resource=resource)
1005
+
1006
+ # Export to OTLP endpoint if configured, otherwise console
1007
+ otlp_endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
1008
+ if otlp_endpoint:
1009
+ try:
1010
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
1011
+ provider.add_span_processor(BatchSpanExporter(OTLPSpanExporter(endpoint=otlp_endpoint)))
1012
+ except ImportError:
1013
+ provider.add_span_processor(BatchSpanExporter(ConsoleSpanExporter()))
1014
+ else:
1015
+ provider.add_span_processor(BatchSpanExporter(ConsoleSpanExporter()))
1016
+
1017
+ trace.set_tracer_provider(provider)
1018
+
1019
+ try:
1020
+ FastAPIInstrumentor.instrument_app(app)
1021
+ logging.getLogger(__name__).info("OpenTelemetry tracing enabled")
1022
+ except Exception:
1023
+ logging.getLogger(__name__).debug("FastAPI instrumentation not available")
1024
+ except ImportError:
1025
+ pass # optional
1026
+ except Exception as _otel_err:
1027
+ logging.getLogger(__name__).debug("OpenTelemetry not configured: %s", _otel_err)
1028
+
1029
+ # ── Context Boundary Security ─────────────────────────────────────
1030
+ # Ensures:
1031
+ # 1. Agents can only access sessions they're members of
1032
+ # 2. Context data is read-only once attached to a boundary
1033
+ # 3. Cross-boundary data leakage is prevented
1034
+ # 4. All access is logged for audit trail
1035
+
1036
+ @app.middleware("http")
1037
+ async def context_boundary_middleware(request: Request, call_next):
1038
+ """Enforce context boundary isolation."""
1039
+ path = request.url.path
1040
+ method = request.method
1041
+
1042
+ # Only enforce on context/session/agent endpoints
1043
+ if not any(seg in path for seg in ["/sessions/", "/contexts/", "/agent/", "/boundaries/"]):
1044
+ return await call_next(request)
1045
+
1046
+ # Extract session_id from path if present
1047
+ import re
1048
+ session_match = re.search(r'/sessions/([a-f0-9]+)', path)
1049
+
1050
+ if session_match and method in ("POST", "PUT", "DELETE"):
1051
+ session_id = session_match.group(1)
1052
+ # In production, verify agent/user has access to this session
1053
+ if os.environ.get("CONTEXTSYNAPSE_ENFORCE_TENANT_SCOPE") or os.environ.get("AICONTEXTDB_ENFORCE_TENANT_SCOPE") == "1":
1054
+ # Check agent auth
1055
+ auth_header = request.headers.get("authorization", "")
1056
+ if auth_header.startswith("Bearer ") and ":" in auth_header[7:]:
1057
+ # Agent auth — verify session membership
1058
+ agent_key = auth_header[7:]
1059
+ agent_id = agent_key.split(":")[0]
1060
+ try:
1061
+ if _session_mgr:
1062
+ access = _session_mgr.get_access_list(session_id) or []
1063
+ member_ids = [m.get("agent_id", "") for m in access if isinstance(m, dict)]
1064
+ if agent_id not in member_ids:
1065
+ from fastapi.responses import JSONResponse
1066
+ return JSONResponse(
1067
+ status_code=403,
1068
+ content={"detail": "Agent not authorized for this boundary"},
1069
+ )
1070
+ except Exception:
1071
+ pass # optional
1072
+
1073
+ response = await call_next(request)
1074
+ return response
1075
+
1076
+ # ── Metering + Quota middleware ────────────────────────────────────
1077
+ # Maps URL path patterns to metering event types for accurate tracking
1078
+ _METERING_ROUTES = {
1079
+ "/query": "query",
1080
+ "/aiql": "query",
1081
+ "/search": "search",
1082
+ "/rag": "search",
1083
+ "/ingest": "ingest",
1084
+ "/graphs": "graph_create",
1085
+ "/agents": "agent_create",
1086
+ "/contexts": "context_build",
1087
+ "/nodes": "node_create",
1088
+ }
1089
+
1090
+ @app.middleware("http")
1091
+ async def metering_middleware(request: Request, call_next):
1092
+ # Resolve tenant from JWT before processing the request
1093
+ if not hasattr(request.state, 'tenant') or request.state.tenant is None:
1094
+ try:
1095
+ auth_header = request.headers.get("authorization", "")
1096
+ if auth_header.startswith("Bearer ") and user_registry and tenant_registry:
1097
+ token = auth_header[7:]
1098
+ from .auth import verify_jwt
1099
+ payload = verify_jwt(token)
1100
+ if payload and "user_id" in payload:
1101
+ tid = user_registry.get_primary_tenant_id(payload["user_id"])
1102
+ if tid:
1103
+ request.state.tenant = tenant_registry.get(tid)
1104
+ except Exception:
1105
+ pass # optional
1106
+
1107
+ # Quota check on mutating requests (POST/PUT/DELETE) — before processing
1108
+ if quota_enforcer and request.method in ("POST", "PUT") and hasattr(request.state, 'tenant') and request.state.tenant:
1109
+ tid = request.state.tenant.tenant_id
1110
+ path = request.url.path.lower()
1111
+ try:
1112
+ if "/graphs" in path and request.method == "POST" and "/query" not in path:
1113
+ count = len(graph_registry.list_graphs()) if graph_registry else 0
1114
+ quota_enforcer.check(tid, "graphs", count)
1115
+ elif "/agents" in path and request.method == "POST":
1116
+ from .dashboard_router import _agent_reg as _ar
1117
+ count = len(_ar.list_agents()) if _ar else 0
1118
+ quota_enforcer.check(tid, "agents", count)
1119
+ except HTTPException:
1120
+ raise
1121
+ except Exception:
1122
+ pass # optional
1123
+
1124
+ response = await call_next(request)
1125
+
1126
+ # Record usage after successful requests
1127
+ if usage_meter and hasattr(request.state, 'tenant') and request.state.tenant and response.status_code < 400:
1128
+ try:
1129
+ tid = request.state.tenant.tenant_id
1130
+ path = request.url.path.lower()
1131
+ # Determine event type from path
1132
+ event_type = "api_call"
1133
+ for pattern, etype in _METERING_ROUTES.items():
1134
+ if pattern in path:
1135
+ event_type = etype
1136
+ break
1137
+ usage_meter.record(tid, event_type)
1138
+ except Exception:
1139
+ pass # optional
1140
+ return response
1141
+
1142
+ # Mount Context-as-a-Service router
1143
+ try:
1144
+ from .context_router import create_context_router
1145
+ app.include_router(create_context_router(graph_registry))
1146
+ except Exception as _ctx_err:
1147
+ logging.getLogger(__name__).warning(f"Context router not loaded: {_ctx_err}")
1148
+
1149
+ # Mount Agent Worker router (remote agent task polling, claiming, graph access)
1150
+ try:
1151
+ from .agent_worker_router import create_agent_worker_router
1152
+ app.include_router(create_agent_worker_router(graph_registry))
1153
+ except Exception as _aw_err:
1154
+ logging.getLogger(__name__).warning(f"Agent worker router not loaded: {_aw_err}")
1155
+
1156
+ # Mount MCP multi-session app (agents connect via /mcp/sessions/{session_id}/sse)
1157
+ try:
1158
+ from ..mcp.server import create_multi_session_app
1159
+ mcp_app = create_multi_session_app(graph_registry)
1160
+ app.mount("/mcp", mcp_app)
1161
+ logging.getLogger(__name__).info("MCP multi-session app mounted at /mcp")
1162
+ except Exception as _mcp_err:
1163
+ logging.getLogger(__name__).warning(f"MCP multi-session app not loaded: {_mcp_err}")
1164
+
1165
+ # Mount Boundary router (atomic contexts + runtime context boundaries)
1166
+ try:
1167
+ from .boundary_router import create_boundary_router
1168
+ app.include_router(create_boundary_router(graph_registry))
1169
+ except Exception as _br_err:
1170
+ logging.getLogger(__name__).warning(f"Boundary router not loaded: {_br_err}")
1171
+
1172
+ # ── A2A Protocol ─────────────────────────────────────────────────────
1173
+ try:
1174
+ from .a2a_router import create_a2a_router
1175
+ app.include_router(create_a2a_router(
1176
+ graph_registry=graph_registry,
1177
+ agent_registry=_agent_reg,
1178
+ session_manager=_session_mgr,
1179
+ tool_registry=None, # Loaded lazily via ToolRegistry singleton
1180
+ tool_gateway=None,
1181
+ pubsub=None,
1182
+ ))
1183
+ logger.info("A2A protocol router mounted")
1184
+ except Exception as _a2a_err:
1185
+ logger.warning(f"A2A router not loaded: {_a2a_err}")
1186
+
1187
+ # Mount federation router
1188
+ try:
1189
+ from .federation_router import create_federation_router
1190
+ from .auth import UserAuth
1191
+ _fed_auth = UserAuth(user_registry) if user_registry else None
1192
+ app.include_router(create_federation_router(
1193
+ graph_registry=graph_registry,
1194
+ user_auth=_fed_auth or (lambda: None),
1195
+ require_admin=_fed_auth or (lambda: None),
1196
+ ))
1197
+ logger.info("Federation router mounted")
1198
+ except Exception as _fed_err:
1199
+ logging.getLogger(__name__).warning(f"Federation router not loaded: {_fed_err}")
1200
+
1201
+ # Mount cognition router
1202
+ try:
1203
+ from .cognition_router import create_cognition_router
1204
+ app.include_router(create_cognition_router(
1205
+ graph_registry=graph_registry,
1206
+ user_auth=_fed_auth or (lambda: None),
1207
+ ))
1208
+ logger.info("Cognition router mounted")
1209
+ except Exception as _cog_err:
1210
+ logging.getLogger(__name__).warning(f"Cognition router not loaded: {_cog_err}")
1211
+
1212
+ # Mount intelligence router
1213
+ try:
1214
+ from .intelligence_router import create_intelligence_router
1215
+ app.include_router(create_intelligence_router(
1216
+ context_manager=_context_mgr,
1217
+ graph_registry=graph_registry,
1218
+ ))
1219
+ logger.info("Intelligence router mounted")
1220
+ except Exception as _intel_err:
1221
+ import traceback as _tb
1222
+ logging.getLogger(__name__).error(f"Intelligence router not loaded: {_intel_err}\n{_tb.format_exc()}")
1223
+
1224
+ # Mount fusion router
1225
+ try:
1226
+ from .fusion_router import create_fusion_router
1227
+ app.include_router(create_fusion_router(graph_registry=graph_registry))
1228
+ logger.info("Fusion router mounted")
1229
+ except Exception as _fuse_err:
1230
+ logging.getLogger(__name__).warning(f"Fusion router not loaded: {_fuse_err}")
1231
+
1232
+ # Mount shield router
1233
+ try:
1234
+ from .shield_router import create_shield_router
1235
+ app.include_router(create_shield_router(
1236
+ user_auth=_fed_auth or (lambda: None),
1237
+ ))
1238
+ logger.info("Shield router mounted")
1239
+ except Exception as _sh_err:
1240
+ logging.getLogger(__name__).warning(f"Shield router not loaded: {_sh_err}")
1241
+
1242
+ # Mount PMS router (portfolio management, trades, compliance, tax, fees)
1243
+ try:
1244
+ from .pms_router import create_pms_router
1245
+ app.include_router(create_pms_router(graph_registry=graph_registry))
1246
+ logger.info("PMS router mounted")
1247
+ except Exception as _pms_err:
1248
+ logging.getLogger(__name__).warning(f"PMS router not loaded: {_pms_err}")
1249
+
1250
+ # Mount PMS WebSocket
1251
+ try:
1252
+ from .pms_websocket import create_ws_router as create_pms_ws
1253
+ app.include_router(create_pms_ws())
1254
+ logger.info("PMS WebSocket mounted")
1255
+ except Exception as _ws_err:
1256
+ logging.getLogger(__name__).warning(f"PMS WebSocket not loaded: {_ws_err}")
1257
+
1258
+ # Mount connector router (RSS, Webhook, Kafka, Scraper)
1259
+ try:
1260
+ from ..connectors.api_router import create_connector_router
1261
+ app.include_router(create_connector_router(
1262
+ graph_registry=graph_registry,
1263
+ context_manager=_context_mgr,
1264
+ session_manager=_session_mgr,
1265
+ user_auth=_fed_auth or (lambda: None),
1266
+ ))
1267
+ logger.info("Connector router mounted")
1268
+ except Exception as _conn_err:
1269
+ logging.getLogger(__name__).warning(f"Connector router not loaded: {_conn_err}")
1270
+
1271
+ # Mount pipeline connector router (batch, streaming, webhook)
1272
+ try:
1273
+ from .connector_router import create_connector_router as _create_pipeline_router
1274
+ app.include_router(_create_pipeline_router(graph_registry=graph_registry))
1275
+ logger.info("Pipeline connector router mounted")
1276
+ except Exception as _pcr_err:
1277
+ logging.getLogger(__name__).warning(f"Pipeline connector router not loaded: {_pcr_err}")
1278
+
1279
+ # Optional: in-process stream task consumer
1280
+ # In-process stream consumer — GIL-friendly short polls (no blocking XREADGROUP)
1281
+ try:
1282
+ from ..project.task_stream import TaskStreamConsumer, get_task_publisher
1283
+ import threading as _threading
1284
+
1285
+ _publisher = get_task_publisher()
1286
+ if _publisher._redis:
1287
+ _stream_ns = os.environ.get("CONTEXTSYNAPSE_STREAM_NAMESPACE") or os.environ.get("AICONTEXTDB_STREAM_NAMESPACE", "default")
1288
+
1289
+ def _stream_worker_callback(task_data):
1290
+ """Notify connected agents when tasks arrive via event bus."""
1291
+ task_id = task_data.get("task_id", "?")
1292
+ logger.info("[STREAM] Task available: %s", task_id)
1293
+ event_bus.emit("task_available", {
1294
+ "task_id": task_id,
1295
+ "priority": task_data.get("priority", "0"),
1296
+ "namespace": _stream_ns,
1297
+ })
1298
+
1299
+ _stream_consumer = TaskStreamConsumer(
1300
+ redis_client=_publisher._redis,
1301
+ namespace=_stream_ns,
1302
+ publisher=_publisher,
1303
+ on_task=_stream_worker_callback,
1304
+ block_ms=500, # Short poll — yields GIL every 500ms
1305
+ )
1306
+
1307
+ def _stream_loop():
1308
+ import time as _t
1309
+ while True:
1310
+ try:
1311
+ _stream_consumer.poll_once()
1312
+ except Exception as e:
1313
+ logger.debug("[STREAM] poll error: %s", e)
1314
+ _t.sleep(0.1) # Yield GIL between polls
1315
+
1316
+ _stream_thread = _threading.Thread(target=_stream_loop, name="stream-consumer", daemon=True)
1317
+ _stream_thread.start()
1318
+ logger.info("In-process stream consumer started on tasks:%s (non-blocking)", _stream_ns)
1319
+ except Exception as _sw_err:
1320
+ logging.getLogger(__name__).warning("Stream consumer not started: %s", _sw_err)
1321
+
1322
+ # ── API v1 — all routers also available under /api/v1/ prefix ────────
1323
+ try:
1324
+ from .v1 import v1_router, mount_v1_routers
1325
+ mount_v1_routers(
1326
+ v1_router,
1327
+ tenant_registry=tenant_registry,
1328
+ user_registry=user_registry,
1329
+ graph_registry=graph_registry,
1330
+ usage_meter=usage_meter,
1331
+ agent_registry=_agent_reg,
1332
+ session_manager=_session_mgr,
1333
+ audit_log=_audit_log,
1334
+ billing_manager=billing_manager,
1335
+ quota_enforcer=quota_enforcer,
1336
+ integration_registry=integration_registry if 'integration_registry' in dir() else None,
1337
+ )
1338
+ app.include_router(v1_router)
1339
+ logger.info("API v1 router mounted at /api/v1")
1340
+ except Exception as _v1_err:
1341
+ logging.getLogger(__name__).warning(f"API v1 router not loaded: {_v1_err}")
1342
+
1343
+ # API-Version response header
1344
+ @app.middleware("http")
1345
+ async def api_version_header(request: Request, call_next):
1346
+ response = await call_next(request)
1347
+ response.headers["API-Version"] = "v1"
1348
+ return response
1349
+
1350
+ # Session management for context (USE NAMESPACE/COLLECTION)
1351
+ _sessions = {} # session_id -> {active_namespace, active_collection, contextcore}
1352
+ _executor_pool = {} # namespace -> executor mapping for reuse
1353
+ _sessions_lock = threading.RLock()
1354
+ _executor_pool_lock = threading.RLock()
1355
+
1356
+ def _cleanup_expired_sessions():
1357
+ """Remove expired sessions from memory."""
1358
+ import time
1359
+ current_time = time.time()
1360
+ with _sessions_lock:
1361
+ expired_ids = []
1362
+
1363
+ for session_id, session in _sessions.items():
1364
+ elapsed = current_time - session.get('created_at', current_time)
1365
+ timeout = session.get('timeout', 3600)
1366
+ if elapsed > timeout:
1367
+ expired_ids.append(session_id)
1368
+
1369
+ for session_id in expired_ids:
1370
+ del _sessions[session_id]
1371
+
1372
+ if expired_ids:
1373
+ logger.info(f"[EMOJI] Cleaned up {len(expired_ids)} expired sessions")
1374
+
1375
+ def _create_session(namespace: str, graph: AIContextDB, request: dict = None, client_info: dict = None) -> str:
1376
+ """
1377
+ Create new session for stateful mode (CLI / Interactive Sessions).
1378
+
1379
+ Args:
1380
+ namespace: Active namespace for the session
1381
+ graph: AIContextDB graph instance
1382
+ request: Optional request dictionary for extracting client info
1383
+ client_info: Optional pre-extracted client info
1384
+
1385
+ Returns:
1386
+ session_id: Unique session identifier
1387
+ """
1388
+ import uuid
1389
+ import time
1390
+
1391
+ session_id = str(uuid.uuid4())
1392
+
1393
+ if client_info is None:
1394
+ client_info = _get_client_info(request) if request else {}
1395
+
1396
+ with _sessions_lock:
1397
+ _sessions[session_id] = {
1398
+ 'active_namespace': namespace,
1399
+ 'active_collection': None,
1400
+ 'contextcore': graph,
1401
+ 'created_at': time.time(),
1402
+ 'last_accessed': time.time(),
1403
+ 'session_id': session_id,
1404
+ 'query_count': 0,
1405
+ 'last_query': None,
1406
+ 'error_count': 0,
1407
+ 'timeout': 3600, # 1 hour default
1408
+ 'client_info': {
1409
+ 'api_version': 'v1',
1410
+ 'created_at': time.time(),
1411
+ 'user_agent': client_info.get('user_agent', 'Unknown'),
1412
+ 'ip_address': client_info.get('ip_address', 'Unknown'),
1413
+ 'client_version': client_info.get('client_version', '1.0.0')
1414
+ },
1415
+ 'performance': {
1416
+ 'total_query_time': 0.0,
1417
+ 'total_queries': 0,
1418
+ 'avg_response_time': 0.0,
1419
+ 'min_response_time': float('inf'),
1420
+ 'max_response_time': 0.0,
1421
+ 'cache_hits': 0,
1422
+ 'cache_misses': 0,
1423
+ 'error_rate': 0.0
1424
+ },
1425
+ 'security': {
1426
+ 'user_id': request.get('user_id', None) if request else None,
1427
+ 'role': request.get('role', 'user') if request else 'user',
1428
+ 'permissions': request.get('permissions', []) if request else [],
1429
+ 'authenticated': request.get('authenticated', False) if request else False,
1430
+ 'ip_address': client_info.get('ip_address', 'Unknown')
1431
+ },
1432
+ 'monitoring': {
1433
+ 'alerts': [],
1434
+ 'warnings': [],
1435
+ 'health_score': 100.0,
1436
+ 'last_health_check': time.time()
1437
+ }
1438
+ }
1439
+
1440
+ logger.debug(f"[SESSION] Created new session {session_id[:8]}... for namespace '{namespace}'")
1441
+ return session_id
1442
+
1443
+ def _update_session(session_id: str, executor, old_namespace: str):
1444
+ """
1445
+ Update session after query execution.
1446
+ Handles namespace switching and graph updates.
1447
+
1448
+ Args:
1449
+ session_id: Session identifier
1450
+ executor: AIQLExecutor instance (may have updated namespace/graph)
1451
+ old_namespace: Previous namespace (to detect changes)
1452
+ """
1453
+ import time
1454
+
1455
+ with _sessions_lock:
1456
+ if session_id not in _sessions:
1457
+ return
1458
+
1459
+ session = _sessions[session_id]
1460
+
1461
+ # Update namespace if changed via USE NAMESPACE query
1462
+ if hasattr(executor, 'active_namespace') and executor.active_namespace:
1463
+ new_namespace = executor.active_namespace
1464
+ if new_namespace != old_namespace:
1465
+ # Namespace changed - load new graph
1466
+ new_graph = graph_registry.get_graph(new_namespace, load_if_missing=True)
1467
+ if new_graph:
1468
+ session['active_namespace'] = new_namespace
1469
+ session['contextcore'] = new_graph
1470
+ logger.debug(f"[SESSION] Updated session {session_id[:8]}... namespace: {old_namespace} -> {new_namespace}")
1471
+
1472
+ # Update graph reference if executor's graph changed
1473
+ if hasattr(executor, 'contextcore') and executor.contextcore:
1474
+ session['contextcore'] = executor.contextcore
1475
+
1476
+ # Update collection if changed
1477
+ if hasattr(executor, 'active_collection') and executor.active_collection:
1478
+ session['active_collection'] = executor.active_collection
1479
+
1480
+ # Update metrics
1481
+ session['query_count'] = session.get('query_count', 0) + 1
1482
+ session['last_accessed'] = time.time()
1483
+
1484
+ def _ensure_dict(body) -> dict:
1485
+ """
1486
+ Ensure the request body is a dict.
1487
+ Handles cases where clients (e.g. PowerShell Invoke-WebRequest) send
1488
+ the JSON body as a raw string instead of parsed JSON.
1489
+ """
1490
+ if isinstance(body, dict):
1491
+ return body
1492
+ if isinstance(body, str):
1493
+ try:
1494
+ parsed = json.loads(body)
1495
+ if isinstance(parsed, dict):
1496
+ return parsed
1497
+ except (json.JSONDecodeError, TypeError):
1498
+ pass # optional
1499
+ raise HTTPException(status_code=400, detail="Request body must be valid JSON object")
1500
+ raise HTTPException(status_code=400, detail=f"Unexpected body type: {type(body).__name__}")
1501
+
1502
+ def _get_client_info(request: dict):
1503
+ """Extract client information from request."""
1504
+ if not isinstance(request, dict):
1505
+ return {'user_agent': 'Unknown', 'ip_address': 'Unknown', 'client_version': '1.0.0'}
1506
+ return {
1507
+ 'user_agent': request.get('user_agent', 'Unknown'),
1508
+ 'ip_address': request.get('ip_address', 'Unknown'),
1509
+ 'client_version': request.get('client_version', '1.0.0')
1510
+ }
1511
+
1512
+ def _track_performance(session: dict, start_time: float, result: dict):
1513
+ """Track performance metrics for the session."""
1514
+ import time
1515
+
1516
+ query_time = time.time() - start_time
1517
+
1518
+ # Update performance metrics
1519
+ if 'performance' not in session:
1520
+ session['performance'] = {
1521
+ 'total_query_time': 0.0,
1522
+ 'total_queries': 0,
1523
+ 'avg_response_time': 0.0,
1524
+ 'min_response_time': float('inf'),
1525
+ 'max_response_time': 0.0,
1526
+ 'cache_hits': 0,
1527
+ 'cache_misses': 0,
1528
+ 'error_rate': 0.0
1529
+ }
1530
+
1531
+ perf = session['performance']
1532
+ perf['total_query_time'] += query_time
1533
+ perf['total_queries'] += 1
1534
+ perf['avg_response_time'] = perf['total_query_time'] / perf['total_queries']
1535
+ perf['min_response_time'] = min(perf['min_response_time'], query_time)
1536
+ perf['max_response_time'] = max(perf['max_response_time'], query_time)
1537
+
1538
+ # Track errors
1539
+ if not result.get('success'):
1540
+ perf['error_rate'] = perf['total_queries'] / perf['total_queries'] if perf['total_queries'] > 0 else 0.0
1541
+
1542
+ return perf
1543
+
1544
+ # Auto-save configuration
1545
+ AUTO_SAVE_ENABLED = True
1546
+ AUTO_SAVE_INTERVAL = 30 # seconds
1547
+ last_save_time = 0
1548
+
1549
+ async def auto_save_graph(graph_db: QGraphDB):
1550
+ """Auto-save graph if enabled and enough time has passed (synchronous version for compatibility)."""
1551
+ global last_save_time
1552
+ if not AUTO_SAVE_ENABLED:
1553
+ logger.debug("Auto-save disabled, skipping")
1554
+ return
1555
+
1556
+ current_time = time.time()
1557
+ if current_time - last_save_time >= AUTO_SAVE_INTERVAL:
1558
+ try:
1559
+ logger.debug(f"Auto-saving graph '{graph_db.name}' (last save: {current_time - last_save_time:.1f}s ago)")
1560
+ success = graph_registry.save_graph(graph_db.name)
1561
+ if success:
1562
+ last_save_time = current_time
1563
+ logger.debug(f"Auto-saved graph '{graph_db.name}'")
1564
+ else:
1565
+ logger.warning(f"Failed to auto-save graph '{graph_db.name}'")
1566
+ except Exception as e:
1567
+ logger.error(f"Auto-save error: {e}")
1568
+ else:
1569
+ logger.debug(f"Auto-save skipped (last save: {current_time - last_save_time:.1f}s ago, interval: {AUTO_SAVE_INTERVAL}s)")
1570
+
1571
+ async def auto_save_graph_async(graph_db: QGraphDB):
1572
+ """Async auto-save graph (non-blocking, fire-and-forget version)."""
1573
+ global last_save_time
1574
+ if not AUTO_SAVE_ENABLED:
1575
+ return
1576
+
1577
+ current_time = time.time()
1578
+ if current_time - last_save_time >= AUTO_SAVE_INTERVAL:
1579
+ try:
1580
+ # Run save in thread pool to avoid blocking
1581
+ import asyncio
1582
+ loop = asyncio.get_event_loop()
1583
+ success = await loop.run_in_executor(None, graph_registry.save_graph, graph_db.name)
1584
+ if success:
1585
+ last_save_time = current_time
1586
+ logger.debug(f"Background auto-saved graph '{graph_db.name}'")
1587
+ else:
1588
+ logger.warning(f"Background auto-save failed for graph '{graph_db.name}'")
1589
+ except Exception as e:
1590
+ logger.error(f"Background auto-save error: {e}")
1591
+
1592
+ # Pydantic models
1593
+ class NodeCreate(BaseModel):
1594
+ id: str
1595
+ label: str
1596
+ properties: Dict[str, Any] = {}
1597
+
1598
+ class EdgeCreate(BaseModel):
1599
+ source: str
1600
+ target: str
1601
+ relationship: str
1602
+ properties: Dict[str, Any] = {}
1603
+ weight: float = 1.0
1604
+
1605
+ class GraphCreate(BaseModel):
1606
+ name: str
1607
+ config: Optional[Dict[str, Any]] = {}
1608
+
1609
+ class QueryRequest(BaseModel):
1610
+ query: str
1611
+ graph_name: Optional[str] = None
1612
+
1613
+ class SearchRequest(BaseModel):
1614
+ query: str
1615
+ target: str = "nodes"
1616
+ limit: int = 10
1617
+ strategy: str = "hybrid"
1618
+
1619
+ class TransactionRequest(BaseModel):
1620
+ operations: List[Dict[str, Any]]
1621
+
1622
+ class ConstraintConfig(BaseModel):
1623
+ node_constraints: Optional[Dict[str, List[str]]] = {}
1624
+ edge_constraints: Optional[Dict[str, List[str]]] = {}
1625
+
1626
+ # Dependency to get current graph — always goes through registry (thread-safe)
1627
+ def get_current_graph(graph: str = Query("default", alias="graph")):
1628
+ """Get graph by namespace. Defaults to 'default' if not specified."""
1629
+ namespace = graph or "default"
1630
+ db = graph_registry.get_graph(namespace, load_if_missing=True)
1631
+ if db is None:
1632
+ db = graph_registry.create_graph(namespace)
1633
+ return db
1634
+
1635
+ # Root endpoint
1636
+ @app.get("/", response_class=HTMLResponse)
1637
+ async def root():
1638
+ """Root endpoint with API information."""
1639
+ return """
1640
+ <html>
1641
+ <head>
1642
+ <title>ContextCore API</title>
1643
+ <style>
1644
+ body { font-family: Arial, sans-serif; margin: 40px; }
1645
+ .header { color: #2c3e50; }
1646
+ .endpoint { background: #f8f9fa; padding: 10px; margin: 10px 0; border-radius: 5px; }
1647
+ .method { font-weight: bold; color: #27ae60; }
1648
+ </style>
1649
+ </head>
1650
+ <body>
1651
+ <h1 class="header">[EMOJI] ContextCore API</h1>
1652
+ <p>Graph RAG + Agentic AI Native GraphDB Package</p>
1653
+
1654
+ <h2>Quick Links</h2>
1655
+ <div class="endpoint">
1656
+ <span class="method">GET</span> <a href="/docs">/docs</a> - Interactive API Documentation
1657
+ </div>
1658
+ <div class="endpoint">
1659
+ <span class="method">GET</span> <a href="/health">/health</a> - Health Check
1660
+ </div>
1661
+ <div class="endpoint">
1662
+ <span class="method">GET</span> <a href="/graphs">/graphs</a> - List All Graphs
1663
+ </div>
1664
+
1665
+ <h2>Core Features</h2>
1666
+ <ul>
1667
+ <li>[EMOJI] Graph Database Operations (CRUD)</li>
1668
+ <li>[EMOJI] QGRAQL Advanced Query Language</li>
1669
+ <li>[EMOJI] Enhanced Hybrid Search</li>
1670
+ <li>[EMOJI] Write-Ahead Logging (WAL)</li>
1671
+ <li>[EMOJI] AI/ML Integration</li>
1672
+ <li>[EMOJI] Real-time Statistics</li>
1673
+ </ul>
1674
+
1675
+ <h2>API Status</h2>
1676
+ <p>QGRAQL: {'[EMOJI] Available' if QGRAQL_AVAILABLE else '[EMOJI] Not Available'}</p>
1677
+ <p>Enhanced Search: {'[EMOJI] Available' if ENHANCED_SEARCH_AVAILABLE else '[EMOJI] Not Available'}</p>
1678
+ <p>WAL: {'[EMOJI] Available' if WAL_AVAILABLE else '[EMOJI] Not Available'}</p>
1679
+ <p>LLM: {'[EMOJI] Available' if LLM_AVAILABLE else '[EMOJI] Not Available'}</p>
1680
+ </body>
1681
+ </html>
1682
+ """
1683
+
1684
+ # Health check endpoint — public (no auth) for load-balancer probes.
1685
+ # Intentionally does NOT expose graph counts or internal state.
1686
+ @app.get("/health")
1687
+ async def health():
1688
+ """Liveness probe — is the process alive? K8s restarts pod if this fails."""
1689
+ return {"status": "healthy", "timestamp": datetime.now().isoformat()}
1690
+
1691
+
1692
+ # ── Prediction endpoints ──
1693
+ @app.get("/predictions/accuracy")
1694
+ async def _api_predictions_accuracy():
1695
+ try:
1696
+ import sys as _sys
1697
+ from pathlib import Path as _P
1698
+ _root = str(_P(__file__).parent.parent.parent)
1699
+ if _root not in _sys.path:
1700
+ _sys.path.insert(0, _root)
1701
+ from plugins.stock_analysis.predictor import PredictionTracker
1702
+ tracker = PredictionTracker(graph_registry=graph_registry)
1703
+ return tracker.get_accuracy()
1704
+ except Exception as e:
1705
+ return {"error": str(e), "type": type(e).__name__}
1706
+
1707
+ @app.post("/predictions/predict/{entity}")
1708
+ async def _api_predict_entity(entity: str):
1709
+ try:
1710
+ import sys as _sys
1711
+ from pathlib import Path as _P
1712
+ _root = str(_P(__file__).parent.parent.parent)
1713
+ if _root not in _sys.path:
1714
+ _sys.path.insert(0, _root)
1715
+ from plugins.stock_analysis.predictor import PredictionTracker
1716
+ tracker = PredictionTracker(graph_registry=graph_registry)
1717
+ pred = tracker.predict(entity)
1718
+ return pred.to_dict()
1719
+ except Exception as e:
1720
+ return {"error": str(e), "type": type(e).__name__}
1721
+
1722
+
1723
+ @app.get("/graph/fusion/{entity}")
1724
+ async def _api_fusion(entity: str, days: int = 7):
1725
+ import json as _json
1726
+ import os as _os
1727
+
1728
+ # ── Resolve NSE/BSE ticker → canonical entity name ────────
1729
+ # e.g. "APOLLOHOSP" → "apollo_hospitals", "TCS" → "tcs"
1730
+ # The fusion engine stores graphs by entity name, not ticker.
1731
+ _e_lower = entity.lower().replace(".ns", "").replace(".bo", "")
1732
+ try:
1733
+ from plugins.stock_analysis.config import TICKERS
1734
+ for _cname, _info in TICKERS.items():
1735
+ _ticker = (_info.get("ticker") or "").replace(".NS", "").replace(".BO", "").lower()
1736
+ if _ticker == _e_lower:
1737
+ _e_lower = _cname.lower()
1738
+ break
1739
+ except Exception:
1740
+ pass
1741
+ entity = _e_lower # canonical form for cache key + engine call
1742
+
1743
+ # ── Redis cache check (serve stale data immediately) ──────
1744
+ cache_key = f"fusion:{entity}:{days}"
1745
+ _redis_client = None
1746
+ try:
1747
+ import redis as _redis_mod
1748
+ _redis_client = _redis_mod.Redis.from_url(
1749
+ _os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL", "redis://localhost:6379/0"),
1750
+ socket_connect_timeout=1, socket_timeout=5,
1751
+ )
1752
+ cached = _redis_client.get(cache_key)
1753
+ if cached:
1754
+ payload = _json.loads(cached)
1755
+ payload["_cache"] = "hit"
1756
+ return payload
1757
+ except Exception:
1758
+ pass # Redis unavailable — fall through to live compute
1759
+
1760
+ # ── Live compute (offloaded to thread pool — never blocks event loop) ───
1761
+ import asyncio as _asyncio
1762
+ import sys as _sys
1763
+ from pathlib import Path as _P
1764
+ _root = str(_P(__file__).parent.parent.parent)
1765
+ if _root not in _sys.path:
1766
+ _sys.path.insert(0, _root)
1767
+
1768
+ def _compute_fusion():
1769
+ from plugins.stock_analysis.sensor_fusion import SensorFusionEngine
1770
+ eng = SensorFusionEngine(graph_registry=graph_registry)
1771
+ return eng.fuse(entity, days=days).to_dict()
1772
+
1773
+ try:
1774
+ loop = _asyncio.get_event_loop()
1775
+ data = await loop.run_in_executor(None, _compute_fusion)
1776
+ data["_cache"] = "miss"
1777
+
1778
+ if _redis_client:
1779
+ try:
1780
+ # TTL = 600s — matches the refresh loop's cache TTL so live-computed
1781
+ # results survive until the background refresher overwrites them.
1782
+ # Use orjson when available — plain json.dumps fails on numpy.float32.
1783
+ try:
1784
+ import orjson as _orjson
1785
+ _payload = _orjson.dumps(data, option=_orjson.OPT_NON_STR_KEYS | _orjson.OPT_SERIALIZE_NUMPY).decode()
1786
+ except ImportError:
1787
+ _payload = _json.dumps(data, default=lambda x: float(x) if hasattr(x, "__float__") else str(x))
1788
+ _redis_client.setex(cache_key, 600, _payload)
1789
+ except Exception:
1790
+ pass
1791
+
1792
+ return data
1793
+ except Exception as e:
1794
+ return {"error": str(e), "type": type(e).__name__}
1795
+
1796
+
1797
+ @app.get("/ready")
1798
+ async def readiness():
1799
+ """Readiness probe — can the pod serve traffic? K8s removes from LB if this fails."""
1800
+ checks = {}
1801
+
1802
+ # Check Redis connectivity
1803
+ try:
1804
+ redis_url = os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL")
1805
+ if redis_url:
1806
+ import redis
1807
+ r = redis.from_url(redis_url, decode_responses=True, socket_timeout=2)
1808
+ r.ping()
1809
+ checks["redis"] = "ok"
1810
+ else:
1811
+ checks["redis"] = "not_configured"
1812
+ except Exception as e:
1813
+ checks["redis"] = f"error: {e}"
1814
+
1815
+ # Check graph registry
1816
+ try:
1817
+ count = len(graph_registry.list_graphs()) if hasattr(graph_registry, "list_graphs") else 0
1818
+ checks["graph_registry"] = f"ok ({count} graphs)"
1819
+ except Exception as e:
1820
+ checks["graph_registry"] = f"error: {e}"
1821
+
1822
+ # Overall status
1823
+ has_errors = any("error" in str(v) for v in checks.values())
1824
+ status_code = 503 if has_errors else 200
1825
+
1826
+ from fastapi.responses import JSONResponse
1827
+ return JSONResponse(
1828
+ status_code=status_code,
1829
+ content={"status": "degraded" if has_errors else "ready", "checks": checks},
1830
+ )
1831
+
1832
+ # Graph management endpoints (require admin auth)
1833
+ @app.get("/graphs")
1834
+ async def list_graphs(_admin=Depends(AdminAuth())):
1835
+ """List all available graphs."""
1836
+ global current_graph
1837
+ return {
1838
+ "graphs": graph_registry.list_graphs(),
1839
+ "current": current_graph.name if current_graph else None
1840
+ }
1841
+
1842
+ @app.post("/graphs")
1843
+ async def create_graph(graph: GraphCreate, _admin=Depends(AdminAuth())):
1844
+ """Create a new graph."""
1845
+ global current_graph
1846
+ try:
1847
+ new_graph = graph_registry.create_graph(graph.name, config=graph.config)
1848
+ current_graph = new_graph
1849
+ return {
1850
+ "success": True,
1851
+ "message": f"Graph '{graph.name}' created successfully",
1852
+ "graph_name": graph.name
1853
+ }
1854
+ except Exception as e:
1855
+ raise HTTPException(status_code=400, detail=str(e))
1856
+
1857
+ @app.get("/graphs/{graph_name}")
1858
+ async def get_graph_info(graph_name: str, _admin=Depends(AdminAuth())):
1859
+ """Get information about a specific graph."""
1860
+ graph = graph_registry.get_graph(graph_name)
1861
+ if not graph:
1862
+ raise HTTPException(status_code=404, detail="Graph not found")
1863
+
1864
+ # Get node and edge counts using CSR storage
1865
+ node_count = 0
1866
+ edge_count = 0
1867
+ if hasattr(graph, 'csr_storage') and graph.csr_storage:
1868
+ node_count = graph.csr_storage.get_node_count() if hasattr(graph.csr_storage, 'get_node_count') else 0
1869
+ edge_count = graph.csr_storage.get_edge_count() if hasattr(graph.csr_storage, 'get_edge_count') else 0
1870
+ elif hasattr(graph, 'node_index'):
1871
+ node_count = len(graph.node_index) if graph.node_index else 0
1872
+
1873
+ return {
1874
+ "name": graph.name,
1875
+ "nodes": node_count,
1876
+ "edges": edge_count,
1877
+ "config": graph.config
1878
+ }
1879
+
1880
+ @app.delete("/graphs/{graph_name}")
1881
+ async def delete_graph(graph_name: str, _admin=Depends(AdminAuth())):
1882
+ """Delete a graph."""
1883
+ global current_graph
1884
+ try:
1885
+ if graph_name in graph_registry.graphs:
1886
+ # Clean LMDB index before evicting graph
1887
+ try:
1888
+ from ..search.lmdb_index import remove_lmdb_index
1889
+ remove_lmdb_index(graph_name)
1890
+ except Exception:
1891
+ pass
1892
+ del graph_registry.graphs[graph_name]
1893
+ if current_graph and current_graph.name == graph_name:
1894
+ current_graph = None
1895
+ return {"message": f"Graph '{graph_name}' deleted successfully"}
1896
+ else:
1897
+ raise HTTPException(status_code=404, detail="Graph not found")
1898
+ except Exception as e:
1899
+ raise HTTPException(status_code=400, detail=str(e))
1900
+
1901
+ @app.post("/graph/constraints")
1902
+ async def configure_constraints(constraints: ConstraintConfig, graph_db: QGraphDB = Depends(get_current_graph)):
1903
+ """Configure unique constraints for nodes and edges."""
1904
+ try:
1905
+ if constraints.node_constraints:
1906
+ graph_db.set_unique_constraints(constraints.node_constraints)
1907
+
1908
+ if constraints.edge_constraints:
1909
+ graph_db.set_edge_unique_constraints(constraints.edge_constraints)
1910
+
1911
+ return {
1912
+ "message": "Constraints configured successfully",
1913
+ "node_constraints": graph_db.get_unique_constraints(),
1914
+ "edge_constraints": graph_db.get_edge_unique_constraints()
1915
+ }
1916
+ except Exception as e:
1917
+ raise HTTPException(status_code=400, detail=str(e))
1918
+
1919
+ @app.get("/graph/constraints")
1920
+ async def get_constraints(graph_db: QGraphDB = Depends(get_current_graph)):
1921
+ """Get current unique constraints."""
1922
+ return {
1923
+ "node_constraints": graph_db.get_unique_constraints(),
1924
+ "edge_constraints": graph_db.get_edge_unique_constraints()
1925
+ }
1926
+
1927
+ @app.get("/graph")
1928
+ async def get_full_graph(graph_db: QGraphDB = Depends(get_current_graph)):
1929
+ """Get all nodes and edges in the current graph (for initial load)."""
1930
+ nodes = []
1931
+ edges = []
1932
+
1933
+ # Get all nodes
1934
+ if hasattr(graph_db, 'node_index') and graph_db.node_index:
1935
+ for node_id, node in graph_db.node_index.items():
1936
+ nodes.append({
1937
+ "id": node_id,
1938
+ "label": node.label,
1939
+ "properties": node.properties,
1940
+ "name": getattr(node, 'name', None),
1941
+ "uuid": getattr(node, 'uuid', node_id)
1942
+ })
1943
+
1944
+ # Get all edges
1945
+ if hasattr(graph_db, 'edge_index') and graph_db.edge_index:
1946
+ for edge_id, edge in graph_db.edge_index.items():
1947
+ # Resolve source/target UUIDs to display names
1948
+ source_name = edge.source
1949
+ target_name = edge.target
1950
+ if hasattr(graph_db, 'node_index') and graph_db.node_index:
1951
+ src_node = graph_db.node_index.get(edge.source)
1952
+ tgt_node = graph_db.node_index.get(edge.target)
1953
+ if src_node:
1954
+ source_name = (src_node.properties or {}).get('name') or getattr(src_node, 'name', None) or getattr(src_node, 'label', edge.source)
1955
+ if tgt_node:
1956
+ target_name = (tgt_node.properties or {}).get('name') or getattr(tgt_node, 'name', None) or getattr(tgt_node, 'label', edge.target)
1957
+ edges.append({
1958
+ "id": edge_id,
1959
+ "source": source_name,
1960
+ "target": target_name,
1961
+ "source_id": edge.source,
1962
+ "target_id": edge.target,
1963
+ "label": edge.label,
1964
+ "properties": edge.properties,
1965
+ "name": getattr(edge, 'name', None),
1966
+ "uuid": getattr(edge, 'uuid', edge_id)
1967
+ })
1968
+
1969
+ return {
1970
+ "nodes": nodes,
1971
+ "edges": edges,
1972
+ "metadata": {
1973
+ "node_count": len(nodes),
1974
+ "edge_count": len(edges),
1975
+ "graph_name": graph_db.name
1976
+ }
1977
+ }
1978
+
1979
+
1980
+ @app.get("/api/v1/data/{namespace}/graph")
1981
+ async def get_paginated_graph(
1982
+ namespace: str,
1983
+ page: int = Query(1, ge=1),
1984
+ size: int = Query(100, ge=1, le=1000),
1985
+ node_type: Optional[str] = Query(None, description="Filter nodes by label"),
1986
+ ):
1987
+ """Paginated graph data for large namespaces."""
1988
+ graph = graph_registry.get_graph(namespace, load_if_missing=True)
1989
+ if not graph:
1990
+ raise HTTPException(404, f"Namespace '{namespace}' not found")
1991
+
1992
+ all_nodes = []
1993
+ if hasattr(graph, 'node_index') and graph.node_index:
1994
+ for nid, node in graph.node_index.items():
1995
+ if node_type and node.label != node_type:
1996
+ continue
1997
+ all_nodes.append({
1998
+ "id": nid,
1999
+ "label": node.label,
2000
+ "name": (node.properties or {}).get("name") or getattr(node, "name", None),
2001
+ **{k: v for k, v in (node.properties or {}).items() if k != "name"},
2002
+ })
2003
+
2004
+ total = len(all_nodes)
2005
+ start = (page - 1) * size
2006
+ page_nodes = all_nodes[start : start + size]
2007
+ node_ids = {n["id"] for n in page_nodes}
2008
+
2009
+ # Return edges where both endpoints are in the page
2010
+ page_edges = []
2011
+ if hasattr(graph, 'edge_index') and graph.edge_index:
2012
+ for eid, edge in graph.edge_index.items():
2013
+ if edge.source in node_ids and edge.target in node_ids:
2014
+ page_edges.append({
2015
+ "id": eid,
2016
+ "source": edge.source,
2017
+ "target": edge.target,
2018
+ "label": edge.label,
2019
+ **(edge.properties or {}),
2020
+ })
2021
+
2022
+ return {
2023
+ "nodes": page_nodes,
2024
+ "edges": page_edges,
2025
+ "page": page,
2026
+ "size": size,
2027
+ "total_nodes": total,
2028
+ "has_more": start + size < total,
2029
+ }
2030
+
2031
+
2032
+ # Node operations
2033
+ @app.get("/graph/nodes")
2034
+ async def get_nodes(
2035
+ limit: int = Query(1000, ge=1, le=10000),
2036
+ offset: int = Query(0, ge=0),
2037
+ label: Optional[str] = Query(None),
2038
+ graph_db: QGraphDB = Depends(get_current_graph),
2039
+ ):
2040
+ """Get nodes in the current graph with pagination."""
2041
+ raw_nodes = graph_db.get_all_nodes(label=label, limit=limit, offset=offset)
2042
+ nodes = [
2043
+ {"id": n.id, "label": n.label, "properties": n.properties}
2044
+ for n in raw_nodes
2045
+ ]
2046
+ return {"nodes": nodes, "limit": limit, "offset": offset, "count": len(nodes)}
2047
+
2048
+ # Removed hardcoded TCS endpoints - now using generic /api/v1/data/{namespace}/ endpoints
2049
+
2050
+ @app.post("/rag/ask")
2051
+ async def ask_rag_question(question: dict):
2052
+ """Ask a natural language question using RAG system."""
2053
+ import json
2054
+ import os
2055
+ import hashlib
2056
+ import numpy as np
2057
+
2058
+ try:
2059
+ query_text = question.get("question", "")
2060
+ namespace = question.get("namespace", "default") # Default to default namespace
2061
+ print(f"[EMOJI] RAG Question: {query_text}")
2062
+ print(f"[EMOJI] Namespace: {namespace}")
2063
+
2064
+ # Load data from specified namespace
2065
+ namespace_data = []
2066
+ namespace_dir = f"contextcore_data/namespaces/{namespace}/nodes"
2067
+
2068
+ if os.path.exists(namespace_dir):
2069
+ for node_type in os.listdir(namespace_dir):
2070
+ node_type_dir = os.path.join(namespace_dir, node_type)
2071
+ if os.path.isdir(node_type_dir):
2072
+ for node_file in os.listdir(node_type_dir):
2073
+ if node_file.endswith('.json'):
2074
+ node_path = os.path.join(node_type_dir, node_file)
2075
+ try:
2076
+ with open(node_path, 'r') as f:
2077
+ node_data = json.load(f)
2078
+ node_data['node_type'] = node_type
2079
+ namespace_data.append(node_data)
2080
+ except Exception as e:
2081
+ continue
2082
+
2083
+ # Hybrid Search
2084
+ query_lower = query_text.lower()
2085
+ search_results = []
2086
+
2087
+ # Sparse search (keyword matching)
2088
+ for node in namespace_data:
2089
+ node_text = str(node).lower()
2090
+ score = 0
2091
+ query_words = query_lower.split()
2092
+ for word in query_words:
2093
+ if word in node_text:
2094
+ score += node_text.count(word)
2095
+
2096
+ if score > 0:
2097
+ search_results.append({
2098
+ 'node': node,
2099
+ 'score': score,
2100
+ 'type': 'sparse'
2101
+ })
2102
+
2103
+ # Sort by score and take top 10
2104
+ search_results.sort(key=lambda x: x['score'], reverse=True)
2105
+ search_results = search_results[:10]
2106
+
2107
+ # Extract context
2108
+ context = {
2109
+ 'chunks': [],
2110
+ 'entities': [],
2111
+ 'documents': [],
2112
+ 'tables': []
2113
+ }
2114
+
2115
+ for result in search_results:
2116
+ node = result['node']
2117
+ node_type = node.get('node_type', 'unknown')
2118
+
2119
+ if node_type == 'Chunk':
2120
+ context['chunks'].append({
2121
+ 'id': node.get('id'),
2122
+ 'text': node.get('text', ''),
2123
+ 'chunk_type': node.get('chunk_type', ''),
2124
+ 'score': result['score']
2125
+ })
2126
+ elif node_type == 'Entity':
2127
+ context['entities'].append({
2128
+ 'id': node.get('id'),
2129
+ 'name': node.get('name', ''),
2130
+ 'type': node.get('type', ''),
2131
+ 'confidence': node.get('confidence', 0),
2132
+ 'score': result['score']
2133
+ })
2134
+ elif node_type == 'Document':
2135
+ context['documents'].append({
2136
+ 'id': node.get('id'),
2137
+ 'title': node.get('title', ''),
2138
+ 'score': result['score']
2139
+ })
2140
+ elif node_type == 'Table':
2141
+ context['tables'].append({
2142
+ 'id': node.get('id'),
2143
+ 'table_type': node.get('table_type', ''),
2144
+ 'score': result['score']
2145
+ })
2146
+
2147
+ # Generate answer based on context
2148
+ chunks_text = "\n".join([chunk['text'] for chunk in context['chunks']])
2149
+ entities_text = ", ".join([f"{entity['name']} ({entity['type']})" for entity in context['entities']])
2150
+
2151
+ # Detect organization name from data
2152
+ organization_name = "the organization"
2153
+ for node in namespace_data:
2154
+ if node.get('type') == 'ORGANIZATION' or 'organization' in str(node).lower():
2155
+ organization_name = node.get('name', 'the organization')
2156
+ break
2157
+
2158
+ # Simple answer generation
2159
+ if 'financial' in query_lower or 'revenue' in query_lower:
2160
+ answer = f"Based on {organization_name}'s data, here are the key financial insights:\n\n"
2161
+ answer += f"Financial Performance: {chunks_text[:200]}...\n\n"
2162
+ answer += f"Key Entities: {entities_text}\n\n"
2163
+ answer += f"Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2164
+ elif 'ceo' in query_lower or 'leadership' in query_lower:
2165
+ answer = f"Leadership Information:\n\n"
2166
+ answer += f"Key Leadership Details: {chunks_text[:200]}...\n\n"
2167
+ answer += f"Related Entities: {entities_text}"
2168
+ elif 'employee' in query_lower or 'workforce' in query_lower:
2169
+ answer = f"Employee Metrics:\n\n"
2170
+ answer += f"Workforce Information: {chunks_text[:200]}...\n\n"
2171
+ answer += f"Key Metrics: {entities_text}"
2172
+ else:
2173
+ answer = f"Based on {organization_name}'s data, here's what I found:\n\n"
2174
+ answer += f"Relevant Information: {chunks_text[:300]}...\n\n"
2175
+ answer += f"Key Entities: {entities_text}\n\n"
2176
+ answer += f"Sources: {len(search_results)} relevant items found"
2177
+
2178
+ return {
2179
+ "question": query_text,
2180
+ "answer": answer,
2181
+ "context": context,
2182
+ "search_results": len(search_results),
2183
+ "metadata": {
2184
+ "total_items_searched": len(namespace_data),
2185
+ "relevant_items_found": len(search_results),
2186
+ "context_chunks": len(context['chunks']),
2187
+ "context_entities": len(context['entities']),
2188
+ "context_documents": len(context['documents']),
2189
+ "context_tables": len(context['tables']),
2190
+ "namespace": namespace,
2191
+ "company_name": organization_name
2192
+ }
2193
+ }
2194
+
2195
+ except Exception as e:
2196
+ raise HTTPException(status_code=400, detail=str(e))
2197
+
2198
+ @app.post("/retrieval/execute")
2199
+ async def execute_retrieval_pipeline(request: dict):
2200
+ """Execute a retrieval pipeline with the 5-stage process."""
2201
+ import json
2202
+ import os
2203
+ from datetime import datetime
2204
+
2205
+ try:
2206
+ query = request.get("query", "")
2207
+ namespace = request.get("namespace", "default")
2208
+ collection = request.get("collection", "enterprise_graph")
2209
+ run_id = request.get("run_id", f"retrieval_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
2210
+
2211
+ print(f"[EMOJI] Executing Retrieval Pipeline")
2212
+ print(f"[EMOJI] Query: {query}")
2213
+ print(f"[EMOJI][EMOJI] Run ID: {run_id}")
2214
+ print(f"[EMOJI] Namespace: {namespace}")
2215
+ print(f"[EMOJI][EMOJI] Collection: {collection}")
2216
+
2217
+ # Load data from namespace
2218
+ namespace_data = []
2219
+ namespace_dir = f"contextcore_data/namespaces/{namespace}/nodes"
2220
+
2221
+ if os.path.exists(namespace_dir):
2222
+ for node_type in os.listdir(namespace_dir):
2223
+ node_type_dir = os.path.join(namespace_dir, node_type)
2224
+ if os.path.isdir(node_type_dir):
2225
+ for node_file in os.listdir(node_type_dir):
2226
+ if node_file.endswith('.json'):
2227
+ node_path = os.path.join(node_type_dir, node_file)
2228
+ try:
2229
+ with open(node_path, 'r') as f:
2230
+ node_data = json.load(f)
2231
+ node_data['node_type'] = node_type
2232
+ namespace_data.append(node_data)
2233
+ except Exception as e:
2234
+ continue
2235
+
2236
+ # Stage 1: RETRIEVE
2237
+ print("[EMOJI] Stage 1: RETRIEVE")
2238
+ query_lower = query.lower()
2239
+ retrieved_items = []
2240
+
2241
+ for node in namespace_data:
2242
+ node_type = node.get('node_type', '').upper()
2243
+ if node_type in ['ENTITY', 'RELATIONSHIP', 'TABLE', 'IMAGE', 'CHUNK']:
2244
+ node_text = str(node).lower()
2245
+ score = 0
2246
+ query_words = query_lower.split()
2247
+ for word in query_words:
2248
+ if word in node_text:
2249
+ score += node_text.count(word)
2250
+
2251
+ if score > 0:
2252
+ retrieved_items.append({
2253
+ 'node': node,
2254
+ 'score': score,
2255
+ 'type': node_type,
2256
+ 'retrieval_method': 'hybrid'
2257
+ })
2258
+
2259
+ retrieved_items.sort(key=lambda x: x['score'], reverse=True)
2260
+ retrieved_items = retrieved_items[:20]
2261
+
2262
+ # Stage 2: CONTEXT
2263
+ print("[EMOJI] Stage 2: CONTEXT")
2264
+ context = {
2265
+ 'chunks': [],
2266
+ 'entities': [],
2267
+ 'tables': [],
2268
+ 'images': [],
2269
+ 'relationships': []
2270
+ }
2271
+
2272
+ window_size = 3500
2273
+ current_size = 0
2274
+
2275
+ for item in retrieved_items:
2276
+ node = item['node']
2277
+ node_type = node.get('node_type', '').upper()
2278
+
2279
+ if current_size >= window_size:
2280
+ break
2281
+
2282
+ if node_type == 'CHUNK' or 'text' in node:
2283
+ chunk_text = node.get('text', '')
2284
+ if chunk_text and current_size + len(chunk_text) <= window_size:
2285
+ context['chunks'].append({
2286
+ 'id': node.get('id'),
2287
+ 'text': chunk_text,
2288
+ 'chunk_type': node.get('chunk_type', node_type.lower()),
2289
+ 'score': item['score']
2290
+ })
2291
+ current_size += len(chunk_text)
2292
+
2293
+ elif node_type == 'ENTITY':
2294
+ context['entities'].append({
2295
+ 'id': node.get('id'),
2296
+ 'name': node.get('name', ''),
2297
+ 'type': node.get('type', ''),
2298
+ 'confidence': node.get('confidence', 0),
2299
+ 'score': item['score']
2300
+ })
2301
+
2302
+ elif node_type == 'TABLE':
2303
+ context['tables'].append({
2304
+ 'id': node.get('id'),
2305
+ 'table_type': node.get('table_type', ''),
2306
+ 'data': node.get('data', {}),
2307
+ 'score': item['score']
2308
+ })
2309
+
2310
+ # Stage 3: REASON
2311
+ print("[EMOJI] Stage 3: REASON")
2312
+ chunks_text = "\n".join([chunk['text'] for chunk in context['chunks']])
2313
+ entities_text = ", ".join([f"{entity['name']} ({entity['type']})" for entity in context['entities']])
2314
+
2315
+ # Generate answer based on query type
2316
+ if 'subsidiaries' in query_lower and 'europe' in query_lower:
2317
+ answer = f"Based on the available data, here's what I found about subsidiaries in Europe:\n\n"
2318
+ answer += f"European operations contribute significantly to the business. "
2319
+ answer += f"Key European markets include major cities across the continent. "
2320
+ answer += f"The company serves clients in banking, financial services, and other industries.\n\n"
2321
+ answer += f"Context Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2322
+
2323
+ elif 'financial' in query_lower:
2324
+ answer = f"Financial Performance Summary:\n\n"
2325
+ answer += f"Revenue growth and operating margins show strong performance. "
2326
+ answer += f"Geographic distribution includes multiple markets worldwide.\n\n"
2327
+ answer += f"Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2328
+
2329
+ elif 'employee' in query_lower or 'workforce' in query_lower:
2330
+ answer = f"Employee Metrics:\n\n"
2331
+ answer += f"Workforce includes thousands of professionals across multiple countries. "
2332
+ answer += f"Diversity and inclusion are key priorities.\n\n"
2333
+ answer += f"Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2334
+
2335
+ else:
2336
+ answer = f"Based on the available data:\n\n"
2337
+ answer += f"Relevant Information: {chunks_text[:500]}...\n\n"
2338
+ answer += f"Key Entities: {entities_text}\n\n"
2339
+ answer += f"Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2340
+
2341
+ # Stage 4: VERIFY
2342
+ print("[EMOJI] Stage 4: VERIFY")
2343
+ context_text = chunks_text.lower()
2344
+ answer_lower = answer.lower()
2345
+
2346
+ context_words = set(context_text.split())
2347
+ answer_words = set(answer_lower.split())
2348
+
2349
+ overlap = len(context_words.intersection(answer_words))
2350
+ total_context_words = len(context_words)
2351
+
2352
+ verification_score = overlap / total_context_words if total_context_words > 0 else 0
2353
+
2354
+ verification = {
2355
+ 'score': verification_score,
2356
+ 'overlap_words': overlap,
2357
+ 'total_context_words': total_context_words,
2358
+ 'verification_method': 'verifier_bge',
2359
+ 'is_grounded': verification_score > 0.1
2360
+ }
2361
+
2362
+ # Stage 5: EVALUATE
2363
+ print("[EMOJI] Stage 5: EVALUATE")
2364
+ metrics = ['faithfulness', 'context_precision', 'recall@5', 'hallucination_rate']
2365
+
2366
+ evaluation = {
2367
+ 'metrics': {
2368
+ 'faithfulness': verification_score,
2369
+ 'context_precision': min(len(context['chunks']) / 10.0, 1.0),
2370
+ 'recall@5': min(len(context['chunks']) / 5.0, 1.0),
2371
+ 'hallucination_rate': 1.0 - verification_score
2372
+ },
2373
+ 'overall_score': 0,
2374
+ 'recommendations': []
2375
+ }
2376
+
2377
+ scores = list(evaluation['metrics'].values())
2378
+ evaluation['overall_score'] = sum(scores) / len(scores) if scores else 0
2379
+
2380
+ if evaluation['overall_score'] < 0.7:
2381
+ evaluation['recommendations'].append("Consider expanding context window")
2382
+ if evaluation['metrics']['hallucination_rate'] > 0.3:
2383
+ evaluation['recommendations'].append("Improve answer grounding")
2384
+
2385
+ print("[EMOJI] Retrieval Pipeline completed")
2386
+
2387
+ return {
2388
+ "query": query,
2389
+ "run_id": run_id,
2390
+ "namespace": namespace,
2391
+ "collection": collection,
2392
+ "stages": [
2393
+ {
2394
+ "stage": "RETRIEVE",
2395
+ "strategy": "HYBRID_GRAPH",
2396
+ "results": len(retrieved_items),
2397
+ "count": len(retrieved_items)
2398
+ },
2399
+ {
2400
+ "stage": "CONTEXT",
2401
+ "context": context,
2402
+ "window_size": window_size,
2403
+ "mode": "semantic_coherence"
2404
+ },
2405
+ {
2406
+ "stage": "REASON",
2407
+ "answer": answer,
2408
+ "model": "reasoner_gpt",
2409
+ "instruction": "Answer the question using only retrieved context."
2410
+ },
2411
+ {
2412
+ "stage": "VERIFY",
2413
+ "verification": verification,
2414
+ "verifier": "verifier_bge"
2415
+ },
2416
+ {
2417
+ "stage": "EVALUATE",
2418
+ "evaluation": evaluation,
2419
+ "metrics": metrics
2420
+ }
2421
+ ],
2422
+ "final_answer": answer,
2423
+ "evaluation": evaluation,
2424
+ "metadata": {
2425
+ "start_time": datetime.now().isoformat(),
2426
+ "end_time": datetime.now().isoformat(),
2427
+ "total_stages": 5,
2428
+ "total_items_searched": len(namespace_data),
2429
+ "relevant_items_found": len(retrieved_items)
2430
+ }
2431
+ }
2432
+
2433
+ except Exception as e:
2434
+ raise HTTPException(status_code=400, detail=str(e))
2435
+
2436
+ @app.post("/pipeline/create")
2437
+ async def create_retrieval_pipeline(request: dict):
2438
+ """Create a retrieval pipeline (reusable query plan)."""
2439
+ try:
2440
+ pipeline_name = request.get("pipeline_name", "")
2441
+ namespace = request.get("namespace", "default")
2442
+ collection = request.get("collection", "default")
2443
+ description = request.get("description", "")
2444
+ stages = request.get("stages", [])
2445
+
2446
+ print(f"[EMOJI] Creating Retrieval Pipeline: {pipeline_name}")
2447
+ print(f"[EMOJI] Namespace: {namespace}")
2448
+ print(f"[EMOJI][EMOJI] Collection: {collection}")
2449
+ print(f"[EMOJI] Description: {description}")
2450
+ print(f"[EMOJI] Stages: {len(stages)}")
2451
+
2452
+ # Create pipeline configuration
2453
+ pipeline_config = {
2454
+ 'pipeline_name': pipeline_name,
2455
+ 'namespace': namespace,
2456
+ 'collection': collection,
2457
+ 'description': description,
2458
+ 'stages': stages,
2459
+ 'created_at': datetime.now().isoformat(),
2460
+ 'status': 'created',
2461
+ 'type': 'retrieval',
2462
+ 'execution_count': 0
2463
+ }
2464
+
2465
+ # Store pipeline configuration
2466
+ pipeline_dir = f"contextcore_data/namespaces/{namespace}/retrieval_pipelines/{pipeline_name}"
2467
+ os.makedirs(pipeline_dir, exist_ok=True)
2468
+
2469
+ config_file = os.path.join(pipeline_dir, "retrieval_pipeline_config.json")
2470
+ with open(config_file, 'w') as f:
2471
+ json.dump(pipeline_config, f, indent=2)
2472
+
2473
+ print(f"[EMOJI] Retrieval pipeline created successfully: {pipeline_name}")
2474
+
2475
+ return {
2476
+ "success": True,
2477
+ "message": f"Pipeline '{pipeline_name}' created successfully",
2478
+ "pipeline_config": pipeline_config
2479
+ }
2480
+
2481
+ except Exception as e:
2482
+ raise HTTPException(status_code=400, detail=str(e))
2483
+
2484
+ @app.post("/pipeline/run")
2485
+ async def run_retrieval_pipeline(request: dict):
2486
+ """Run a retrieval pipeline with query injection."""
2487
+ try:
2488
+ query = request.get("query", "")
2489
+ pipeline_name = request.get("pipeline_name", "")
2490
+ run_id = request.get("run_id", f"retrieval_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
2491
+
2492
+ print(f"[EMOJI] Running Retrieval Pipeline")
2493
+ print(f"[EMOJI] Query: {query}")
2494
+ print(f"[EMOJI] Pipeline: {pipeline_name}")
2495
+ print(f"[EMOJI][EMOJI] Run ID: {run_id}")
2496
+
2497
+ # Load pipeline configuration
2498
+ pipeline_config = None
2499
+ namespace = "default"
2500
+ collection = "default"
2501
+
2502
+ if pipeline_name:
2503
+ # Look for pipeline config in all namespaces
2504
+ namespaces_dir = "contextcore_data/namespaces"
2505
+ if os.path.exists(namespaces_dir):
2506
+ for ns in os.listdir(namespaces_dir):
2507
+ ns_dir = os.path.join(namespaces_dir, ns)
2508
+ if os.path.isdir(ns_dir):
2509
+ # Check retrieval_pipelines directory
2510
+ pipelines_dir = os.path.join(ns_dir, "retrieval_pipelines")
2511
+ if os.path.exists(pipelines_dir):
2512
+ pipeline_dir = os.path.join(pipelines_dir, pipeline_name)
2513
+ if os.path.exists(pipeline_dir):
2514
+ config_file = os.path.join(pipeline_dir, "retrieval_pipeline_config.json")
2515
+ if os.path.exists(config_file):
2516
+ with open(config_file, 'r') as f:
2517
+ pipeline_config = json.load(f)
2518
+ namespace = pipeline_config.get('namespace', 'default')
2519
+ collection = pipeline_config.get('collection', 'default')
2520
+ break
2521
+
2522
+ if pipeline_config:
2523
+ print(f"[EMOJI] Loaded pipeline config: {pipeline_config.get('pipeline_name')}")
2524
+ else:
2525
+ print(f"[EMOJI][EMOJI] Pipeline '{pipeline_name}' not found, using defaults")
2526
+
2527
+ # Load data from namespace
2528
+ data = []
2529
+ namespace_dir = f"contextcore_data/namespaces/{namespace}/nodes"
2530
+
2531
+ if os.path.exists(namespace_dir):
2532
+ for node_type in os.listdir(namespace_dir):
2533
+ node_type_dir = os.path.join(namespace_dir, node_type)
2534
+ if os.path.isdir(node_type_dir):
2535
+ for node_file in os.listdir(node_type_dir):
2536
+ if node_file.endswith('.json'):
2537
+ node_path = os.path.join(node_type_dir, node_file)
2538
+ try:
2539
+ with open(node_path, 'r') as f:
2540
+ node_data = json.load(f)
2541
+ node_data['node_type'] = node_type
2542
+ data.append(node_data)
2543
+ except Exception as e:
2544
+ continue
2545
+
2546
+ # Execute 5-stage retrieval pipeline
2547
+ results = execute_retrieval_pipeline_stages(query, data, namespace, collection, run_id, pipeline_config)
2548
+
2549
+ print(f"[EMOJI] Retrieval pipeline executed successfully")
2550
+
2551
+ return results
2552
+
2553
+ except Exception as e:
2554
+ raise HTTPException(status_code=400, detail=str(e))
2555
+
2556
+ @app.post("/contextcore/run")
2557
+ async def run_pipeline_via_rest(request: dict):
2558
+ """REST API endpoint matching your specification."""
2559
+ try:
2560
+ namespace = request.get("namespace", "default")
2561
+ pipeline = request.get("pipeline", "")
2562
+ query = request.get("query", "")
2563
+ run_id = request.get("run_id", f"retrieval_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
2564
+
2565
+ print(f"[EMOJI] REST API Pipeline Execution")
2566
+ print(f"[EMOJI] Namespace: {namespace}")
2567
+ print(f"[EMOJI] Pipeline: {pipeline}")
2568
+ print(f"[EMOJI] Query: {query}")
2569
+ print(f"[EMOJI][EMOJI] Run ID: {run_id}")
2570
+
2571
+ # Use the same logic as /pipeline/run
2572
+ pipeline_request = {
2573
+ "query": query,
2574
+ "pipeline_name": pipeline,
2575
+ "run_id": run_id
2576
+ }
2577
+
2578
+ # Call the internal pipeline execution
2579
+ result = await run_retrieval_pipeline(pipeline_request)
2580
+
2581
+ return result
2582
+
2583
+ except Exception as e:
2584
+ raise HTTPException(status_code=400, detail=str(e))
2585
+
2586
+ def execute_retrieval_pipeline_stages(query: str, data: list, namespace: str, collection: str, run_id: str, pipeline_config: dict = None):
2587
+ """Execute the 5-stage retrieval pipeline."""
2588
+ from datetime import datetime
2589
+
2590
+ # Stage 1: RETRIEVE
2591
+ print("[EMOJI] Stage 1: RETRIEVE")
2592
+ retrieved_items = []
2593
+ query_lower = query.lower()
2594
+
2595
+ for node in data:
2596
+ node_type = node.get('node_type', '').upper()
2597
+ if node_type in ['ENTITY', 'RELATIONSHIP', 'TABLE', 'IMAGE', 'CHUNK']:
2598
+ node_text = str(node).lower()
2599
+ score = 0
2600
+ query_words = query_lower.split()
2601
+ for word in query_words:
2602
+ if word in node_text:
2603
+ score += node_text.count(word)
2604
+
2605
+ if score > 0:
2606
+ retrieved_items.append({
2607
+ 'node': node,
2608
+ 'score': score,
2609
+ 'type': node_type,
2610
+ 'retrieval_method': 'hybrid'
2611
+ })
2612
+
2613
+ retrieved_items.sort(key=lambda x: x['score'], reverse=True)
2614
+ retrieved_items = retrieved_items[:20]
2615
+
2616
+ # Stage 2: CONTEXT
2617
+ print("[EMOJI] Stage 2: CONTEXT")
2618
+ context = {
2619
+ 'chunks': [],
2620
+ 'entities': [],
2621
+ 'tables': [],
2622
+ 'images': [],
2623
+ 'relationships': []
2624
+ }
2625
+
2626
+ window_size = 3500
2627
+ current_size = 0
2628
+
2629
+ for item in retrieved_items:
2630
+ node = item['node']
2631
+ node_type = node.get('node_type', '').upper()
2632
+
2633
+ if current_size >= window_size:
2634
+ break
2635
+
2636
+ if node_type == 'CHUNK' or 'text' in node:
2637
+ chunk_text = node.get('text', '')
2638
+ if chunk_text and current_size + len(chunk_text) <= window_size:
2639
+ context['chunks'].append({
2640
+ 'id': node.get('id'),
2641
+ 'text': chunk_text,
2642
+ 'chunk_type': node.get('chunk_type', node_type.lower()),
2643
+ 'score': item['score']
2644
+ })
2645
+ current_size += len(chunk_text)
2646
+
2647
+ elif node_type == 'ENTITY':
2648
+ context['entities'].append({
2649
+ 'id': node.get('id'),
2650
+ 'name': node.get('name', ''),
2651
+ 'type': node.get('type', ''),
2652
+ 'confidence': node.get('confidence', 0),
2653
+ 'score': item['score']
2654
+ })
2655
+
2656
+ elif node_type == 'TABLE':
2657
+ context['tables'].append({
2658
+ 'id': node.get('id'),
2659
+ 'table_type': node.get('table_type', ''),
2660
+ 'data': node.get('data', {}),
2661
+ 'score': item['score']
2662
+ })
2663
+
2664
+ # Stage 3: REASON
2665
+ print("[EMOJI] Stage 3: REASON")
2666
+ chunks_text = "\n".join([chunk['text'] for chunk in context['chunks']])
2667
+ entities_text = ", ".join([f"{entity['name']} ({entity['type']})" for entity in context['entities']])
2668
+
2669
+ # Extract prompt from pipeline configuration if available
2670
+ prompt = None
2671
+ if pipeline_config and 'stages' in pipeline_config:
2672
+ for stage in pipeline_config['stages']:
2673
+ if stage.get('stage') == 'REASON' and 'prompt' in stage:
2674
+ prompt = stage['prompt']
2675
+ break
2676
+
2677
+ # Try to use real OpenAI LLM if available
2678
+ try:
2679
+ import openai
2680
+ import os
2681
+
2682
+ # Load environment variables from .env file if available
2683
+ try:
2684
+ env_file = Path('.env')
2685
+ if not env_file.exists():
2686
+ env_file = Path('config.env') # Legacy fallback
2687
+ with open(env_file, 'r') as f:
2688
+ for line in f:
2689
+ line = line.strip()
2690
+ if line and not line.startswith('#') and '=' in line:
2691
+ key, value = line.split('=', 1)
2692
+ os.environ[key] = value
2693
+ except:
2694
+ pass # optional
2695
+
2696
+ api_key = os.getenv('OPENAI_API_KEY')
2697
+ if api_key:
2698
+ print("[EMOJI] Using real OpenAI LLM for reasoning")
2699
+
2700
+ client = openai.OpenAI(api_key=api_key)
2701
+
2702
+ # Use custom prompt if provided, otherwise use default
2703
+ if prompt:
2704
+ print(f"[EMOJI] Using custom prompt: {prompt[:50]}...")
2705
+ context_text = f"""
2706
+ {prompt}
2707
+
2708
+ Context Information:
2709
+ {chunks_text}
2710
+
2711
+ Key Entities: {entities_text}
2712
+
2713
+ Question: {query}
2714
+ """
2715
+ else:
2716
+ # Default prompt
2717
+ context_text = f"""
2718
+ Context Information:
2719
+ {chunks_text}
2720
+
2721
+ Key Entities: {entities_text}
2722
+
2723
+ Question: {query}
2724
+
2725
+ Please answer the question using only the provided context information. Be specific and detailed in your response.
2726
+ """
2727
+
2728
+ response = client.chat.completions.create(
2729
+ model="gpt-4",
2730
+ messages=[
2731
+ {"role": "system", "content": "You are a helpful assistant that answers questions based on provided context. Only use information from the context provided."},
2732
+ {"role": "user", "content": context_text}
2733
+ ],
2734
+ max_tokens=1000,
2735
+ temperature=0.3
2736
+ )
2737
+
2738
+ answer = response.choices[0].message.content
2739
+ print("[EMOJI] Real LLM response generated")
2740
+ else:
2741
+ print("[EMOJI][EMOJI] No OpenAI API key found, using mock response")
2742
+ raise Exception("No API key")
2743
+ except Exception as e:
2744
+ print(f"[EMOJI][EMOJI] OpenAI LLM failed: {e}, using mock response")
2745
+
2746
+ # Fallback to mock response
2747
+ query_lower = query.lower()
2748
+
2749
+ # Generate answer based on query type
2750
+ if 'subsidiaries' in query_lower and 'europe' in query_lower:
2751
+ answer = f"Based on the available data, here's what I found about subsidiaries in Europe:\n\n"
2752
+ answer += f"European operations contribute significantly to the business. "
2753
+ answer += f"Key European markets include major cities across the continent. "
2754
+ answer += f"The company serves clients in banking, financial services, and other industries.\n\n"
2755
+ answer += f"Context Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2756
+
2757
+ elif 'financial' in query_lower:
2758
+ answer = f"Financial Performance Summary:\n\n"
2759
+ answer += f"Revenue growth and operating margins show strong performance. "
2760
+ answer += f"Geographic distribution includes multiple markets worldwide.\n\n"
2761
+ answer += f"Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2762
+
2763
+ elif 'employee' in query_lower or 'workforce' in query_lower:
2764
+ answer = f"Employee Metrics:\n\n"
2765
+ answer += f"Workforce includes thousands of professionals across multiple countries. "
2766
+ answer += f"Diversity and inclusion are key priorities.\n\n"
2767
+ answer += f"Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2768
+
2769
+ else:
2770
+ answer = f"Based on the available data:\n\n"
2771
+ answer += f"Relevant Information: {chunks_text[:500]}...\n\n"
2772
+ answer += f"Key Entities: {entities_text}\n\n"
2773
+ answer += f"Sources: {len(context['chunks'])} chunks, {len(context['entities'])} entities"
2774
+
2775
+ # Stage 4: VERIFY
2776
+ print("[EMOJI] Stage 4: VERIFY")
2777
+ context_text = chunks_text.lower()
2778
+ answer_lower = answer.lower()
2779
+
2780
+ context_words = set(context_text.split())
2781
+ answer_words = set(answer_lower.split())
2782
+
2783
+ overlap = len(context_words.intersection(answer_words))
2784
+ total_context_words = len(context_words)
2785
+
2786
+ verification_score = overlap / total_context_words if total_context_words > 0 else 0
2787
+
2788
+ verification = {
2789
+ 'score': verification_score,
2790
+ 'overlap_words': overlap,
2791
+ 'total_context_words': total_context_words,
2792
+ 'verification_method': 'verifier_bge',
2793
+ 'is_grounded': verification_score > 0.1
2794
+ }
2795
+
2796
+ # Stage 5: EVALUATE
2797
+ print("[EMOJI] Stage 5: EVALUATE")
2798
+ metrics = ['faithfulness', 'context_precision', 'recall@5', 'hallucination_rate']
2799
+
2800
+ evaluation = {
2801
+ 'metrics': {
2802
+ 'faithfulness': verification_score,
2803
+ 'context_precision': min(len(context['chunks']) / 10.0, 1.0),
2804
+ 'recall@5': min(len(context['chunks']) / 5.0, 1.0),
2805
+ 'hallucination_rate': 1.0 - verification_score
2806
+ },
2807
+ 'overall_score': 0,
2808
+ 'recommendations': []
2809
+ }
2810
+
2811
+ scores = list(evaluation['metrics'].values())
2812
+ evaluation['overall_score'] = sum(scores) / len(scores) if scores else 0
2813
+
2814
+ if evaluation['overall_score'] < 0.7:
2815
+ evaluation['recommendations'].append("Consider expanding context window")
2816
+ if evaluation['metrics']['hallucination_rate'] > 0.3:
2817
+ evaluation['recommendations'].append("Improve answer grounding")
2818
+
2819
+ print("[EMOJI] Retrieval Pipeline completed")
2820
+
2821
+ return {
2822
+ "query": query,
2823
+ "run_id": run_id,
2824
+ "namespace": namespace,
2825
+ "collection": collection,
2826
+ "pipeline_name": pipeline_config.get('pipeline_name') if pipeline_config else None,
2827
+ "stages": [
2828
+ {
2829
+ "stage": "RETRIEVE",
2830
+ "strategy": "HYBRID_GRAPH",
2831
+ "results": len(retrieved_items),
2832
+ "count": len(retrieved_items)
2833
+ },
2834
+ {
2835
+ "stage": "CONTEXT",
2836
+ "context": context,
2837
+ "window_size": window_size,
2838
+ "mode": "semantic_coherence"
2839
+ },
2840
+ {
2841
+ "stage": "REASON",
2842
+ "answer": answer,
2843
+ "model": "reasoner_gpt",
2844
+ "instruction": "Answer the question using only retrieved context."
2845
+ },
2846
+ {
2847
+ "stage": "VERIFY",
2848
+ "verification": verification,
2849
+ "verifier": "verifier_bge"
2850
+ },
2851
+ {
2852
+ "stage": "EVALUATE",
2853
+ "evaluation": evaluation,
2854
+ "metrics": metrics
2855
+ }
2856
+ ],
2857
+ "final_answer": answer,
2858
+ "evaluation": evaluation,
2859
+ "metadata": {
2860
+ "start_time": datetime.now().isoformat(),
2861
+ "end_time": datetime.now().isoformat(),
2862
+ "total_stages": 5,
2863
+ "total_items_searched": len(data),
2864
+ "relevant_items_found": len(retrieved_items)
2865
+ }
2866
+ }
2867
+
2868
+ @app.post("/graph/nodes")
2869
+ async def create_node(node: dict = Body(...), graph_db: QGraphDB = Depends(get_current_graph)):
2870
+ """Create a new node."""
2871
+ try:
2872
+ import traceback as tb
2873
+ # Handle string bodies (e.g. PowerShell Invoke-WebRequest)
2874
+ node = _ensure_dict(node)
2875
+
2876
+ # Manually convert dict to NodeCreate
2877
+ from pydantic import ValidationError
2878
+ try:
2879
+ node_obj = NodeCreate(**node)
2880
+ except ValidationError as ve:
2881
+ raise HTTPException(status_code=400, detail=f"NodeCreate validation error: {ve}")
2882
+ except Exception as e:
2883
+ raise HTTPException(status_code=400, detail=f"NodeCreate conversion error: {e}")
2884
+ graph_node = GraphNode(
2885
+ id=node_obj.id,
2886
+ label=node_obj.label,
2887
+ properties=node_obj.properties or {},
2888
+ name=node_obj.properties.get('name') if node_obj.properties else None
2889
+ )
2890
+ graph_db.add_node(graph_node, write_through=True)
2891
+ await auto_save_graph(graph_db)
2892
+ return {"message": f"Node '{node_obj.id}' created successfully", "id": node_obj.id}
2893
+ except HTTPException:
2894
+ raise
2895
+ except Exception as e:
2896
+ import traceback
2897
+ logger.error(f"create_node exception: {e}\n{traceback.format_exc()}")
2898
+ raise HTTPException(status_code=400, detail=str(e))
2899
+
2900
+ @app.get("/graph/nodes/{node_id}")
2901
+ async def get_node(node_id: str, graph_db: QGraphDB = Depends(get_current_graph)):
2902
+ """Get a specific node."""
2903
+ node_data = graph_db.get_node(node_id)
2904
+ if not node_data:
2905
+ raise HTTPException(status_code=404, detail="Node not found")
2906
+
2907
+ return {
2908
+ "id": node_id,
2909
+ "label": node_data.label,
2910
+ "properties": node_data.properties
2911
+ }
2912
+
2913
+ @app.delete("/graph/nodes/{node_id}")
2914
+ async def delete_node(node_id: str, graph_db: QGraphDB = Depends(get_current_graph)):
2915
+ """Delete a node."""
2916
+ try:
2917
+ # Check if node exists
2918
+ node_exists = False
2919
+ if hasattr(graph_db, 'node_index') and graph_db.node_index:
2920
+ node_exists = node_id in graph_db.node_index
2921
+
2922
+ if not node_exists:
2923
+ raise HTTPException(status_code=404, detail="Node not found")
2924
+ success = graph_db.remove_node(node_id)
2925
+ if success:
2926
+ # Clean LMDB search index so deleted node doesn't appear in search
2927
+ try:
2928
+ from ..search.lmdb_index import lmdb_delete_node
2929
+ lmdb_delete_node(graph_db.name, node_id)
2930
+ except Exception:
2931
+ pass
2932
+ return {"message": f"Node '{node_id}' deleted successfully"}
2933
+ else:
2934
+ raise HTTPException(status_code=400, detail="Failed to delete node")
2935
+ except Exception as e:
2936
+ raise HTTPException(status_code=400, detail=str(e))
2937
+
2938
+ # Edge operations
2939
+ @app.get("/graph/edges")
2940
+ async def get_edges(
2941
+ limit: int = Query(1000, ge=1, le=10000),
2942
+ offset: int = Query(0, ge=0),
2943
+ label: Optional[str] = Query(None),
2944
+ graph_db: QGraphDB = Depends(get_current_graph),
2945
+ ):
2946
+ """Get edges in the current graph with pagination."""
2947
+ raw_edges = graph_db.get_all_edges(label=label, limit=limit, offset=offset)
2948
+ edges = []
2949
+ for e in raw_edges:
2950
+ source_name = e.source
2951
+ target_name = e.target
2952
+ if hasattr(graph_db, 'get_node'):
2953
+ src_node = graph_db.get_node(e.source)
2954
+ tgt_node = graph_db.get_node(e.target)
2955
+ if src_node:
2956
+ source_name = (src_node.properties or {}).get('name') or getattr(src_node, 'name', None) or getattr(src_node, 'label', e.source)
2957
+ if tgt_node:
2958
+ target_name = (tgt_node.properties or {}).get('name') or getattr(tgt_node, 'name', None) or getattr(tgt_node, 'label', e.target)
2959
+ edges.append({
2960
+ "source": source_name,
2961
+ "target": target_name,
2962
+ "source_id": e.source,
2963
+ "target_id": e.target,
2964
+ "relationship": e.label or "",
2965
+ "properties": e.properties or {},
2966
+ "weight": (e.properties or {}).get("weight", 1.0)
2967
+ })
2968
+ return {"edges": edges, "limit": limit, "offset": offset, "count": len(edges)}
2969
+
2970
+ @app.post("/graph/edges")
2971
+ async def create_edge(edge: EdgeCreate, graph_db: QGraphDB = Depends(get_current_graph)):
2972
+ """Create a new edge."""
2973
+ try:
2974
+ success = graph_db.add_edge(edge.source, edge.target, edge.relationship, edge.properties, edge.weight)
2975
+ if success:
2976
+ # Auto-save after edge creation
2977
+ await auto_save_graph(graph_db)
2978
+ return {"message": f"Edge '{edge.source}' -> '{edge.target}' created successfully"}
2979
+ else:
2980
+ raise HTTPException(status_code=400, detail="Failed to create edge")
2981
+ except Exception as e:
2982
+ raise HTTPException(status_code=400, detail=str(e))
2983
+
2984
+ @app.delete("/graph/edges")
2985
+ async def delete_edge(source: str, target: str, graph_db: QGraphDB = Depends(get_current_graph)):
2986
+ """Delete an edge."""
2987
+ try:
2988
+ # Check if edge exists
2989
+ edge_exists = False
2990
+ if hasattr(graph_db, 'csr_storage') and graph_db.csr_storage:
2991
+ edge_exists = graph_db.csr_storage.has_edge(source, target) if hasattr(graph_db.csr_storage, 'has_edge') else False
2992
+
2993
+ if not edge_exists:
2994
+ raise HTTPException(status_code=404, detail="Edge not found")
2995
+ success = graph_db.remove_edge(source, target)
2996
+ if success:
2997
+ return {"message": f"Edge '{source}' -> '{target}' deleted successfully"}
2998
+ else:
2999
+ raise HTTPException(status_code=400, detail="Failed to delete edge")
3000
+ except Exception as e:
3001
+ raise HTTPException(status_code=400, detail=str(e))
3002
+
3003
+ # Query endpoints
3004
+ @app.post("/query/grql")
3005
+ async def execute_grql(query: QueryRequest, graph_db: QGraphDB = Depends(get_current_graph)):
3006
+ """Execute a GRQL query."""
3007
+ import logging
3008
+ logger = logging.getLogger(__name__)
3009
+
3010
+ try:
3011
+ # Use the requested graph_name if provided, otherwise fall back to current_graph
3012
+ if query.graph_name:
3013
+ graph_db = graph_registry.get_graph(query.graph_name, load_if_missing=True)
3014
+ if not graph_db:
3015
+ graph_db = graph_registry.create_graph(query.graph_name)
3016
+
3017
+ logger.info(f"Executing QGRAQL query: {query.query[:100]}")
3018
+
3019
+ # Pool executors per graph to avoid expensive re-init on every request
3020
+ if not hasattr(app.state, 'grql_executor_pool'):
3021
+ app.state.grql_executor_pool = {}
3022
+
3023
+ graph_key = graph_db.name or 'default'
3024
+ if graph_key in app.state.grql_executor_pool:
3025
+ executor = app.state.grql_executor_pool[graph_key]
3026
+ # Update graph reference in case it changed
3027
+ executor.contextcore = graph_db
3028
+ else:
3029
+ executor = AIQLExecutor(contextcore=graph_db, graph_registry=graph_registry)
3030
+ app.state.grql_executor_pool[graph_key] = executor
3031
+
3032
+ # Ensure executor's namespace matches the requested graph
3033
+ executor.active_namespace = graph_key
3034
+
3035
+ result = executor.execute(query.query)
3036
+
3037
+ # UNIFIED FORMAT: Extract nodes and edges using unified format
3038
+ # The executor now returns results in format: {"nodes": [...], "edges": [...], "data": {...}, ...}
3039
+ nodes = []
3040
+ edges = []
3041
+ metadata = {}
3042
+
3043
+ if isinstance(result, dict):
3044
+ # Standard format from new executor methods
3045
+ nodes = result.get('nodes', [])
3046
+ edges = result.get('edges', [])
3047
+ metadata = result.get('data', {})
3048
+
3049
+ # Fallback for legacy formats or edge cases
3050
+ if not nodes and not edges:
3051
+ # Try alternative data structures
3052
+ data = result.get('data', {})
3053
+ if isinstance(data, dict):
3054
+ nodes = data.get('nodes', [])
3055
+ edges = data.get('edges', [])
3056
+
3057
+ # Final fallback for legacy format
3058
+ if not nodes:
3059
+ nodes = result.get('nodes', []) if 'nodes' in result else []
3060
+ if not edges:
3061
+ edges = result.get('edges', []) if 'edges' in result else []
3062
+ elif isinstance(result, list):
3063
+ # SELECT queries might return lists directly (legacy format)
3064
+ # Treat list items as nodes
3065
+ nodes = result
3066
+
3067
+ # Log failures at warning level so they show up in logs
3068
+ if isinstance(result, dict) and not result.get('success', True):
3069
+ err_msg = result.get('message') or result.get('error', 'unknown')
3070
+ logger.warning(f"Query failed: {err_msg}")
3071
+ else:
3072
+ logger.debug(f"Query result: {len(nodes)} nodes, {len(edges)} edges")
3073
+
3074
+ # Save after mutation queries
3075
+ query_upper = query.query.upper()
3076
+ is_modifying_query = any(keyword in query_upper for keyword in ['CREATE', 'UPDATE', 'DELETE'])
3077
+
3078
+ is_success = result.get('success', True) if isinstance(result, dict) else True
3079
+
3080
+ if is_modifying_query and is_success:
3081
+ # Only save + return full graph on SUCCESSFUL mutations
3082
+ try:
3083
+ graph_registry.save_graph(graph_key, create_checkpoint=False)
3084
+ except Exception as e:
3085
+ logger.warning(f"Failed to save graph after mutation: {e}")
3086
+
3087
+ # Return the FULL graph so the UI shows everything
3088
+ reg_graph = graph_registry.get_graph(graph_key)
3089
+ all_nodes = reg_graph.get_all_nodes()
3090
+ all_edges = reg_graph.get_all_edges() if hasattr(reg_graph, 'get_all_edges') else []
3091
+ logger.info(f"[MUTATION OK] graph_db={id(graph_db)}, reg_graph={id(reg_graph)}, executor={id(executor.contextcore)} | {len(all_nodes)} nodes, {len(all_edges)} edges")
3092
+ nodes = [executor._format_node_for_display(n) for n in all_nodes]
3093
+ edges = [executor._format_edge_for_display(e) for e in all_edges]
3094
+ else:
3095
+ logger.debug(f"Read-only query executed, skipping auto-save")
3096
+
3097
+ # Convert result to dict for JSON serialization using unified format
3098
+ result_dict = {
3099
+ "nodes": nodes,
3100
+ "edges": edges,
3101
+ "metadata": result.get('metadata', {}) if isinstance(result, dict) else {},
3102
+ "execution_time": result.get('metadata', {}).get('execution_time_ms', 0) / 1000.0 if isinstance(result, dict) else 0,
3103
+ "data": result.get('data', {}) if isinstance(result, dict) else {},
3104
+ "success": result.get('success', True) if isinstance(result, dict) else True,
3105
+ "message": (result.get('message') or result.get('error', '')) if isinstance(result, dict) else ''
3106
+ }
3107
+
3108
+ logger.info(f"[RESPONSE] {len(result_dict['nodes'])} nodes, {len(result_dict['edges'])} edges, success={result_dict['success']}")
3109
+ if result_dict['edges']:
3110
+ for e in result_dict['edges'][:3]:
3111
+ logger.info(f" edge: {e.get('label')} src={str(e.get('source',''))[:8]} tgt={str(e.get('target',''))[:8]}")
3112
+ if result_dict['nodes']:
3113
+ for n in result_dict['nodes'][:5]:
3114
+ logger.info(f" node: {n.get('label')} id={str(n.get('id',''))[:8]} name={n.get('name')}")
3115
+
3116
+ return {"result": result_dict}
3117
+ except ValueError as e:
3118
+ error_message = str(e)
3119
+ logger.error(f"Query failed: {error_message}")
3120
+
3121
+ # Check for specific error types and provide structured responses
3122
+ if "DUPLICATE NODE" in error_message:
3123
+ # Extract information from the error message
3124
+ if "email" in error_message.lower():
3125
+ raise HTTPException(
3126
+ status_code=409, # Conflict
3127
+ detail={
3128
+ "error": "DUPLICATE_NODE",
3129
+ "error_type": "duplicate_node",
3130
+ "message": error_message,
3131
+ "details": {
3132
+ "node_type": "Person",
3133
+ "duplicate_field": "email",
3134
+ "suggestion": "Use UPDATE to modify existing node or CREATE with different email"
3135
+ }
3136
+ }
3137
+ )
3138
+ else:
3139
+ raise HTTPException(
3140
+ status_code=409, # Conflict
3141
+ detail={
3142
+ "error": "DUPLICATE_NODE",
3143
+ "error_type": "duplicate_node",
3144
+ "message": error_message,
3145
+ "details": {
3146
+ "suggestion": "Use UPDATE to modify existing node or CREATE with different properties"
3147
+ }
3148
+ }
3149
+ )
3150
+ elif "Edge" in error_message and ("already exists" in error_message or "violates unique constraints" in error_message):
3151
+ raise HTTPException(
3152
+ status_code=409, # Conflict
3153
+ detail={
3154
+ "error": "DUPLICATE_EDGE",
3155
+ "error_type": "duplicate_edge",
3156
+ "message": error_message,
3157
+ "details": {
3158
+ "suggestion": "Use UPDATE to modify existing edge or CREATE with different properties"
3159
+ }
3160
+ }
3161
+ )
3162
+ else:
3163
+ raise HTTPException(status_code=400, detail=error_message)
3164
+ except Exception as e:
3165
+ logger.error(f"[EMOJI] Query failed: {str(e)}")
3166
+ logger.error(f"[EMOJI] Query was: {query.query}")
3167
+ raise HTTPException(status_code=400, detail=str(e))
3168
+
3169
+ @app.post("/query/qgraql")
3170
+ async def execute_qgraql(query: QueryRequest, graph_db: QGraphDB = Depends(get_current_graph)):
3171
+ """Execute a QGRAQL query."""
3172
+ if not QGRAQL_AVAILABLE:
3173
+ raise HTTPException(status_code=501, detail="QGRAQL not available")
3174
+
3175
+ try:
3176
+ config = QGRAQLConfig()
3177
+ engine = QGRAQLEngine(graph_db, config)
3178
+ result = await engine.execute(query.query)
3179
+ return {"result": result}
3180
+ except Exception as e:
3181
+ raise HTTPException(status_code=400, detail=str(e))
3182
+
3183
+ # Search endpoints
3184
+ @app.post("/search")
3185
+ async def search(search_req: SearchRequest, graph_db: QGraphDB = Depends(get_current_graph)):
3186
+ """Perform hybrid search."""
3187
+ try:
3188
+ if ENHANCED_SEARCH_AVAILABLE:
3189
+ config = EnhancedSearchConfig()
3190
+ search_engine = EnhancedSearch(graph_db, config)
3191
+ # Call search without limit parameter, then apply limit to results
3192
+ results = search_engine.search(search_req.query, target=search_req.target)
3193
+ # Apply limit to results if specified
3194
+ if search_req.limit and len(results) > search_req.limit:
3195
+ results = results[:search_req.limit]
3196
+ else:
3197
+ # Fallback to basic search using AIQL (sanitized to prevent injection)
3198
+ import re
3199
+ sanitized = re.sub(r"['\";\\]", "", search_req.query)[:200]
3200
+ search_query = f"RETRIEVE nodes WHERE content CONTAINS '{sanitized}'"
3201
+ executor = AIQLExecutor(contextcore=graph_db)
3202
+ result = executor.execute(search_query)
3203
+
3204
+ # UNIFIED FORMAT: Extract nodes using unified format
3205
+ nodes = []
3206
+ if isinstance(result, dict):
3207
+ data = result.get('data', {})
3208
+ if isinstance(data, dict):
3209
+ nodes = data.get('nodes', [])
3210
+ else:
3211
+ # Fallback: check results structure
3212
+ results_dict = result.get('results', {})
3213
+ if isinstance(results_dict, dict):
3214
+ nodes = results_dict.get('nodes', [])
3215
+ # Fallback for legacy format
3216
+ nodes = result.get('nodes', []) if not nodes else nodes
3217
+
3218
+ results = []
3219
+ for node in nodes:
3220
+ if isinstance(node, dict):
3221
+ results.append({
3222
+ "id": node.get('id', ''),
3223
+ "type": node.get('type', ''),
3224
+ "content": node.get('content', ''),
3225
+ "score": 1.0 # Simple scoring
3226
+ })
3227
+
3228
+ return {"results": results}
3229
+ except Exception as e:
3230
+ raise HTTPException(status_code=400, detail=str(e))
3231
+
3232
+ # Statistics endpoint
3233
+ @app.get("/stats")
3234
+ async def get_stats(graph_db: QGraphDB = Depends(get_current_graph), _admin=Depends(AdminAuth())):
3235
+ """Get comprehensive graph statistics."""
3236
+ try:
3237
+ # Basic graph metrics using CSR storage
3238
+ nodes = 0
3239
+ edges = 0
3240
+ if hasattr(graph_db, 'csr_storage') and graph_db.csr_storage:
3241
+ nodes = graph_db.csr_storage.get_node_count() if hasattr(graph_db.csr_storage, 'get_node_count') else 0
3242
+ edges = graph_db.csr_storage.get_edge_count() if hasattr(graph_db.csr_storage, 'get_edge_count') else 0
3243
+ elif hasattr(graph_db, 'node_index'):
3244
+ nodes = len(graph_db.node_index) if graph_db.node_index else 0
3245
+
3246
+ # Node degree distribution
3247
+ degrees = []
3248
+ if hasattr(graph_db, 'node_index') and graph_db.node_index:
3249
+ for node_id in list(graph_db.node_index.keys())[:1000]: # Sample first 1000 nodes for performance
3250
+ if hasattr(graph_db, 'csr_storage') and graph_db.csr_storage:
3251
+ degree = graph_db.csr_storage.get_node_degree(node_id) if hasattr(graph_db.csr_storage, 'get_node_degree') else 0
3252
+ degrees.append(degree)
3253
+ avg_degree = sum(degrees) / len(degrees) if degrees else 0
3254
+
3255
+ # Connected components
3256
+ try:
3257
+ # Use CSR storage methods instead of .graph
3258
+ if hasattr(graph_db, 'csr_storage') and graph_db.csr_storage:
3259
+ # For CSR storage, we can't easily compute connected components
3260
+ # Return basic metrics instead
3261
+ num_components = 1
3262
+ is_connected = True
3263
+ elif hasattr(graph_db, 'graph') and graph_db.graph:
3264
+ num_components = nx.number_weakly_connected_components(graph_db.graph)
3265
+ is_connected = nx.is_weakly_connected(graph_db.graph)
3266
+ else:
3267
+ num_components = 1
3268
+ is_connected = True
3269
+ except:
3270
+ num_components = 1
3271
+ is_connected = True
3272
+
3273
+ # Graph density
3274
+ try:
3275
+ if hasattr(graph_db, 'graph') and graph_db.graph:
3276
+ density = nx.density(graph_db.graph) if nodes > 1 else 0
3277
+ else:
3278
+ # For CSR storage, calculate density manually
3279
+ density = (2 * edges) / (nodes * (nodes - 1)) if nodes > 1 else 0
3280
+ except:
3281
+ density = 0
3282
+
3283
+ return {
3284
+ "basic_stats": {
3285
+ "nodes": nodes,
3286
+ "edges": edges,
3287
+ "density": density,
3288
+ "avg_degree": avg_degree,
3289
+ "connected_components": num_components,
3290
+ "is_connected": is_connected
3291
+ },
3292
+ "degree_distribution": {
3293
+ "min_degree": min(degrees) if degrees else 0,
3294
+ "max_degree": max(degrees) if degrees else 0,
3295
+ "avg_degree": avg_degree
3296
+ },
3297
+ "features": {
3298
+ "qgraql": QGRAQL_AVAILABLE,
3299
+ "enhanced_search": ENHANCED_SEARCH_AVAILABLE,
3300
+ "wal": WAL_AVAILABLE,
3301
+ "llm": LLM_AVAILABLE
3302
+ }
3303
+ }
3304
+ except Exception as e:
3305
+ raise HTTPException(status_code=500, detail=str(e))
3306
+
3307
+ # WAL endpoints (if available)
3308
+ if WAL_AVAILABLE:
3309
+ @app.post("/wal/transaction/begin")
3310
+ async def begin_transaction(graph_db: QGraphDB = Depends(get_current_graph)):
3311
+ """Begin a new transaction."""
3312
+ try:
3313
+ if not hasattr(graph_db, 'wal_manager') or graph_db.wal_manager is None:
3314
+ wal_config = WALConfig()
3315
+ graph_db.wal_manager = WALManager(graph_db, wal_config)
3316
+
3317
+ transaction_id = graph_db.wal_manager.begin_transaction()
3318
+ return {"transaction_id": transaction_id, "message": "Transaction started"}
3319
+ except Exception as e:
3320
+ raise HTTPException(status_code=400, detail=str(e))
3321
+
3322
+ @app.post("/wal/transaction/{transaction_id}/commit")
3323
+ async def commit_transaction(transaction_id: str, graph_db: QGraphDB = Depends(get_current_graph)):
3324
+ """Commit a transaction."""
3325
+ try:
3326
+ if not hasattr(graph_db, 'wal_manager') or graph_db.wal_manager is None:
3327
+ raise HTTPException(status_code=400, detail="WAL not initialized")
3328
+
3329
+ success = graph_db.wal_manager.commit_transaction(transaction_id)
3330
+ if success:
3331
+ return {"message": "Transaction committed successfully"}
3332
+ else:
3333
+ raise HTTPException(status_code=400, detail="Failed to commit transaction")
3334
+ except Exception as e:
3335
+ raise HTTPException(status_code=400, detail=str(e))
3336
+
3337
+ @app.post("/wal/transaction/{transaction_id}/rollback")
3338
+ async def rollback_transaction(transaction_id: str, graph_db: QGraphDB = Depends(get_current_graph)):
3339
+ """Rollback a transaction."""
3340
+ try:
3341
+ if not hasattr(graph_db, 'wal_manager') or graph_db.wal_manager is None:
3342
+ raise HTTPException(status_code=400, detail="WAL not initialized")
3343
+
3344
+ success = graph_db.wal_manager.rollback_transaction(transaction_id)
3345
+ if success:
3346
+ return {"message": "Transaction rolled back successfully"}
3347
+ else:
3348
+ raise HTTPException(status_code=400, detail="Failed to rollback transaction")
3349
+ except Exception as e:
3350
+ raise HTTPException(status_code=400, detail=str(e))
3351
+
3352
+ # LLM endpoints (if available)
3353
+ if LLM_AVAILABLE:
3354
+ @app.post("/llm/embed")
3355
+ async def embed_text(texts: List[str]):
3356
+ """Generate embeddings for text."""
3357
+ try:
3358
+ embedding_service = LocalEmbeddingService()
3359
+ embeddings = embedding_service.embed_texts(texts)
3360
+ return {"embeddings": [emb.tolist() for emb in embeddings]}
3361
+ except Exception as e:
3362
+ raise HTTPException(status_code=400, detail=str(e))
3363
+
3364
+ # Custom exception handler for duplicate errors
3365
+ @app.exception_handler(HTTPException)
3366
+ async def duplicate_error_handler(request: Request, exc: HTTPException):
3367
+ """Custom handler for duplicate node/edge errors."""
3368
+ if exc.status_code == 409 and isinstance(exc.detail, dict):
3369
+ return JSONResponse(
3370
+ status_code=exc.status_code,
3371
+ content=exc.detail
3372
+ )
3373
+ return JSONResponse(
3374
+ status_code=exc.status_code,
3375
+ content={"detail": exc.detail}
3376
+ )
3377
+
3378
+ # Stock universe endpoints — DB-backed TICKERS management
3379
+ @app.get("/pms/universe")
3380
+ async def pms_universe_list(active_only: bool = True):
3381
+ """List all tracked stocks from the StockRegistry DB."""
3382
+ try:
3383
+ from plugins.stock_analysis.stock_registry import get_registry
3384
+ except ImportError:
3385
+ return JSONResponse({"error": "stock_analysis plugin not installed"}, status_code=501)
3386
+ return {"stocks": get_registry().list_all(active_only=active_only)}
3387
+
3388
+ @app.post("/pms/universe")
3389
+ async def pms_universe_add(request: Request):
3390
+ """Add a new stock to the tracked universe."""
3391
+ try:
3392
+ from plugins.stock_analysis.stock_registry import get_registry
3393
+ except ImportError:
3394
+ return JSONResponse({"error": "stock_analysis plugin not installed"}, status_code=501)
3395
+ body = await request.json()
3396
+ name = body.get("name", "").strip()
3397
+ ticker = body.get("ticker", "").strip()
3398
+ if not name or not ticker:
3399
+ raise HTTPException(status_code=400, detail="name and ticker are required")
3400
+ try:
3401
+ stock = get_registry().add(
3402
+ name=name, ticker=ticker,
3403
+ exchange=body.get("exchange", "NSE"),
3404
+ sector=body.get("sector", "Unknown"),
3405
+ bse_code=body.get("bse_code", ""),
3406
+ description=body.get("description", ""),
3407
+ ir_url=body.get("ir_url", ""),
3408
+ )
3409
+ except ValueError as e:
3410
+ raise HTTPException(status_code=409, detail=str(e))
3411
+ return {"status": "added", "stock": stock}
3412
+
3413
+ @app.put("/pms/universe/{stock_name}")
3414
+ async def pms_universe_update(stock_name: str, request: Request):
3415
+ """Update a tracked stock."""
3416
+ try:
3417
+ from plugins.stock_analysis.stock_registry import get_registry
3418
+ except ImportError:
3419
+ return JSONResponse({"error": "stock_analysis plugin not installed"}, status_code=501)
3420
+ body = await request.json()
3421
+ stock = get_registry().update(stock_name, **body)
3422
+ if not stock:
3423
+ raise HTTPException(status_code=404, detail=f"Stock '{stock_name}' not found")
3424
+ return {"status": "updated", "stock": stock}
3425
+
3426
+ @app.delete("/pms/universe/{stock_name}")
3427
+ async def pms_universe_delete(stock_name: str):
3428
+ """Remove a tracked stock."""
3429
+ try:
3430
+ from plugins.stock_analysis.stock_registry import get_registry
3431
+ except ImportError:
3432
+ return JSONResponse({"error": "stock_analysis plugin not installed"}, status_code=501)
3433
+ deleted = get_registry().remove(stock_name)
3434
+ if not deleted:
3435
+ raise HTTPException(status_code=404, detail=f"Stock '{stock_name}' not found")
3436
+ return {"status": "deleted", "name": stock_name}
3437
+
3438
+ # Error handlers
3439
+ @app.exception_handler(404)
3440
+ async def not_found_handler(request: Request, exc: HTTPException):
3441
+ return JSONResponse(
3442
+ status_code=404,
3443
+ content={"error": "Not Found", "message": "The requested resource was not found"}
3444
+ )
3445
+
3446
+ @app.exception_handler(500)
3447
+ async def internal_error_handler(request: Request, exc):
3448
+ import traceback as _tb
3449
+ detail = str(exc) if exc else "Unknown"
3450
+ body = {"error": "Internal Server Error", "message": detail}
3451
+ if os.environ.get("CONTEXTSYNAPSE_DEBUG") or os.environ.get("AICONTEXTDB_DEBUG", "").lower() in ("true", "1"):
3452
+ body["traceback"] = _tb.format_exc()
3453
+ logger.error("500 error: %s", detail, exc_info=True)
3454
+ return JSONResponse(status_code=500, content=body)
3455
+
3456
+ # Transaction endpoints
3457
+ @app.post("/transactions")
3458
+ async def begin_transaction(graph_db: QGraphDB = Depends(get_current_graph)):
3459
+ """Begin a new transaction."""
3460
+ try:
3461
+ transaction_id = f"tx_{int(time.time())}"
3462
+ # Store transaction state (simplified implementation)
3463
+ return {"transaction_id": transaction_id, "status": "started"}
3464
+ except Exception as e:
3465
+ raise HTTPException(status_code=400, detail=str(e))
3466
+
3467
+ @app.post("/transactions/{transaction_id}/commit")
3468
+ async def commit_transaction(transaction_id: str, graph_db: QGraphDB = Depends(get_current_graph)):
3469
+ """Commit a transaction."""
3470
+ try:
3471
+ # Commit transaction (simplified implementation)
3472
+ return {"transaction_id": transaction_id, "status": "committed"}
3473
+ except Exception as e:
3474
+ raise HTTPException(status_code=400, detail=str(e))
3475
+
3476
+ @app.post("/transactions/{transaction_id}/rollback")
3477
+ async def rollback_transaction(transaction_id: str, graph_db: QGraphDB = Depends(get_current_graph)):
3478
+ """Rollback a transaction."""
3479
+ try:
3480
+ # Rollback transaction (simplified implementation)
3481
+ return {"transaction_id": transaction_id, "status": "rolled_back"}
3482
+ except Exception as e:
3483
+ raise HTTPException(status_code=400, detail=str(e))
3484
+
3485
+ # AIQL API Endpoints
3486
+ @app.post("/api/v1/data/{namespace}/query")
3487
+ async def execute_aiql_query(namespace: str, query: dict, graph_db: QGraphDB = Depends(get_current_graph)):
3488
+ """Execute AIQL query for a specific namespace."""
3489
+ try:
3490
+ query = _ensure_dict(query)
3491
+ query_text = query.get("query", "")
3492
+ if not query_text:
3493
+ raise HTTPException(status_code=400, detail="Query text is required")
3494
+
3495
+ # Initialize AIQL executor
3496
+ executor = AIQLExecutor()
3497
+
3498
+ # Execute the query
3499
+ result = executor.execute(query_text)
3500
+
3501
+ # UNIFIED FORMAT: Extract nodes and edges using unified format
3502
+ nodes = []
3503
+ edges = []
3504
+ if isinstance(result, dict):
3505
+ data = result.get('data', {})
3506
+ if isinstance(data, dict):
3507
+ nodes = data.get('nodes', [])
3508
+ edges = data.get('edges', [])
3509
+ else:
3510
+ # Fallback: check results structure
3511
+ results = result.get('results', {})
3512
+ if isinstance(results, dict):
3513
+ nodes = results.get('nodes', [])
3514
+ edges = results.get('edges', [])
3515
+ # Fallback for legacy format
3516
+ nodes = result.get('nodes', []) if not nodes else nodes
3517
+ edges = result.get('edges', []) if not edges else edges
3518
+
3519
+ return {
3520
+ "success": result.get("success", False) if isinstance(result, dict) else False,
3521
+ "data": result.get("data", {}) if isinstance(result, dict) else {},
3522
+ "nodes": nodes,
3523
+ "edges": edges,
3524
+ "error": result.get("error") if isinstance(result, dict) else None,
3525
+ "metadata": {
3526
+ "namespace": namespace,
3527
+ "query": query_text,
3528
+ "timestamp": time.time()
3529
+ }
3530
+ }
3531
+ except Exception as e:
3532
+ raise HTTPException(status_code=400, detail=str(e))
3533
+
3534
+ # ============================================================================
3535
+ # API VERSIONING - v1 and v2 endpoints
3536
+ # ============================================================================
3537
+
3538
+ @app.post("/aiql")
3539
+ async def execute_aiql(request: dict):
3540
+ """
3541
+ Execute AIQL query with unified single-path architecture.
3542
+
3543
+ AUTO-DETECTION:
3544
+ - session_id provided and valid → STATEFUL MODE (CLI / Interactive Sessions)
3545
+ Uses cached graph instance from session
3546
+ - No session_id or invalid → STATELESS MODE (API / Per-Request)
3547
+ Creates new graph instance per request (thread-safe)
3548
+ """
3549
+ import time
3550
+
3551
+ try:
3552
+ import uuid
3553
+
3554
+ # Handle string bodies (e.g. PowerShell Invoke-WebRequest)
3555
+ request = _ensure_dict(request)
3556
+
3557
+ start_time = time.time()
3558
+ query = request.get("query", "")
3559
+ session_id = request.get("session_id", None)
3560
+ namespace = request.get("namespace", "default")
3561
+
3562
+ # Extract client info
3563
+ client_info = _get_client_info(request)
3564
+
3565
+ if not query:
3566
+ raise HTTPException(status_code=400, detail="Query is required")
3567
+
3568
+ logger.info(f"Executing AIQL Query: {query[:100]}...")
3569
+
3570
+ # Check for expired sessions first
3571
+ _cleanup_expired_sessions()
3572
+
3573
+ # ============================================================
3574
+ # MODE DETECTION: Auto-detect based on session_id
3575
+ # ============================================================
3576
+
3577
+ is_stateful = False
3578
+ current_graph = None
3579
+ old_namespace = namespace
3580
+
3581
+ with _sessions_lock:
3582
+ if session_id and session_id in _sessions:
3583
+ # ============================================================
3584
+ # STATEFUL MODE: CLI / Interactive Sessions
3585
+ # ============================================================
3586
+ is_stateful = True
3587
+ session = _sessions[session_id]
3588
+
3589
+ # Check if session is expired
3590
+ elapsed = time.time() - session.get('created_at', time.time())
3591
+ timeout = session.get('timeout', 3600)
3592
+ if elapsed > timeout:
3593
+ # Session expired - switch to stateless mode
3594
+ del _sessions[session_id]
3595
+ logger.info(f"[MODE] Session {session_id[:8]}... expired, switching to stateless mode")
3596
+ is_stateful = False
3597
+ session_id = None
3598
+
3599
+ if is_stateful:
3600
+ # Use session's graph and namespace
3601
+ current_graph = session.get('contextcore')
3602
+ namespace = session.get('active_namespace', namespace)
3603
+ old_namespace = namespace
3604
+ logger.debug(f"[MODE] STATEFUL: Using session {session_id[:8]}... namespace '{namespace}'")
3605
+ else:
3606
+ # ============================================================
3607
+ # STATELESS MODE: API / Per-Request Instances
3608
+ # ============================================================
3609
+ is_stateful = False
3610
+
3611
+ if not is_stateful:
3612
+ # Create new graph instance per request (thread-safe)
3613
+ current_graph = graph_registry.get_graph_for_request(namespace)
3614
+ logger.debug(f"[MODE] STATELESS: Created new graph instance for namespace '{namespace}'")
3615
+
3616
+ # Create session only if session_id was provided (CLI first request)
3617
+ if session_id:
3618
+ # User provided session_id but it doesn't exist - create new session
3619
+ session_id = _create_session(namespace, current_graph, request, client_info)
3620
+ is_stateful = True # Now we're in stateful mode
3621
+ logger.debug(f"[MODE] Created new session {session_id[:8]}... (switched to stateful)")
3622
+
3623
+ # Ensure graph is initialized
3624
+ if not current_graph:
3625
+ current_graph = graph_registry.get_graph_for_request(namespace)
3626
+
3627
+ # NOTE: Aliases are now query-scoped (stored in executor, not in graph)
3628
+ # No need to initialize alias_to_node on graph anymore
3629
+
3630
+ # ============================================================
3631
+ # UNIFIED EXECUTION PATH (Same for both modes)
3632
+ # ============================================================
3633
+
3634
+ # Use executor pool to avoid creating new executor per request (performance optimization)
3635
+ executor_key = f"{namespace}_{session_id or 'stateless'}"
3636
+ with _executor_pool_lock:
3637
+ if executor_key in _executor_pool:
3638
+ # Reuse existing executor (already warmed up)
3639
+ executor = _executor_pool[executor_key]
3640
+ # Update graph reference in case it changed
3641
+ if hasattr(executor, 'contextcore'):
3642
+ executor.contextcore = current_graph
3643
+ executor.active_namespace = namespace
3644
+ else:
3645
+ # Create new executor and warm it up
3646
+ executor = AIQLExecutor(contextcore=current_graph)
3647
+ executor.active_namespace = namespace
3648
+ executor.graph_registry = graph_registry
3649
+
3650
+ # Warm up executor (trigger lazy initialization once)
3651
+ try:
3652
+ executor.execute("SHOW NAMESPACES;")
3653
+ except:
3654
+ pass # Warm-up failed, continue anyway
3655
+
3656
+ # Store in pool for reuse
3657
+ _executor_pool[executor_key] = executor
3658
+ logger.debug(f"[PERF] Created and warmed up executor for {executor_key}")
3659
+
3660
+ # Debug: Log graph state before execution
3661
+ if current_graph:
3662
+ node_count = len(current_graph.node_index) if hasattr(current_graph, 'node_index') else 0
3663
+ logger.debug(f"[EXEC] Graph state before execution: {node_count} nodes (mode: {'STATEFUL' if is_stateful else 'STATELESS'})")
3664
+
3665
+ # Execute query with timeout to prevent resource exhaustion
3666
+ _query_timeout = int(os.environ.get("CONTEXTSYNAPSE_QUERY_TIMEOUT") or os.environ.get("AICONTEXTDB_QUERY_TIMEOUT", "30"))
3667
+ try:
3668
+ result = await asyncio.wait_for(
3669
+ asyncio.to_thread(executor.execute, query),
3670
+ timeout=_query_timeout,
3671
+ )
3672
+ except asyncio.TimeoutError:
3673
+ raise HTTPException(
3674
+ status_code=408,
3675
+ detail=f"Query timed out after {_query_timeout}s. Simplify your query or add LIMIT.",
3676
+ )
3677
+
3678
+ # Force save to disk after write operations (critical for multi-worker)
3679
+ _q_upper = query.strip().upper()
3680
+ if any(_q_upper.startswith(w) for w in ("CREATE", "DELETE", "MERGE", "SET", "INSERT", "UPDATE")):
3681
+ try:
3682
+ graph_registry.save_graph(namespace, create_checkpoint=False)
3683
+ except Exception:
3684
+ pass # optional
3685
+
3686
+ # UNIFIED FORMAT: Extract nodes and edges from the new unified format
3687
+ # The executor now returns: {"nodes": [...], "edges": [...], "data": {...}, ...}
3688
+ nodes = []
3689
+ edges = []
3690
+
3691
+ if isinstance(result, dict):
3692
+ # Try direct format first (new unified format)
3693
+ nodes = result.get('nodes', [])
3694
+ edges = result.get('edges', [])
3695
+
3696
+ # Fallback for legacy nested format
3697
+ if not nodes or not edges:
3698
+ data = result.get('data', {})
3699
+ if isinstance(data, dict):
3700
+ fallback_nodes = data.get('nodes', [])
3701
+ fallback_edges = data.get('edges', [])
3702
+ if fallback_nodes:
3703
+ nodes = fallback_nodes
3704
+ if fallback_edges:
3705
+ edges = fallback_edges
3706
+
3707
+ # Add nodes and edges to result for backward compatibility
3708
+ result['nodes'] = nodes
3709
+ result['edges'] = edges
3710
+ elif isinstance(result, list):
3711
+ # Legacy format: bare list treated as nodes
3712
+ nodes = result
3713
+ result = {"nodes": nodes, "edges": []}
3714
+
3715
+ # ============================================================
3716
+ # POST-EXECUTION: Update State (if stateful)
3717
+ # ============================================================
3718
+
3719
+ if is_stateful and session_id:
3720
+ # Update session state
3721
+ _update_session(session_id, executor, old_namespace)
3722
+ with _sessions_lock:
3723
+ session = _sessions.get(session_id)
3724
+ if session:
3725
+ # Track errors
3726
+ if not result.get('success'):
3727
+ session['error_count'] = session.get('error_count', 0) + 1
3728
+
3729
+ # Track performance
3730
+ _track_performance(session, start_time, result)
3731
+
3732
+ # Add session info to result
3733
+ query_time = time.time() - start_time
3734
+ result['session_id'] = session_id
3735
+ result['session_info'] = {
3736
+ 'query_count': session.get('query_count', 0),
3737
+ 'active_namespace': session.get('active_namespace'),
3738
+ 'active_collection': session.get('active_collection'),
3739
+ 'error_count': session.get('error_count', 0),
3740
+ 'query_time_ms': round(query_time * 1000, 2)
3741
+ }
3742
+
3743
+ # Add performance metrics
3744
+ if 'performance' in session:
3745
+ perf = session['performance']
3746
+ result['performance'] = {
3747
+ 'avg_response_time_ms': round(perf.get('avg_response_time', 0) * 1000, 2),
3748
+ 'min_response_time_ms': round(perf.get('min_response_time', 0) * 1000, 2),
3749
+ 'max_response_time_ms': round(perf.get('max_response_time', 0) * 1000, 2),
3750
+ 'total_queries': perf.get('total_queries', 0),
3751
+ 'error_rate': round(perf.get('error_rate', 0) * 100, 2),
3752
+ 'cache_hit_rate': round(perf.get('cache_hits', 0) / max(perf.get('total_queries', 1), 1) * 100, 2)
3753
+ }
3754
+
3755
+ # Add security info (sanitized)
3756
+ if 'security' in session:
3757
+ result['security'] = {
3758
+ 'role': session['security'].get('role', 'user'),
3759
+ 'authenticated': session['security'].get('authenticated', False)
3760
+ }
3761
+
3762
+ # Add monitoring info
3763
+ if 'monitoring' in session:
3764
+ result['monitoring'] = {
3765
+ 'health_score': session['monitoring'].get('health_score', 100.0),
3766
+ 'alerts_count': len(session['monitoring'].get('alerts', []))
3767
+ }
3768
+ else:
3769
+ # Stateless mode - minimal response
3770
+ query_time = time.time() - start_time
3771
+ result['query_time_ms'] = round(query_time * 1000, 2)
3772
+
3773
+ logger.info(f"Query executed successfully (mode: {'STATEFUL' if is_stateful else 'STATELESS'})")
3774
+
3775
+ # Track metadata (after execution completes)
3776
+ if METADATA_TRACKING_AVAILABLE:
3777
+ try:
3778
+ tracker = get_metadata_tracker()
3779
+
3780
+ if tracker:
3781
+ # Track query with full session context
3782
+ query_data = {
3783
+ 'query': query,
3784
+ 'query_type': result.get('query_type', 'UNKNOWN')
3785
+ }
3786
+
3787
+ tracker.track_query(
3788
+ session_data=session,
3789
+ query_data=query_data,
3790
+ execution_result=result
3791
+ )
3792
+
3793
+ # Update session state in metadata store
3794
+ tracker.track_session_update(session)
3795
+
3796
+ except Exception as e:
3797
+ logger.warning(f"[EMOJI][EMOJI] Metadata tracking failed: {e}")
3798
+ # Don't fail the main request if tracking fails
3799
+
3800
+ return result
3801
+
3802
+ except Exception as e:
3803
+ logger.error(f"Error executing AIQL query: {e}")
3804
+ import traceback
3805
+ logger.error(traceback.format_exc())
3806
+ raise HTTPException(status_code=400, detail=str(e))
3807
+
3808
+ # API v1 endpoints (standardized)
3809
+ @app.post("/api/v1/aiql")
3810
+ async def execute_aiql_v1(request: dict):
3811
+ """Execute AIQL query - API v1."""
3812
+ return await execute_aiql(request)
3813
+
3814
+ @app.post("/api/v1/pipeline/create")
3815
+ async def create_pipeline_v1(request: dict):
3816
+ """Create pipeline - API v1."""
3817
+ return await execute_aiql({"query": request.get("query", ""), "namespace": request.get("namespace", "default")})
3818
+
3819
+ @app.post("/api/v1/pipeline/run")
3820
+ async def run_pipeline_v1(request: dict):
3821
+ """Run pipeline - API v1."""
3822
+ return await execute_aiql({"query": request.get("query", ""), "namespace": request.get("namespace", "default")})
3823
+
3824
+ @app.post("/api/v1/data/{namespace}/rag")
3825
+ async def execute_rag_query(namespace: str, question: dict, graph_db: QGraphDB = Depends(get_current_graph)):
3826
+ """Execute RAG query for a specific namespace."""
3827
+ try:
3828
+ question_text = question.get("question", "")
3829
+ if not question_text:
3830
+ raise HTTPException(status_code=400, detail="Question text is required")
3831
+
3832
+ # Initialize AIQL executor
3833
+ executor = AIQLExecutor()
3834
+
3835
+ # Execute RAG query using the correct grammar with AT NAMESPACE
3836
+ rag_query = f'RAG "{question_text}" AT NAMESPACE {namespace}'
3837
+ result = executor.execute(rag_query)
3838
+
3839
+ # UNIFIED FORMAT: Extract nodes and edges using unified format
3840
+ nodes = []
3841
+ if isinstance(result, dict):
3842
+ data = result.get('data', {})
3843
+ if isinstance(data, dict):
3844
+ nodes = data.get('nodes', [])
3845
+ else:
3846
+ # Fallback: check results structure
3847
+ results = result.get('results', {})
3848
+ if isinstance(results, dict):
3849
+ nodes = results.get('nodes', [])
3850
+ # Fallback for legacy format
3851
+ nodes = result.get('nodes', []) if not nodes else nodes
3852
+
3853
+ return {
3854
+ "success": result.get("success", False) if isinstance(result, dict) else False,
3855
+ "answer": result.get("data", {}) if isinstance(result, dict) else {},
3856
+ "context": nodes,
3857
+ "error": result.get("error") if isinstance(result, dict) else None,
3858
+ "metadata": {
3859
+ "namespace": namespace,
3860
+ "question": question_text,
3861
+ "timestamp": time.time()
3862
+ }
3863
+ }
3864
+ except Exception as e:
3865
+ raise HTTPException(status_code=400, detail=str(e))
3866
+
3867
+ @app.get("/api/v1/data/{namespace}/nodes")
3868
+ async def get_namespace_nodes(namespace: str):
3869
+ """Get all nodes from a specific namespace."""
3870
+ try:
3871
+ nodes = []
3872
+ namespace_dir = f"contextcore_data/namespaces/{namespace}/nodes"
3873
+
3874
+ if os.path.exists(namespace_dir):
3875
+ for node_type in os.listdir(namespace_dir):
3876
+ node_type_dir = os.path.join(namespace_dir, node_type)
3877
+ if os.path.isdir(node_type_dir):
3878
+ for node_file in os.listdir(node_type_dir):
3879
+ if node_file.endswith('.json'):
3880
+ node_path = os.path.join(node_type_dir, node_file)
3881
+ try:
3882
+ with open(node_path, 'r') as f:
3883
+ node_data = json.load(f)
3884
+ nodes.append({
3885
+ "id": node_data.get('id', 'N/A'),
3886
+ "type": node_type,
3887
+ "properties": node_data
3888
+ })
3889
+ except Exception as e:
3890
+ continue
3891
+
3892
+ return {
3893
+ "success": True,
3894
+ "data": nodes,
3895
+ "count": len(nodes),
3896
+ "metadata": {
3897
+ "namespace": namespace,
3898
+ "timestamp": time.time()
3899
+ }
3900
+ }
3901
+ except Exception as e:
3902
+ raise HTTPException(status_code=400, detail=str(e))
3903
+
3904
+ @app.get("/api/v1/data/{namespace}/schema")
3905
+ async def get_namespace_schema(namespace: str):
3906
+ """Get schema information for a specific namespace."""
3907
+ try:
3908
+ schema = {
3909
+ "node_types": [],
3910
+ "edge_types": [],
3911
+ "collections": [],
3912
+ "pipelines": []
3913
+ }
3914
+
3915
+ namespace_dir = f"contextcore_data/namespaces/{namespace}"
3916
+
3917
+ # Get node types
3918
+ nodes_dir = os.path.join(namespace_dir, "nodes")
3919
+ if os.path.exists(nodes_dir):
3920
+ schema["node_types"] = [d for d in os.listdir(nodes_dir) if os.path.isdir(os.path.join(nodes_dir, d))]
3921
+
3922
+ # Get edge types
3923
+ edges_dir = os.path.join(namespace_dir, "edges")
3924
+ if os.path.exists(edges_dir):
3925
+ schema["edge_types"] = [d for d in os.listdir(edges_dir) if os.path.isdir(os.path.join(edges_dir, d))]
3926
+
3927
+ # Get collections
3928
+ collections_dir = os.path.join(namespace_dir, "collections")
3929
+ if os.path.exists(collections_dir):
3930
+ schema["collections"] = [d for d in os.listdir(collections_dir) if os.path.isdir(os.path.join(collections_dir, d))]
3931
+
3932
+ # Get pipelines
3933
+ pipelines_dir = os.path.join(namespace_dir, "pipelines")
3934
+ if os.path.exists(pipelines_dir):
3935
+ schema["pipelines"] = [d for d in os.listdir(pipelines_dir) if os.path.isdir(os.path.join(pipelines_dir, d))]
3936
+
3937
+ return {
3938
+ "success": True,
3939
+ "data": schema,
3940
+ "metadata": {
3941
+ "namespace": namespace,
3942
+ "timestamp": time.time()
3943
+ }
3944
+ }
3945
+ except Exception as e:
3946
+ raise HTTPException(status_code=400, detail=str(e))
3947
+
3948
+ @app.get("/api/v1/system/health")
3949
+ async def get_system_health(_admin=Depends(AdminAuth())):
3950
+ """Get detailed system health status (admin only)."""
3951
+ try:
3952
+ # Get node and edge counts using CSR storage
3953
+ default_graph = graph_registry.get_graph("default")
3954
+ node_count = 0
3955
+ edge_count = 0
3956
+ if default_graph:
3957
+ if hasattr(default_graph, 'csr_storage') and default_graph.csr_storage:
3958
+ node_count = default_graph.csr_storage.get_node_count() if hasattr(default_graph.csr_storage, 'get_node_count') else 0
3959
+ edge_count = default_graph.csr_storage.get_edge_count() if hasattr(default_graph.csr_storage, 'get_edge_count') else 0
3960
+ elif hasattr(default_graph, 'node_index'):
3961
+ node_count = len(default_graph.node_index) if default_graph.node_index else 0
3962
+
3963
+ return {
3964
+ "status": "healthy",
3965
+ "timestamp": datetime.now().isoformat(),
3966
+ "graph_stats": {
3967
+ "nodes": node_count,
3968
+ "edges": edge_count
3969
+ },
3970
+ "features": {
3971
+ "aiql": True,
3972
+ "rag": True,
3973
+ "hybrid_search": True,
3974
+ "pipelines": True
3975
+ }
3976
+ }
3977
+ except Exception as e:
3978
+ raise HTTPException(status_code=500, detail=str(e))
3979
+
3980
+ @app.post("/tinker")
3981
+ async def execute_tinker(request: dict, _admin=Depends(AdminAuth())):
3982
+ """Tinker CLI endpoint - direct DB access with immediate consistency (port 8001).
3983
+
3984
+ This endpoint provides direct database access similar to Neo4j's Bolt protocol.
3985
+ It's optimized for troubleshooting, development, and interactive use.
3986
+ Requires admin authentication.
3987
+ """
3988
+ import time
3989
+
3990
+ try:
3991
+ # Handle string bodies (e.g. PowerShell Invoke-WebRequest)
3992
+ request = _ensure_dict(request)
3993
+
3994
+ start_time = time.time()
3995
+ query = request.get("query", "")
3996
+ namespace = request.get("namespace", "default")
3997
+
3998
+ if not query:
3999
+ raise HTTPException(status_code=400, detail="Query is required")
4000
+
4001
+ logger.debug(f"Tinker CLI executing query: {query[:100]}...")
4002
+
4003
+ # Get direct DB instance (shared with API server)
4004
+ current_graph = graph_registry.get_graph(namespace)
4005
+ if not current_graph:
4006
+ # Create if doesn't exist
4007
+ current_graph = graph_registry.create_graph(namespace)
4008
+
4009
+ # Create executor with direct DB access
4010
+ executor = AIQLExecutor(current_graph, graph_registry)
4011
+
4012
+ # Execute query directly (no session overhead)
4013
+ result = executor.execute(query)
4014
+
4015
+ # UNIFIED FORMAT: Executor always returns nodes/edges in result.data
4016
+ # Use same extraction logic as /aiql endpoint for consistency
4017
+ nodes = []
4018
+ edges = []
4019
+
4020
+ if isinstance(result, dict):
4021
+ data = result.get('data', {})
4022
+ if isinstance(data, dict):
4023
+ # Unified format: nodes and edges are always in data['nodes'] and data['edges']
4024
+ nodes = data.get('nodes', [])
4025
+ edges = data.get('edges', [])
4026
+ else:
4027
+ # Fallback: check results structure
4028
+ results = result.get('results', {})
4029
+ if isinstance(results, dict):
4030
+ nodes = results.get('nodes', [])
4031
+ edges = results.get('edges', [])
4032
+ # Fallback for legacy format
4033
+ nodes = result.get('nodes', []) if not nodes else nodes
4034
+ edges = result.get('edges', []) if not edges else edges
4035
+
4036
+ execution_time = time.time() - start_time
4037
+
4038
+ return {
4039
+ "success": result.get('success', True) if isinstance(result, dict) else True,
4040
+ "data": result.get('data', {}) if isinstance(result, dict) else {},
4041
+ "nodes": nodes,
4042
+ "edges": edges,
4043
+ "execution_time": execution_time,
4044
+ "namespace": namespace,
4045
+ "message": result.get('message', 'Query executed successfully') if isinstance(result, dict) else "Query executed successfully"
4046
+ }
4047
+
4048
+ except Exception as e:
4049
+ logger.error(f"Tinker CLI error: {e}")
4050
+ import traceback
4051
+ return {
4052
+ "success": False,
4053
+ "error": str(e),
4054
+ "traceback": traceback.format_exc() if logger.isEnabledFor(logging.DEBUG) else None,
4055
+ "execution_time": time.time() - start_time if 'start_time' in locals() else 0
4056
+ }
4057
+
4058
+ # Create separate FastAPI app for Tinker (port 8001)
4059
+ # Disabled by default — set AICONTEXTDB_ENABLE_TINKER=true to enable.
4060
+ _tinker_enabled = os.environ.get("CONTEXTSYNAPSE_ENABLE_TINKER") or os.environ.get("AICONTEXTDB_ENABLE_TINKER", "false").lower() in ("true", "1", "yes")
4061
+
4062
+ tinker_app = FastAPI(
4063
+ title="AIContextDB Tinker CLI",
4064
+ description="Direct database access endpoint for troubleshooting and development",
4065
+ version="1.0.0"
4066
+ )
4067
+
4068
+ # Use same CORS origins as main app
4069
+ tinker_app.add_middleware(
4070
+ CORSMiddleware,
4071
+ allow_origins=_cors_origins,
4072
+ allow_credentials=True,
4073
+ allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
4074
+ allow_headers=["Authorization", "Content-Type", "X-Request-ID", "X-Admin-Key"],
4075
+ )
4076
+
4077
+ # Register tinker endpoint on tinker app
4078
+ @tinker_app.post("/tinker")
4079
+ async def tinker_endpoint(request: dict, _admin=Depends(AdminAuth())):
4080
+ """Tinker endpoint on separate app. Requires admin auth."""
4081
+ if not _tinker_enabled:
4082
+ raise HTTPException(status_code=403, detail="Tinker endpoint is disabled. Set AICONTEXTDB_ENABLE_TINKER=true to enable.")
4083
+ return await execute_tinker(request)
4084
+
4085
+ @tinker_app.get("/health")
4086
+ async def tinker_health():
4087
+ """Health check for tinker server."""
4088
+ return {"status": "healthy", "service": "tinker", "enabled": _tinker_enabled}
4089
+
4090
+ # ── SPA fallback: serve React frontend ────────────────────────────────
4091
+ _frontend_build = _Path(__file__).resolve().parents[2] / "frontend" / "build"
4092
+ if _frontend_build.exists():
4093
+ # Serve static assets (JS, CSS, images) for production deployment
4094
+ app.mount("/static", StaticFiles(directory=str(_frontend_build / "static")), name="static")
4095
+
4096
+ from fastapi.responses import FileResponse
4097
+
4098
+ # Root serves index.html
4099
+ @app.get("/")
4100
+ async def _spa_root():
4101
+ return FileResponse(str(_frontend_build / "index.html"))
4102
+
4103
+ # SPA routes — only explicit dashboard UI paths, NOT API paths
4104
+ @app.get("/login")
4105
+ @app.get("/signup")
4106
+ async def _spa_auth_pages():
4107
+ return FileResponse(str(_frontend_build / "index.html"))
4108
+
4109
+ if __name__ == "__main__":
4110
+ import sys, asyncio, uvicorn
4111
+ # Suppress harmless Windows ConnectionResetError on closed sockets
4112
+ if sys.platform == "win32":
4113
+ _orig_handler = asyncio.get_event_loop_policy()
4114
+ class _QuietProactorPolicy(asyncio.DefaultEventLoopPolicy):
4115
+ class _Loop(asyncio.ProactorEventLoop):
4116
+ def call_exception_handler(self, context):
4117
+ exc = context.get("exception")
4118
+ if isinstance(exc, ConnectionResetError):
4119
+ return # ignore browser dropping CORS preflight connections
4120
+ super().call_exception_handler(context)
4121
+ def new_event_loop(self):
4122
+ return self._Loop()
4123
+ asyncio.set_event_loop_policy(_QuietProactorPolicy())
4124
+
4125
+ workers = int(os.environ.get("AICONTEXTDB_API_WORKERS", "1"))
4126
+
4127
+ # Warn if using file-based storage with multiple workers (state not shared)
4128
+ if workers > 1:
4129
+ backend = os.environ.get("CONTEXTSYNAPSE_GRAPH_BACKEND") or os.environ.get("AICONTEXTDB_GRAPH_BACKEND", "")
4130
+ redis_url = os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL", "")
4131
+ if backend != "redis" and not redis_url:
4132
+ logger.warning(
4133
+ "Running %d workers with file-based storage — each worker gets its own "
4134
+ "graph registry. Set AICONTEXTDB_REDIS_URL for shared state.", workers
4135
+ )
4136
+
4137
+ uvicorn.run(
4138
+ "contextsynapse.api.api:app",
4139
+ host="0.0.0.0",
4140
+ port=8000,
4141
+ workers=workers,
4142
+ log_level="info",
4143
+ timeout_keep_alive=30,
4144
+ )