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,2451 @@
1
+ """Smart Ingestion Pipeline — the main entry point.
2
+
3
+ One function to ingest any web page into a rich knowledge graph:
4
+ Clean -> Chunk -> Extract -> Link -> Embed -> Index -> Validate
5
+
6
+ Pipelines:
7
+ - "smart_article" : For news/blog articles. Uses Trafilatura + hybrid chunking +
8
+ local LLM extraction. Produces Document, Passage, Entity, Fact,
9
+ Link nodes with full relationship edges.
10
+ - "smart_text" : For raw text (no HTML). Same extraction but skips Trafilatura.
11
+
12
+ Usage:
13
+ from contextsynapse.ingestion.smart_ingest import ingest_url, ingest_text
14
+
15
+ result = ingest_url("https://example.com/article", db, schema)
16
+ # result.document_id, result.passage_ids, result.entity_ids, etc.
17
+
18
+ result = ingest_text("Some article text...", db, title="My Article")
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import logging
23
+ import uuid as _uuid
24
+ from dataclasses import dataclass, field
25
+ from datetime import datetime, timezone
26
+ from typing import Any, Callable, Dict, List, Optional
27
+
28
+ from .cleaner import clean_webpage, clean_text, CleanDocument
29
+ from .chunker import chunk_document, PassageChunk
30
+ from .graph_builder import build_graph, BuildResult, ChunkExtraction
31
+ from .schema_extractor import (
32
+ IngestionSchema, load_schema, regex_extract, llm_extract,
33
+ merge_extractions, build_llm_prompt,
34
+ )
35
+ from .schema_validator import validate_and_flag
36
+ from .dedup import dedup_check
37
+ from .filters import FilterConfig, FilterResult, filter_chain, structural_pre_filter, post_extraction_filter
38
+ from .strategies import ContentStrategy, get_strategy, list_strategies
39
+ from .amplifier import amplify_extractions
40
+ from ..intelligence.tagger import tag_extractions as _tag_extractions
41
+ from ..intelligence.dedup import ContentFingerprint, SemanticDedup
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # Module-level dedup instances (shared across ingestion calls within same process)
46
+ _content_fingerprint: Optional[ContentFingerprint] = None
47
+ _semantic_dedup: Optional[SemanticDedup] = None
48
+
49
+
50
+ def _get_content_fingerprint() -> ContentFingerprint:
51
+ global _content_fingerprint
52
+ if _content_fingerprint is None:
53
+ _content_fingerprint = ContentFingerprint()
54
+ return _content_fingerprint
55
+
56
+
57
+ def _get_semantic_dedup() -> SemanticDedup:
58
+ global _semantic_dedup
59
+ if _semantic_dedup is None:
60
+ _semantic_dedup = SemanticDedup()
61
+ return _semantic_dedup
62
+
63
+ # In-memory staging store for review mode previews
64
+ _staging_store: Dict[str, "StagingResult"] = {}
65
+
66
+
67
+ @dataclass
68
+ class StagingResult:
69
+ """Preview of what would be created — not yet committed to graph."""
70
+ staging_id: str = ""
71
+ clean_doc: Any = None
72
+ chunks: List = field(default_factory=list)
73
+ extractions: List = field(default_factory=list)
74
+ passages: List[Dict] = field(default_factory=list)
75
+ entities: List[Dict] = field(default_factory=list)
76
+ facts: List[Dict] = field(default_factory=list)
77
+ edges: List[Dict] = field(default_factory=list)
78
+ links: List[Dict] = field(default_factory=list)
79
+ quality_score: float = 0.0
80
+ filter_log: List[Dict] = field(default_factory=list)
81
+ schema_suggestions: List[Dict] = field(default_factory=list)
82
+ schema_used: str = ""
83
+ pipeline: str = ""
84
+ created_at: str = ""
85
+
86
+ def commit(self, db, schema=None, exclude_ids=None):
87
+ """Commit staged results to graph."""
88
+ from .graph_builder import build_graph
89
+ exclude = set(exclude_ids or [])
90
+
91
+ # Filter out excluded items
92
+ if exclude:
93
+ self.extractions = [
94
+ ChunkExtraction(
95
+ chunk_index=ext.chunk_index,
96
+ entities=[e for e in ext.entities if e.get("_staging_id") not in exclude],
97
+ facts=[f for f in ext.facts if f.get("_staging_id") not in exclude],
98
+ relationships=ext.relationships,
99
+ )
100
+ for ext in self.extractions
101
+ ]
102
+
103
+ result = build_graph(self.clean_doc, self.chunks, self.extractions, db, schema, self.pipeline)
104
+ _embed_nodes(result, db)
105
+ _index_bm25(result, db)
106
+
107
+ # Clean up staging
108
+ if self.staging_id in _staging_store:
109
+ del _staging_store[self.staging_id]
110
+
111
+ return result
112
+
113
+ def discard(self):
114
+ """Discard staged results."""
115
+ if self.staging_id in _staging_store:
116
+ del _staging_store[self.staging_id]
117
+
118
+ def to_dict(self) -> Dict:
119
+ """Serialize for API response."""
120
+ d = {
121
+ "staging_id": self.staging_id,
122
+ "passages": self.passages,
123
+ "entities": self.entities,
124
+ "facts": self.facts,
125
+ "edges": self.edges,
126
+ "links": self.links,
127
+ "quality_score": self.quality_score,
128
+ "filter_log": self.filter_log,
129
+ "schema_used": self.schema_used,
130
+ "pipeline": self.pipeline,
131
+ }
132
+ if self.schema_suggestions:
133
+ d["schema_suggestions"] = self.schema_suggestions
134
+ return d
135
+
136
+
137
+ def _calc_quality(passages, entities, facts, edges) -> float:
138
+ """Calculate quality score 0-100. Uses amplifier signals when available."""
139
+ if not passages:
140
+ return 0.0
141
+
142
+ # Passage quality (unchanged — longer, well-chunked passages are better)
143
+ avg_tokens = sum(p.get("token_count", 0) for p in passages) / len(passages) if passages else 0
144
+ passage_q = min(100, (avg_tokens / 500) * 100) if avg_tokens > 0 else 0
145
+
146
+ # Entity quality — reward relevant entities, penalize noise
147
+ if entities:
148
+ relevant_entities = [e for e in entities if not e.get("_noise_flags")]
149
+ noise_ratio = 1.0 - (len(relevant_entities) / len(entities)) if entities else 0
150
+ relevances = [e.get("_amplifier_relevance", 0.5) for e in relevant_entities]
151
+ avg_ent_relevance = sum(relevances) / len(relevances) if relevances else 0.5
152
+ ent_score = min(100, (len(relevant_entities) / max(1, len(passages))) * 50) * avg_ent_relevance
153
+ # Penalize high noise ratio
154
+ ent_score *= max(0.3, 1.0 - noise_ratio)
155
+ else:
156
+ ent_score = 0
157
+
158
+ # Fact quality — reward relevant facts
159
+ if facts:
160
+ fact_relevances = [f.get("_amplifier_relevance", 0.5) for f in facts]
161
+ avg_fact_relevance = sum(fact_relevances) / len(fact_relevances)
162
+ fact_score = min(100, (len(facts) / max(1, len(passages))) * 100) * avg_fact_relevance
163
+ else:
164
+ fact_score = 0
165
+
166
+ # Edge score (unchanged)
167
+ edge_score = min(100, len(edges) * 5)
168
+
169
+ return round(passage_q * 0.3 + ent_score * 0.3 + fact_score * 0.25 + edge_score * 0.15, 1)
170
+
171
+
172
+ def _auto_detect_strategy(text: str) -> "ContentStrategy":
173
+ """Auto-detect the best content strategy based on text signals."""
174
+ import re as _re
175
+ text_sample = text[:2000].lower()
176
+
177
+ # Financial/business signals
178
+ financial_signals = len(_re.findall(
179
+ r'\b(?:revenue|earnings|profit|stock|market|billion|million|quarter|Q[1-4]|'
180
+ r'CEO|IPO|shares|dividend|fiscal|GDP|inflation|interest rate)\b',
181
+ text_sample, _re.IGNORECASE
182
+ ))
183
+ if financial_signals >= 3:
184
+ return get_strategy("business_report")
185
+
186
+ # News signals (dates, quotes, said/announced/reported)
187
+ news_signals = len(_re.findall(
188
+ r'\b(?:said|announced|reported|according to|confirmed|statement|officials?)\b',
189
+ text_sample, _re.IGNORECASE
190
+ ))
191
+ if news_signals >= 2:
192
+ return get_strategy("news_article")
193
+
194
+ # Technical doc signals
195
+ tech_signals = len(_re.findall(
196
+ r'\b(?:API|function|class|install|import|config|parameter|returns?|module)\b',
197
+ text_sample, _re.IGNORECASE
198
+ ))
199
+ if tech_signals >= 3:
200
+ return get_strategy("technical_doc")
201
+
202
+ # Default to news_article (richer extraction than general)
203
+ return get_strategy("news_article")
204
+
205
+
206
+ def _entity_near_text(entity_name: str, text: str, window: int = 200) -> bool:
207
+ """Check if entity name appears in text (for entity-level tag refinement)."""
208
+ if not entity_name or not text:
209
+ return False
210
+ return entity_name.lower() in text.lower()
211
+
212
+
213
+ def _find_entity_sentiment(entity_name: str, chunk_text: str) -> str | None:
214
+ """Determine entity-specific sentiment by looking at the sentence containing the entity."""
215
+ import re as _re
216
+ name_lower = entity_name.lower()
217
+ text_lower = chunk_text.lower()
218
+
219
+ if name_lower not in text_lower:
220
+ return None
221
+
222
+ # Find the sentence containing the entity
223
+ sentences = _re.split(r'[.!?]+', chunk_text)
224
+ for sentence in sentences:
225
+ if name_lower in sentence.lower():
226
+ from ..intelligence.heuristics import detect_sentiment
227
+ result = detect_sentiment(sentence)
228
+ if result.confidence > 0.3:
229
+ return result.sentiment
230
+
231
+ return None
232
+
233
+
234
+ def _apply_intelligence_tags(extractions, tag_result, chunk_texts):
235
+ """Apply intelligence tags to entities with entity-level refinement.
236
+
237
+ Instead of broadcasting all chunk-level tags to every entity, this checks:
238
+ 1. Sentiment: per-entity by analyzing the sentence containing the entity
239
+ 2. Geography: only if the entity appears near the geographic mention
240
+ 3. Domain/Impact: applied to all entities in the chunk (these are content-level)
241
+ """
242
+ for ext in extractions:
243
+ chunk_tags = [t for t in tag_result.tags if t.chunk_index == ext.chunk_index]
244
+ chunk_text = chunk_texts[ext.chunk_index] if ext.chunk_index < len(chunk_texts) else ""
245
+
246
+ # Get chunk-level tags as defaults
247
+ chunk_sentiment = None
248
+ chunk_sentiment_conf = 0.0
249
+ sentiments = [t for t in chunk_tags if t.dimension == "sentiment"]
250
+ if sentiments:
251
+ best = max(sentiments, key=lambda t: t.confidence)
252
+ chunk_sentiment = best.value
253
+ chunk_sentiment_conf = best.confidence
254
+
255
+ chunk_impact = None
256
+ impacts = [t for t in chunk_tags if t.dimension == "impact"]
257
+ if impacts:
258
+ chunk_impact = max(impacts, key=lambda t: t.confidence).value
259
+
260
+ chunk_geos = [t.value for t in chunk_tags if t.dimension == "geography"]
261
+ chunk_domains = [t.value for t in chunk_tags if t.dimension == "domain"]
262
+
263
+ for ent in ext.entities:
264
+ props = ent.setdefault("properties", {})
265
+ ent_name = props.get("name", "")
266
+
267
+ # Sentiment: try entity-specific first, fall back to chunk-level
268
+ if chunk_text and ent_name:
269
+ entity_sentiment = _find_entity_sentiment(ent_name, chunk_text)
270
+ if entity_sentiment:
271
+ props["_sentiment"] = entity_sentiment
272
+ props["_sentiment_confidence"] = 0.7
273
+ elif chunk_sentiment:
274
+ props["_sentiment"] = chunk_sentiment
275
+ props["_sentiment_confidence"] = chunk_sentiment_conf * 0.8 # lower confidence for inherited
276
+ elif chunk_sentiment:
277
+ props["_sentiment"] = chunk_sentiment
278
+ props["_sentiment_confidence"] = chunk_sentiment_conf
279
+
280
+ # Impact: content-level, apply to all
281
+ if chunk_impact:
282
+ props["_impact"] = chunk_impact
283
+
284
+ # Geography: only geos that appear near the entity in text
285
+ if chunk_geos and chunk_text and ent_name:
286
+ import re as _re
287
+ relevant_geos = []
288
+ # Find sentences containing this entity
289
+ entity_sentences = []
290
+ for sentence in _re.split(r'[.!?]+', chunk_text):
291
+ if ent_name.lower() in sentence.lower():
292
+ entity_sentences.append(sentence)
293
+
294
+ if entity_sentences:
295
+ entity_context = " ".join(entity_sentences)
296
+ for geo in chunk_geos:
297
+ if geo.lower() in entity_context.lower():
298
+ relevant_geos.append(geo)
299
+
300
+ # If no geo found near entity, don't assign any (rather than wrong ones)
301
+ if relevant_geos:
302
+ props["_geography"] = relevant_geos
303
+ elif chunk_geos:
304
+ props["_geography"] = chunk_geos
305
+
306
+ # Domain: content-level, apply to all
307
+ if chunk_domains:
308
+ props["_domain"] = chunk_domains
309
+
310
+ # Facts get chunk-level sentiment (facts are statements, not entities)
311
+ for fact in ext.facts:
312
+ fact_props = fact.setdefault("properties", {})
313
+ if chunk_sentiment:
314
+ fact_props["_sentiment"] = chunk_sentiment
315
+
316
+ # Freshness: use article publish date first, then extract from text
317
+ try:
318
+ from ..intelligence.freshness import detect_event_date, score_freshness
319
+ from datetime import datetime, timezone as _tz
320
+ now_iso = datetime.now(_tz.utc).isoformat()
321
+
322
+ # Priority 1: article's published_at from metadata (most reliable)
323
+ # Priority 2: event date extracted from content text
324
+ event_date = ""
325
+ date_source = ""
326
+
327
+ # Check if any entity already has _published_at from document metadata
328
+ for ent in ext.entities:
329
+ pub = ent.get("properties", {}).get("_published_at", "")
330
+ if pub:
331
+ event_date = pub[:10] # ISO date portion
332
+ date_source = "article_metadata"
333
+ break
334
+
335
+ # Fallback: extract from content text
336
+ if not event_date:
337
+ freshness_result = detect_event_date(chunk_text)
338
+ if freshness_result.event_date:
339
+ event_date = freshness_result.event_date
340
+ date_source = "content_extraction"
341
+
342
+ if event_date:
343
+ scored = score_freshness(event_date, now_iso)
344
+ for ent in ext.entities:
345
+ props = ent.setdefault("properties", {})
346
+ props["_event_date"] = event_date
347
+ props["_freshness"] = scored.freshness
348
+ props["_staleness_days"] = scored.staleness_days
349
+ props["_date_source"] = date_source
350
+ props["_ingested_at"] = now_iso
351
+ for fact in ext.facts:
352
+ fact_props = fact.setdefault("properties", {})
353
+ fact_props["_event_date"] = event_date
354
+ fact_props["_freshness"] = scored.freshness
355
+ fact_props["_staleness_days"] = scored.staleness_days
356
+ fact_props["_date_source"] = date_source
357
+ except Exception:
358
+ pass
359
+
360
+
361
+ # Pipeline registry — describes available pipelines for UI/API
362
+ #
363
+ # "smart_pipeline" is the DEFAULT and only pipeline most users need.
364
+ # It auto-detects input type (URL, text, file, chat export) and
365
+ # auto-selects the appropriate schema. The stages are always the same:
366
+ # PARSE → CHUNK → EXTRACT → LINK → EMBED → INDEX → VALIDATE → CU
367
+ #
368
+ # The other pipelines exist for backward compatibility and edge cases.
369
+
370
+ PIPELINES = {
371
+ "smart_pipeline": {
372
+ "name": "Smart Pipeline",
373
+ "description": "Auto-detects content type (articles, documents, conversations, "
374
+ "structured data) and extracts entities, facts, and relationships. "
375
+ "Uses LLM for high-quality extraction and vector embeddings for search.",
376
+ "input_types": ["url", "html", "text", "file", "zip", "json", "csv"],
377
+ "stages": [
378
+ "parse",
379
+ "chunk:hierarchical", # section-aware: Document→Passage(section)→Fact→Entity
380
+ "extract:llm+regex",
381
+ "amplify:semantic", # relevance scoring via bi-encoder cosine similarity
382
+ "link:graph",
383
+ "embed:qdrant", # passage + entity vectors → Qdrant
384
+ "index:bm25",
385
+ "validate:schema",
386
+ ],
387
+ "chunk_strategy": "hierarchical",
388
+ "llm_required": True,
389
+ "produces": ["Document", "Passage", "Entity", "Fact", "Conversation", "Message", "Topic"],
390
+ "edge_types": ["CONTAINS", "NEXT", "MENTIONS", "STATES", "DERIVED_FROM",
391
+ "LINKS_TO", "HAS_CONVERSATION", "HAS_MESSAGE", "DISCUSSES"],
392
+ "default": True,
393
+ },
394
+ "website": {
395
+ "name": "Website Pipeline",
396
+ "description": "Structured ingestion for web pages — preserves heading hierarchy "
397
+ "(H1→H2→H3) as Section nodes. Uses trafilatura markdown output so "
398
+ "heading depth is retained. Best for IR pages, about pages, blog posts.",
399
+ "input_types": ["url", "html"],
400
+ "stages": [
401
+ "parse",
402
+ "chunk:hierarchical:header-subheader", # depth-aware: Section(H1)→Section(H2)→Passage→Fact→Entity
403
+ "extract:llm+regex",
404
+ "amplify:semantic",
405
+ "link:graph",
406
+ "embed:qdrant",
407
+ "index:bm25",
408
+ "validate:schema",
409
+ ],
410
+ "chunk_strategy": "hierarchical",
411
+ "content_strategy": "website",
412
+ "llm_required": True,
413
+ "produces": ["Document", "Section", "Passage", "Entity", "Fact"],
414
+ "edge_types": ["CONTAINS", "HAS_SECTION", "NEXT", "MENTIONS", "STATES", "DERIVED_FROM"],
415
+ },
416
+ "fast_ingest": {
417
+ "name": "Fast (No LLM)",
418
+ "description": "Regex-only extraction without LLM calls. Fastest option — good "
419
+ "for bulk imports where speed matters more than extraction depth.",
420
+ "input_types": ["url", "html", "text", "file", "csv"],
421
+ "stages": [
422
+ "clean",
423
+ "chunk:paragraph", # flat paragraph splitting, no section detection
424
+ "regex_extract",
425
+ "link:graph",
426
+ "validate",
427
+ ],
428
+ "chunk_strategy": "paragraph",
429
+ "llm_required": False,
430
+ "produces": ["Document", "Passage", "Entity", "Fact"],
431
+ "edge_types": ["CONTAINS", "NEXT", "MENTIONS"],
432
+ },
433
+ }
434
+
435
+ # Legacy aliases — all route to smart_pipeline for backward compatibility
436
+ _PIPELINE_ALIASES = {
437
+ "smart_article": "smart_pipeline",
438
+ "smart_text": "smart_pipeline",
439
+ "chat_history": "smart_pipeline",
440
+ # website aliases
441
+ "ir_page": "website",
442
+ "webpage": "website",
443
+ }
444
+
445
+
446
+ def resolve_named_pipeline(pipeline_name: str) -> Optional[Dict]:
447
+ """Resolve a named pipeline from PipelineStore and return its config.
448
+
449
+ Returns dict with: schema_name, parser, filters, graph_config, default_params
450
+ Or None if pipeline not found or is a built-in alias.
451
+ """
452
+ # Don't resolve built-in names
453
+ if pipeline_name in PIPELINES or pipeline_name in _PIPELINE_ALIASES:
454
+ return None
455
+ try:
456
+ from .pipeline_store import PipelineStore
457
+ store = PipelineStore()
458
+ pipelines = store.list_pipelines(include_builtins=True)
459
+ for p in pipelines:
460
+ if p.get("name") == pipeline_name or p.get("id") == pipeline_name:
461
+ return {
462
+ "schema_name": p.get("schema_name", ""),
463
+ "parser": p.get("parser", ""),
464
+ "filters": p.get("filters", {}),
465
+ "graph_config": p.get("graph_config", {}),
466
+ "default_params": p.get("default_params", {}),
467
+ }
468
+ except Exception:
469
+ pass
470
+ return None
471
+
472
+
473
+ def _get_embed_fn() -> Optional[Callable]:
474
+ """Get embedding callable for semantic filtering."""
475
+ try:
476
+ from ..context.vector_integration import get_session_vector_store
477
+ svs = get_session_vector_store()
478
+ if svs and svs.available and hasattr(svs, 'embed_text'):
479
+ def embed_fn(text: str):
480
+ return svs.embed_text(text)
481
+ # Quick test
482
+ test = embed_fn("test")
483
+ if test and len(test) > 0:
484
+ return embed_fn
485
+ except Exception as e:
486
+ logger.debug("Embed function not available: %s", e)
487
+ return None
488
+
489
+
490
+ def _get_llm_fn(db=None) -> Optional[Callable]:
491
+ """Get LLM callable — tries Ollama (free) first, then cloud."""
492
+ try:
493
+ from ..llm.client import get_llm_client
494
+ client = get_llm_client()
495
+ if client:
496
+ def llm_fn(prompt: str) -> str:
497
+ return client.generate(prompt=prompt, max_tokens=3000)
498
+ return llm_fn
499
+ except Exception as e:
500
+ logger.warning("LLM client not available: %s", e)
501
+ return None
502
+
503
+
504
+ def _extract_chunk(
505
+ passage: PassageChunk,
506
+ schema: IngestionSchema,
507
+ llm_fn: Optional[Callable] = None,
508
+ use_regex: bool = True,
509
+ strategy: Optional[ContentStrategy] = None,
510
+ ) -> ChunkExtraction:
511
+ """Extract entities, facts, relationships from a single passage.
512
+
513
+ Phase A: LLM extraction (local Ollama or cloud), with strategy hints
514
+ Phase B: Regex supplement + strategy-specific fact patterns
515
+ Merge results.
516
+ """
517
+ text = passage.content
518
+ extraction = ChunkExtraction(chunk_index=passage.chunk_index)
519
+
520
+ # Phase A: LLM extraction (with strategy hints appended to prompt)
521
+ llm_nodes = []
522
+ llm_edges = []
523
+ if llm_fn:
524
+ try:
525
+ # Temporarily add strategy hints to schema for prompt building
526
+ if strategy:
527
+ original_hints = schema.field_hints.get("_strategy_hints", "")
528
+ schema.field_hints["_strategy_hints"] = strategy.get_extraction_hints()
529
+ result = llm_extract(text, schema, llm_fn=llm_fn)
530
+ if strategy:
531
+ schema.field_hints["_strategy_hints"] = original_hints # restore
532
+ if isinstance(result, tuple):
533
+ llm_nodes, llm_edges = result
534
+ else:
535
+ llm_nodes = result
536
+ except Exception as e:
537
+ logger.warning("LLM extraction failed for chunk %d: %s", passage.chunk_index, e)
538
+
539
+ # Phase B: Regex extraction
540
+ regex_nodes = []
541
+ if use_regex:
542
+ try:
543
+ regex_nodes = regex_extract(text, schema)
544
+ except Exception as e:
545
+ logger.warning("Regex extraction failed for chunk %d: %s", passage.chunk_index, e)
546
+
547
+ # Phase C: Strategy-specific fact patterns (extract facts regex missed)
548
+ strategy_facts = []
549
+ if strategy:
550
+ for pattern in strategy.get_fact_patterns():
551
+ for match in pattern.findall(text):
552
+ match = match.strip()
553
+ if len(match) > 15:
554
+ strategy_facts.append({
555
+ "label": "Fact",
556
+ "properties": {
557
+ "name": match[:80],
558
+ "statement": match,
559
+ "confidence": 0.7,
560
+ "_extraction_method": "strategy_pattern",
561
+ },
562
+ })
563
+
564
+ # Merge
565
+ if llm_nodes and regex_nodes:
566
+ merged_nodes = merge_extractions(regex_nodes, llm_nodes)
567
+ elif llm_nodes:
568
+ merged_nodes = llm_nodes
569
+ else:
570
+ merged_nodes = regex_nodes
571
+
572
+ # Add strategy-extracted facts (dedup by statement + substring check)
573
+ existing_statements = {n.get("properties", {}).get("statement", "").lower() for n in merged_nodes if n.get("label") == "Fact"}
574
+ for sf in strategy_facts:
575
+ stmt = sf["properties"].get("statement", "").lower()
576
+ if not stmt:
577
+ continue
578
+ # Skip if exact duplicate or substring of an existing fact
579
+ if stmt in existing_statements:
580
+ continue
581
+ is_substring = any(stmt in existing or existing in stmt for existing in existing_statements if existing)
582
+ if is_substring:
583
+ continue
584
+ if stmt:
585
+ merged_nodes.append(sf)
586
+ existing_statements.add(stmt)
587
+
588
+ # Separate entities and facts
589
+ for node in merged_nodes:
590
+ label = node.get("label", "")
591
+ if label == "Fact":
592
+ extraction.facts.append(node)
593
+ else:
594
+ extraction.entities.append(node)
595
+
596
+ # Relationships from LLM + co-occurrence inference
597
+ extraction.relationships = list(llm_edges) if llm_edges else []
598
+
599
+ # Infer additional edges from co-occurrence in text (schema-driven)
600
+ try:
601
+ from .schema_extractor import infer_edges
602
+ inferred = infer_edges(extraction.entities, text, schema)
603
+ if inferred:
604
+ # Dedup against LLM edges
605
+ existing_keys = set()
606
+ for rel in extraction.relationships:
607
+ k = f"{rel.get('label', '')}:{rel.get('source_name', '').lower()}:{rel.get('target_name', '').lower()}"
608
+ existing_keys.add(k)
609
+ for edge in inferred:
610
+ k = f"{edge['label']}:{edge['source_name'].lower()}:{edge['target_name'].lower()}"
611
+ if k not in existing_keys:
612
+ extraction.relationships.append(edge)
613
+ except Exception:
614
+ pass
615
+
616
+ return extraction
617
+
618
+
619
+ def _embed_nodes(result: BuildResult, db, namespace: str = ""):
620
+ """Embed passages + entities into vector store."""
621
+ try:
622
+ from ..context.vector_integration import get_session_vector_store
623
+ svs = get_session_vector_store()
624
+ if not svs or not svs.available:
625
+ logger.warning("Vector store or embedding service not available — skipping embedding")
626
+ return
627
+
628
+ ns = namespace or db.name
629
+ embedded_count = 0
630
+
631
+ # Embed passages
632
+ for pid in result.passage_ids:
633
+ node = db.csr_adapter.get_node(pid)
634
+ if node:
635
+ text = node.properties.get("content", "")
636
+ if text:
637
+ try:
638
+ ok = svs.add_text(ns, text, pid, metadata={
639
+ "label": "Passage",
640
+ "name": node.properties.get("name", ""),
641
+ "chunk_index": node.properties.get("chunk_index", 0),
642
+ "node_id": pid,
643
+ })
644
+ if ok:
645
+ node.properties["_embedded"] = True
646
+ db.csr_adapter.update_node_properties(pid, node.properties)
647
+ embedded_count += 1
648
+ except Exception as e:
649
+ logger.warning("Failed to embed passage %s: %s", pid[:12], e)
650
+
651
+ # Embed entities
652
+ for key, eid in result.entity_ids.items():
653
+ node = db.csr_adapter.get_node(eid)
654
+ if node:
655
+ name = node.properties.get("name", "")
656
+ desc = node.properties.get("description", node.properties.get("role", ""))
657
+ text = f"{name}. {desc}" if desc else name
658
+ if text:
659
+ try:
660
+ ok = svs.add_text(ns, text, eid, metadata={
661
+ "label": node.label if hasattr(node, 'label') else node.node_type,
662
+ "name": name,
663
+ "node_id": eid,
664
+ })
665
+ if ok:
666
+ node.properties["_embedded"] = True
667
+ db.csr_adapter.update_node_properties(eid, node.properties)
668
+ embedded_count += 1
669
+ except Exception as e:
670
+ logger.warning("Failed to embed entity %s: %s", eid[:12], e)
671
+
672
+ logger.info("Embedded %d/%d nodes", embedded_count,
673
+ len(result.passage_ids) + len(result.entity_ids))
674
+
675
+ except Exception as e:
676
+ logger.warning("Embedding stage failed: %s", e)
677
+
678
+
679
+ def _compute_semantic_neighbors(result: BuildResult, db, graph_name: str, limit: int = 5):
680
+ """For each embedded node, find top-k semantic neighbors via Qdrant and store in LMDB."""
681
+ try:
682
+ from ..search.lmdb_index import get_lmdb_index
683
+ from ..search.embedding_cache import get_embedding_cache
684
+ from ..context.vector_integration import get_session_vector_store
685
+
686
+ svs = get_session_vector_store()
687
+ if not svs or not svs.available:
688
+ return
689
+
690
+ lmdb_idx = get_lmdb_index(graph_name)
691
+ adapter = getattr(db, 'csr_adapter', None) or db
692
+ cache = get_embedding_cache()
693
+ stored = 0
694
+
695
+ all_ids = list(result.passage_ids.values()) + list(result.entity_ids.values())
696
+ for nid in all_ids:
697
+ try:
698
+ node = adapter.get_node(nid)
699
+ if not node or not (node.properties or {}).get("_embedded"):
700
+ continue
701
+
702
+ text = (node.properties or {}).get("content") or (node.properties or {}).get("statement") or (node.properties or {}).get("name", "")
703
+ if not text or len(text) < 10:
704
+ continue
705
+
706
+ # Search for semantic neighbors
707
+ neighbors = svs.search(graph_name, text, k=limit + 1)
708
+ neighbor_ids = [h["node_id"] for h in neighbors if h.get("node_id") != nid][:limit]
709
+
710
+ if neighbor_ids:
711
+ lmdb_idx.store_neighbors(nid, neighbor_ids)
712
+ stored += 1
713
+ except Exception:
714
+ continue
715
+
716
+ if stored:
717
+ logger.info("[SEMANTIC] Stored neighbors for %d nodes in LMDB", stored)
718
+ except Exception as e:
719
+ logger.debug("[SEMANTIC] Neighbor computation failed: %s", e)
720
+
721
+
722
+ def _assemble_context_units(result, db, graph_name, schema_name: str = ""):
723
+ """Incrementally add new facts to existing Context Units.
724
+
725
+ On each ingestion:
726
+ - If NO CUs exist: build from scratch (full graph clustering)
727
+ - If CUs exist: add new facts to the nearest existing CU by keyword match
728
+ - Full rebuild only happens via explicit backfill or when CU count = 0
729
+
730
+ This keeps ingestion fast (<100ms for CU step) instead of re-clustering
731
+ all facts on every document (which takes 18s+ on large graphs).
732
+ """
733
+ try:
734
+ from ..context.context_units import cluster_facts_for_cus, build_context_unit, _tokenize
735
+ from ..search.lmdb_index import get_lmdb_index
736
+ from ..core.hybrid_graph_storage import GraphNode, GraphEdge
737
+ import uuid as _uuid
738
+
739
+ # Resolve domain-specific CU config from schema (if available)
740
+ cu_config = None
741
+ if schema_name:
742
+ try:
743
+ from ..extraction.schema_loader import load_schema as _load_extraction_schema
744
+ from pathlib import Path as _Path
745
+ _schema_path = _Path(__file__).parent.parent / "config" / "schemas" / f"{schema_name}.yaml"
746
+ if _schema_path.exists():
747
+ _ext_schema = _load_extraction_schema(str(_schema_path))
748
+ cu_config = _ext_schema.context_unit
749
+ except Exception:
750
+ pass
751
+
752
+ lmdb_idx = get_lmdb_index(graph_name)
753
+
754
+ # Determine which node labels to include in CU clustering.
755
+ # Default: only Fact nodes. With domain schema: also priority_labels types.
756
+ cu_labels = {"Fact"}
757
+ if cu_config is not None:
758
+ priority = getattr(cu_config, "priority_labels", [])
759
+ if priority:
760
+ cu_labels.update(priority)
761
+
762
+ # Load new claimable nodes from this batch (facts + domain entities)
763
+ adapter = getattr(db, 'csr_adapter', None) or db
764
+ new_facts = []
765
+
766
+ # From fact_ids
767
+ fact_id_values = result.fact_ids if isinstance(result.fact_ids, dict) else {i: v for i, v in enumerate(result.fact_ids)}
768
+ for fid in fact_id_values.values():
769
+ try:
770
+ node = adapter.get_node(fid)
771
+ if node:
772
+ props = node.properties or {}
773
+ if props.get("statement") or props.get("name") or props.get("description"):
774
+ new_facts.append({"id": fid, "label": "Fact", "properties": props})
775
+ except Exception:
776
+ pass
777
+
778
+ # From entity_ids — include domain entities that match priority_labels
779
+ if len(cu_labels) > 1: # has domain labels beyond just "Fact"
780
+ for eid in result.entity_ids.values():
781
+ try:
782
+ node = adapter.get_node(eid)
783
+ if node:
784
+ label = getattr(node, "node_type", None) or getattr(node, "label", "")
785
+ if label in cu_labels:
786
+ props = node.properties or {}
787
+ # Normalize: use name/description as statement for clustering
788
+ if not props.get("statement"):
789
+ desc = props.get("description", "")
790
+ name = props.get("name", "")
791
+ props = dict(props) # copy
792
+ props["statement"] = f"{name}: {desc}" if desc else name
793
+ new_facts.append({"id": eid, "label": label, "properties": props})
794
+ except Exception:
795
+ pass
796
+
797
+ logger.info("[CU] Domain labels: %s | New claimable nodes: %d", cu_labels, len(new_facts))
798
+
799
+ # Check if CUs already exist
800
+ existing_cus = list(db.get_all_nodes(label="ContextUnit"))
801
+
802
+ # Skip only if no new nodes AND CUs already exist (nothing to do)
803
+ if len(new_facts) < 1 and existing_cus:
804
+ return
805
+ # If no new nodes but also no CUs, fall through to full graph scan below
806
+
807
+ if not existing_cus:
808
+ # No CUs yet — build from scratch using ALL eligible nodes in the graph
809
+ all_facts = []
810
+ for label in cu_labels:
811
+ for node in db.get_all_nodes(label=label):
812
+ props = node.properties if hasattr(node, 'properties') else {}
813
+ if props.get("statement") or props.get("name") or props.get("description"):
814
+ p = dict(props)
815
+ if not p.get("statement"):
816
+ desc = p.get("description", "")
817
+ name = p.get("name", "")
818
+ p["statement"] = f"{name}: {desc}" if desc else name
819
+ all_facts.append({"id": node.id, "label": label, "properties": p})
820
+
821
+ logger.info("[CU] Full build: %d eligible nodes across labels %s", len(all_facts), cu_labels)
822
+ if len(all_facts) < 3:
823
+ return
824
+
825
+ clusters = cluster_facts_for_cus(all_facts, min_cluster_size=3, db=db)
826
+ logger.info("[CU] Clustered into %d groups", len(clusters))
827
+ for cluster in clusters:
828
+ cu = build_context_unit(topic=cluster["topic"], facts=cluster["facts"], entities=[], use_llm=False, cu_config=cu_config)
829
+ db.add_node(GraphNode(id=cu["id"], label="ContextUnit", properties=cu["properties"]))
830
+ for fid in cu["evidence_ids"]:
831
+ db.add_edge(GraphEdge(id=str(_uuid.uuid4()), source=cu["id"], target=fid, label="HAS_EVIDENCE", properties={}))
832
+ lmdb_idx.index_node(cu["id"], "ContextUnit", cu["properties"])
833
+
834
+ if clusters:
835
+ logger.info("[CU] Initial build: %d CUs from %d facts", len(clusters), len(all_facts))
836
+ else:
837
+ # CUs exist — assign new facts to the nearest CU by keyword overlap
838
+ # Build CU topic → CU mapping
839
+ cu_topics = {}
840
+ for cu_node in existing_cus:
841
+ props = cu_node.properties if hasattr(cu_node, 'properties') else {}
842
+ topic = props.get("topic", "")
843
+ cu_id = cu_node.id if hasattr(cu_node, 'id') else ""
844
+ if topic and cu_id:
845
+ cu_topics[cu_id] = set(_tokenize(topic))
846
+
847
+ assigned = 0
848
+ for fact in new_facts:
849
+ stmt = fact["properties"].get("statement", "")
850
+ fact_tokens = set(_tokenize(stmt))
851
+ if not fact_tokens:
852
+ continue
853
+
854
+ # Find best matching CU by keyword overlap
855
+ best_cu = None
856
+ best_score = 0
857
+ for cu_id, topic_tokens in cu_topics.items():
858
+ score = len(fact_tokens & topic_tokens)
859
+ if score > best_score:
860
+ best_score = score
861
+ best_cu = cu_id
862
+
863
+ if best_cu and best_score > 0:
864
+ # Check for duplicate edge before adding
865
+ already_linked = False
866
+ try:
867
+ existing_edges = adapter.get_edges_from(best_cu) if hasattr(adapter, 'get_edges_from') else []
868
+ for e in existing_edges:
869
+ if getattr(e, 'target', '') == fact["id"] and getattr(e, 'label', '') == "HAS_EVIDENCE":
870
+ already_linked = True
871
+ break
872
+ except Exception:
873
+ pass
874
+ if not already_linked:
875
+ db.add_edge(GraphEdge(
876
+ id=str(_uuid.uuid4()), source=best_cu, target=fact["id"],
877
+ label="HAS_EVIDENCE", properties={},
878
+ ))
879
+ assigned += 1
880
+
881
+ if assigned:
882
+ logger.info("[CU] Incremental: assigned %d new facts to existing CUs", assigned)
883
+
884
+ # Trigger full rebuild if too many facts have been added incrementally
885
+ # Track via a counter on the graph metadata
886
+ try:
887
+ import redis as _redis_mod
888
+ import os as _os
889
+ _r = _redis_mod.from_url(_os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL", "redis://localhost:6379"))
890
+ counter_key = f"cu_incremental_count:{graph_name}"
891
+ current = _r.incrby(counter_key, len(new_facts))
892
+ rebuild_threshold = 50 # Full re-cluster after 50 new facts
893
+
894
+ if current >= rebuild_threshold:
895
+ _r.set(counter_key, 0)
896
+ logger.info("[CU] Threshold reached (%d facts since last rebuild) — triggering full re-cluster", current)
897
+
898
+ # Delete old CUs and their HAS_EVIDENCE edges
899
+ try:
900
+ old_cu_ids = [cu.id for cu in existing_cus if hasattr(cu, 'id')]
901
+ for old_id in old_cu_ids:
902
+ try:
903
+ adapter.remove_node(old_id)
904
+ except Exception:
905
+ pass
906
+ logger.info("[CU] Deleted %d old CUs before rebuild", len(old_cu_ids))
907
+ except Exception:
908
+ pass
909
+
910
+ # Full rebuild — include domain entity types if schema has priority_labels
911
+ all_facts = []
912
+ for _lbl in cu_labels:
913
+ for node in db.get_all_nodes(label=_lbl):
914
+ props = node.properties if hasattr(node, 'properties') else {}
915
+ if props.get("statement") or props.get("name") or props.get("description"):
916
+ p = dict(props)
917
+ if not p.get("statement"):
918
+ desc = p.get("description", "")
919
+ name = p.get("name", "")
920
+ p["statement"] = f"{name}: {desc}" if desc else name
921
+ all_facts.append({"id": node.id, "label": _lbl, "properties": p})
922
+
923
+ if len(all_facts) >= 3:
924
+ import threading
925
+ def _rebuild():
926
+ try:
927
+ clusters = cluster_facts_for_cus(all_facts, min_cluster_size=3, db=db)
928
+ for cluster in clusters:
929
+ cu = build_context_unit(topic=cluster["topic"], facts=cluster["facts"], entities=[], use_llm=False, cu_config=cu_config)
930
+ db.add_node(GraphNode(id=cu["id"], label="ContextUnit", properties=cu["properties"]))
931
+ for fid in cu["evidence_ids"]:
932
+ db.add_edge(GraphEdge(id=str(_uuid.uuid4()), source=cu["id"], target=fid, label="HAS_EVIDENCE", properties={}))
933
+ lmdb_idx.index_node(cu["id"], "ContextUnit", cu["properties"])
934
+ logger.info("[CU] Full rebuild complete: %d CUs from %d facts", len(clusters), len(all_facts))
935
+ except Exception as _e:
936
+ logger.warning("[CU] Background rebuild failed: %s", _e)
937
+
938
+ threading.Thread(target=_rebuild, daemon=True, name="cu-rebuild").start()
939
+ except Exception:
940
+ pass # Redis not available — skip threshold tracking
941
+
942
+ except Exception as e:
943
+ logger.debug("[CU] Assembly failed: %s", e)
944
+
945
+
946
+ def _index_bm25(result: BuildResult, db):
947
+ """Update BM25 index (LMDB + legacy Whoosh) with new nodes."""
948
+ # LMDB incremental update — index only new nodes, not full rebuild
949
+ try:
950
+ from ..search.lmdb_index import get_lmdb_index
951
+ graph_name = getattr(db, '_namespace', '') or getattr(db, 'namespace', '') or getattr(db, 'name', 'default')
952
+ lmdb_idx = get_lmdb_index(graph_name)
953
+ adapter = getattr(db, 'csr_adapter', None) or db
954
+ batch = []
955
+ for nid in list(result.passage_ids.values()) + list(result.entity_ids.values()) + list(result.fact_ids.values()):
956
+ try:
957
+ node = adapter.get_node(nid)
958
+ if node:
959
+ batch.append({
960
+ "id": nid,
961
+ "label": getattr(node, 'label', getattr(node, 'node_type', '')),
962
+ "properties": node.properties or {},
963
+ })
964
+ except Exception:
965
+ pass
966
+ if batch:
967
+ lmdb_idx.index_batch(batch)
968
+
969
+ # Store full passages
970
+ for nid in result.passage_ids.values():
971
+ try:
972
+ node = adapter.get_node(nid)
973
+ if node:
974
+ text = (node.properties or {}).get("content", "")
975
+ if text:
976
+ lmdb_idx.store_passage(nid, text)
977
+ except Exception:
978
+ pass
979
+
980
+ # Store edges for graph expansion
981
+ all_nids = list(result.passage_ids.values()) + list(result.entity_ids.values()) + list(result.fact_ids.values())
982
+ for nid in all_nids:
983
+ try:
984
+ edges_out = adapter.get_edges_for_node(nid) if hasattr(adapter, 'get_edges_for_node') else []
985
+ edge_list = []
986
+ for e in edges_out[:20]:
987
+ target_id = e.target if hasattr(e, 'target') else e.get('target', '')
988
+ if target_id == nid:
989
+ target_id = e.source if hasattr(e, 'source') else e.get('source', '')
990
+ try:
991
+ target = adapter.get_node(target_id)
992
+ if target:
993
+ t_name = (target.properties or {}).get("name", "")
994
+ t_label = getattr(target, 'label', getattr(target, 'node_type', ''))
995
+ if t_name:
996
+ edge_list.append({
997
+ "target_id": target_id, "target_name": t_name,
998
+ "target_type": t_label,
999
+ "label": e.label if hasattr(e, 'label') else e.get('label', ''),
1000
+ })
1001
+ except Exception:
1002
+ pass
1003
+ if edge_list:
1004
+ lmdb_idx.store_edges(nid, edge_list)
1005
+ except Exception:
1006
+ pass
1007
+
1008
+ logger.info("[LMDB] Indexed %d nodes + passages + edges for %s", len(batch), graph_name)
1009
+ except Exception as e:
1010
+ logger.debug("[LMDB] Incremental index failed: %s", e)
1011
+
1012
+ # Legacy Whoosh rebuild
1013
+ try:
1014
+ from ..core.graph_intelligence import build_indexes
1015
+ stats = build_indexes(db, namespace=db.name)
1016
+ logger.info("BM25 indexes rebuilt for %s: %s", db.name, stats)
1017
+ except Exception as e:
1018
+ logger.warning("BM25 indexing failed: %s", e)
1019
+
1020
+
1021
+ def ingest_url(
1022
+ url: str,
1023
+ db,
1024
+ schema: Optional[IngestionSchema] = None,
1025
+ pipeline: str = "smart_article",
1026
+ mode: str = "auto",
1027
+ filter_config: Optional[FilterConfig] = None,
1028
+ strategy: Optional[str] = None,
1029
+ on_stage: Optional[Callable] = None,
1030
+ debug: bool = False,
1031
+ owner: str = "",
1032
+ context_purpose: str = "",
1033
+ ):
1034
+ """Ingest a web page URL into a rich knowledge graph.
1035
+
1036
+ Runs all 7 stages: Clean -> Chunk -> Extract -> Link -> Embed -> Index -> Validate.
1037
+
1038
+ Args:
1039
+ url: Web page URL to ingest.
1040
+ db: AIContextDB instance (target graph).
1041
+ schema: Optional IngestionSchema. If None, loads from graph's ContextMeta.
1042
+ pipeline: Pipeline name (smart_article, smart_text, fast_ingest).
1043
+ mode: "auto" (commit immediately) or "review" (return StagingResult for preview).
1044
+ filter_config: Optional FilterConfig for content filtering.
1045
+ on_stage: Optional callback(stage_name, details) for progress tracking.
1046
+
1047
+ Returns:
1048
+ mode="auto": BuildResult with all created node/edge IDs.
1049
+ mode="review": StagingResult with preview (not committed).
1050
+ """
1051
+ if not schema:
1052
+ schema = load_schema(db)
1053
+
1054
+ llm_fn = _get_llm_fn(db) if pipeline != "fast_ingest" else None
1055
+
1056
+ # Stage 1: Clean
1057
+ if on_stage:
1058
+ on_stage("clean", {"url": url, "message": f"Fetching and cleaning {url}"})
1059
+ clean_doc = clean_webpage(url)
1060
+ if not clean_doc.body:
1061
+ if on_stage:
1062
+ on_stage("clean_failed", {"message": f"No content extracted from {url}"})
1063
+ return BuildResult(errors=[f"No content extracted from {url}"])
1064
+ if on_stage:
1065
+ on_stage("clean_done", {"message": f"Extracted: '{clean_doc.title}' ({clean_doc.word_count} words, {len(clean_doc.links)} links)"})
1066
+
1067
+ # Stage 0: Content Fingerprint Dedup (Layer 1) — reject exact duplicates early
1068
+ try:
1069
+ fp = _get_content_fingerprint()
1070
+ dedup_result = fp.check(clean_doc.body, url=url)
1071
+ if dedup_result.status == "exact_duplicate":
1072
+ if on_stage:
1073
+ on_stage("dedup_rejected", {"status": "exact_duplicate", "url": url})
1074
+ logger.info("[DEDUP] Rejected exact duplicate: %s", url)
1075
+ return BuildResult(errors=[f"Duplicate content (already ingested)"])
1076
+ elif dedup_result.status == "content_changed":
1077
+ if on_stage:
1078
+ on_stage("dedup_versioned", {"status": "content_changed", "url": url})
1079
+ logger.info("[DEDUP] Content changed for URL %s — versioning", url)
1080
+ except Exception as exc:
1081
+ logger.warning("[DEDUP] Fingerprint check failed (non-fatal): %s", exc)
1082
+
1083
+ # Auto-classify sensitivity
1084
+ from ..security.auto_tagger import AutoTagger
1085
+ _tagger = AutoTagger()
1086
+ _classification = _tagger.classify_text(clean_doc.body[:3000])
1087
+ sensitivity = _classification.sensitivity # "public" | "internal" | "confidential" | "restricted"
1088
+
1089
+ # Structural pre-filter (cheap, catches CSV/code/JSON mismatches before LLM)
1090
+ if filter_config:
1091
+ struct_result = structural_pre_filter(clean_doc.body[:2000], filter_config, schema=schema)
1092
+ if struct_result and struct_result.status == "filtered":
1093
+ if on_stage:
1094
+ on_stage("filter_structural", {"status": "filtered", "reason": struct_result.reason})
1095
+ return BuildResult(errors=[f"Filtered (structural): {struct_result.reason}"])
1096
+
1097
+ # Filter chain (if configured)
1098
+ if filter_config:
1099
+ if on_stage:
1100
+ on_stage("filter", {"config": "active"})
1101
+ debug_log = [] if debug else None
1102
+ f_result = filter_chain(clean_doc.title, clean_doc.body, filter_config,
1103
+ llm_fn=llm_fn, embed_fn=_get_embed_fn(), debug_log=debug_log)
1104
+ if debug_log and on_stage:
1105
+ on_stage("filter_debug", {"filter_decisions": debug_log, "result": f_result.status, "reason": f_result.reason})
1106
+ if f_result.status == "filtered":
1107
+ logger.info("Filtered: %s — %s", clean_doc.title, f_result.reason)
1108
+ if mode == "review":
1109
+ staging = StagingResult(
1110
+ staging_id=str(_uuid.uuid4()),
1111
+ filter_log=[{"url": url, "title": clean_doc.title, "status": "filtered", "reason": f_result.reason}],
1112
+ created_at=datetime.now(timezone.utc).isoformat(),
1113
+ )
1114
+ _staging_store[staging.staging_id] = staging
1115
+ return staging
1116
+ return BuildResult(errors=[f"Filtered: {f_result.reason}"])
1117
+ if f_result.status == "review" and mode == "auto":
1118
+ mode = "review" # force review for borderline content
1119
+
1120
+ # Resolve content strategy early (needed for chunk method + extraction hints)
1121
+ # Priority: explicit strategy arg → pipeline's content_strategy → news_article default
1122
+ if strategy:
1123
+ content_strategy = get_strategy(strategy)
1124
+ else:
1125
+ _pipeline_def = PIPELINES.get(pipeline) or PIPELINES.get(_PIPELINE_ALIASES.get(pipeline, ""), {})
1126
+ _strategy_name = (_pipeline_def.get("content_strategy", "news_article") if _pipeline_def else "news_article")
1127
+ content_strategy = get_strategy(_strategy_name)
1128
+ chunk_method = content_strategy.chunk_config.method
1129
+
1130
+ # Stage 2: Chunk
1131
+ if on_stage:
1132
+ on_stage("chunk", {
1133
+ "message": f"Chunking {clean_doc.word_count} words into passages",
1134
+ "chunk_strategy": chunk_method,
1135
+ "content_strategy": content_strategy.name,
1136
+ "token_limits": f"min={content_strategy.chunk_config.min_tokens} max={content_strategy.chunk_config.max_tokens} target={content_strategy.chunk_config.target_tokens}",
1137
+ })
1138
+ link_dicts = [{"url": l.url, "anchor": l.anchor} for l in clean_doc.links]
1139
+ cc = content_strategy.chunk_config
1140
+ chunks = chunk_document(
1141
+ clean_doc.body,
1142
+ links=link_dicts,
1143
+ method=chunk_method,
1144
+ overlap_sentences=cc.overlap_sentences,
1145
+ min_tokens=cc.min_tokens,
1146
+ max_tokens=cc.max_tokens,
1147
+ target_tokens=cc.target_tokens,
1148
+ )
1149
+ if not chunks:
1150
+ if on_stage:
1151
+ on_stage("chunk_failed", {"message": "No chunks produced — content may be too short or empty"})
1152
+ return BuildResult(errors=["No chunks produced"])
1153
+ avg_chars = sum(len(getattr(c, 'content', None) or getattr(c, 'body', '') or '') for c in chunks) // len(chunks)
1154
+ if on_stage:
1155
+ on_stage("chunk_done", {"message": f"Produced {len(chunks)} chunks (avg {avg_chars} chars each)",
1156
+ "chunk_count": len(chunks), "avg_chars": avg_chars})
1157
+ logger.info("Chunked: %d passages (avg %d chars)", len(chunks), avg_chars)
1158
+
1159
+ # Stage 2b: Semantic Dedup (Layer 2) — catch rewritten duplicates via embedding similarity
1160
+ try:
1161
+ _embed_fn_dedup = _get_embed_fn()
1162
+ if _embed_fn_dedup and chunks:
1163
+ sd = _get_semantic_dedup()
1164
+ first_chunk_text = chunks[0].content if hasattr(chunks[0], 'content') else chunks[0].body
1165
+ first_embedding = _embed_fn_dedup(first_chunk_text[:500])
1166
+ sem_result = sd.check(first_embedding, text=first_chunk_text)
1167
+ if sem_result.status == "semantic_duplicate":
1168
+ if on_stage:
1169
+ on_stage("dedup_semantic", {"status": "semantic_duplicate", "similarity": sem_result.similarity})
1170
+ logger.info("[DEDUP] Semantic duplicate detected (similarity=%.2f) — rejecting", sem_result.similarity)
1171
+ return BuildResult(errors=[f"Semantic duplicate (similarity={sem_result.similarity:.2f})"])
1172
+ elif sem_result.status == "factual_update":
1173
+ # Numbers changed — this is a correction/update, not a duplicate
1174
+ # Proceed with ingestion (time-travel will version it)
1175
+ if on_stage:
1176
+ on_stage("dedup_factual_update", {"status": "factual_update", "similarity": sem_result.similarity, "numbers_changed": True})
1177
+ logger.info("[DEDUP] Factual update detected (similarity=%.2f, numbers changed) — versioning", sem_result.similarity)
1178
+ elif sem_result.status == "related_coverage":
1179
+ if on_stage:
1180
+ on_stage("dedup_related", {"status": "related_coverage", "similarity": sem_result.similarity})
1181
+ logger.info("[DEDUP] Related coverage detected (similarity=%.2f) — proceeding with extraction", sem_result.similarity)
1182
+ # Register this content's embedding + text for future dedup
1183
+ sd.add(first_embedding, doc_id=url or clean_doc.title, text=first_chunk_text)
1184
+ except Exception as exc:
1185
+ logger.warning("[DEDUP] Semantic dedup failed (non-fatal): %s", exc)
1186
+
1187
+ # Stage 3: Extract (per chunk)
1188
+ if on_stage:
1189
+ on_stage("extract", {"message": f"Extracting entities/facts from {len(chunks)} passages (LLM: {'yes' if llm_fn else 'no'}, strategy: {content_strategy.name})"})
1190
+ extractions = []
1191
+ for chunk in chunks:
1192
+ ext = _extract_chunk(chunk, schema, llm_fn=llm_fn, use_regex=True, strategy=content_strategy)
1193
+ extractions.append(ext)
1194
+ total_entities = sum(len(e.entities) for e in extractions)
1195
+ total_facts = sum(len(e.facts) for e in extractions)
1196
+ logger.info("Extracted: %d entities, %d facts across %d chunks", total_entities, total_facts, len(chunks))
1197
+
1198
+ # Stage 3a: Quality Amplifier — score relevance against context purpose
1199
+ _embed_fn = _get_embed_fn()
1200
+ if context_purpose and _embed_fn:
1201
+ if on_stage:
1202
+ on_stage("amplify", {"message": f"Scoring {total_entities} entities + {total_facts} facts for relevance"})
1203
+ amp_result = amplify_extractions(
1204
+ extractions=extractions,
1205
+ context_purpose=context_purpose,
1206
+ embed_fn=_embed_fn,
1207
+ )
1208
+ if on_stage:
1209
+ on_stage("amplify_done", amp_result.stats)
1210
+ logger.info("[AMPLIFIER] %s", amp_result.stats)
1211
+
1212
+ # Stage 3b: Intelligence Tagger — sentiment, geography, domain, category, impact
1213
+ try:
1214
+ _llm_fn_for_tags = llm_fn or _get_llm_fn()
1215
+ chunk_texts = [c.content if hasattr(c, 'content') else c.body for c in chunks]
1216
+ if on_stage:
1217
+ on_stage("intelligence_tag", {"message": f"Tagging {len(chunks)} chunks with intelligence dimensions"})
1218
+ tag_result = _tag_extractions(
1219
+ extractions=extractions,
1220
+ chunk_texts=chunk_texts,
1221
+ llm_fn=_llm_fn_for_tags,
1222
+ )
1223
+ _apply_intelligence_tags(extractions, tag_result, chunk_texts)
1224
+ if on_stage:
1225
+ on_stage("intelligence_tag_done", tag_result.stats)
1226
+ logger.info("[TAGGER] %s", tag_result.stats)
1227
+ except Exception as exc:
1228
+ logger.warning("[TAGGER] Intelligence tagging failed (non-fatal): %s", exc)
1229
+
1230
+ # Stage 3c: Correlation Signals — fire on-ingest signals from templates
1231
+ try:
1232
+ from ..intelligence.correlation_engine import CorrelationEngine
1233
+ from ..intelligence.correlation_template import list_templates, load_template
1234
+ _corr_engine = CorrelationEngine()
1235
+ for tmpl_name in list_templates():
1236
+ tmpl = load_template(tmpl_name)
1237
+ if tmpl:
1238
+ _corr_engine.register_template_object(tmpl)
1239
+
1240
+ # Build entity list for signal processing
1241
+ _signal_entities = []
1242
+ for ext in extractions:
1243
+ for ent in ext.entities:
1244
+ props = ent.get("properties", {})
1245
+ _signal_entities.append({
1246
+ "name": props.get("name", ""),
1247
+ "label": ent.get("label", "Entity"),
1248
+ "_sentiment": props.get("_sentiment", "neutral"),
1249
+ })
1250
+
1251
+ for tmpl_name in _corr_engine.list_registered():
1252
+ tmpl = _corr_engine.get_template(tmpl_name)
1253
+ if tmpl:
1254
+ signals = _corr_engine.process_ingest(_signal_entities, tmpl)
1255
+ if signals:
1256
+ if on_stage:
1257
+ on_stage("correlation_signals", {
1258
+ "template": tmpl_name,
1259
+ "signals_fired": len(signals),
1260
+ "signals": [{"type": s.type, "entity": s.entity_name, "severity": s.severity} for s in signals[:5]],
1261
+ })
1262
+ logger.info("[CORR] %d signals fired from template '%s'", len(signals), tmpl_name)
1263
+
1264
+ # Stage 3d: Reactive — trigger pipeline actions from signals
1265
+ try:
1266
+ from ..intelligence.reactive import ReactiveController
1267
+ _reactive = ReactiveController()
1268
+ _reactive.add_default_rules()
1269
+ graph_name = getattr(db, '_namespace', '') or getattr(db, 'namespace', '') or 'default'
1270
+ for sig in signals:
1271
+ reactions = _reactive.react(sig, graph_name)
1272
+ if reactions and on_stage:
1273
+ on_stage("reactive", {
1274
+ "reactions": [r.to_dict() for r in reactions[:3]],
1275
+ })
1276
+ except Exception as react_exc:
1277
+ logger.debug("[REACTIVE] Reaction processing failed: %s", react_exc)
1278
+
1279
+ except Exception as exc:
1280
+ logger.warning("[CORR] Correlation signal processing failed (non-fatal): %s", exc)
1281
+
1282
+ # REVIEW MODE: pause here and return preview
1283
+ if mode == "review":
1284
+ # Build preview data
1285
+ passage_previews = [
1286
+ {"content": c.content[:200], "token_count": c.token_count, "chunk_index": c.chunk_index,
1287
+ "_staging_id": f"p_{i}"}
1288
+ for i, c in enumerate(chunks)
1289
+ ]
1290
+ entity_previews = []
1291
+ fact_previews = []
1292
+ edge_previews = []
1293
+ sid = 0
1294
+ for ext in extractions:
1295
+ for e in ext.entities:
1296
+ e["_staging_id"] = f"e_{sid}"
1297
+ entity_previews.append({
1298
+ "label": e.get("label", "Entity"),
1299
+ "name": e.get("properties", {}).get("name", ""),
1300
+ "properties": e.get("properties", {}),
1301
+ "_staging_id": e["_staging_id"],
1302
+ })
1303
+ sid += 1
1304
+ for f in ext.facts:
1305
+ f["_staging_id"] = f"f_{sid}"
1306
+ fact_previews.append({
1307
+ "statement": f.get("properties", f).get("statement", f.get("properties", f).get("name", "")),
1308
+ "_staging_id": f["_staging_id"],
1309
+ })
1310
+ sid += 1
1311
+ for r in ext.relationships:
1312
+ edge_previews.append({
1313
+ "label": r.get("label", "RELATED_TO"),
1314
+ "source": r.get("source_name", ""),
1315
+ "target": r.get("target_name", ""),
1316
+ })
1317
+
1318
+ link_previews = [{"url": l.url, "anchor": l.anchor} for l in clean_doc.links] if clean_doc.links else []
1319
+
1320
+ quality = _calc_quality(passage_previews, entity_previews, fact_previews, edge_previews)
1321
+
1322
+ # Schema suggestions — discover types not in schema
1323
+ from .graph_builder import _suggest_schema_updates
1324
+ suggestions = _suggest_schema_updates(extractions, schema) if schema else []
1325
+
1326
+ staging = StagingResult(
1327
+ staging_id=str(_uuid.uuid4()),
1328
+ clean_doc=clean_doc,
1329
+ chunks=chunks,
1330
+ extractions=extractions,
1331
+ passages=passage_previews,
1332
+ entities=entity_previews,
1333
+ facts=fact_previews,
1334
+ edges=edge_previews,
1335
+ links=link_previews,
1336
+ quality_score=quality,
1337
+ filter_log=[],
1338
+ schema_suggestions=[s.to_dict() for s in suggestions],
1339
+ schema_used=schema.name if schema else "default",
1340
+ pipeline=pipeline,
1341
+ created_at=datetime.now(timezone.utc).isoformat(),
1342
+ )
1343
+ _staging_store[staging.staging_id] = staging
1344
+ logger.info("Staged for review: %s (quality: %.0f%%, %d entities, %d facts)",
1345
+ staging.staging_id[:12], quality, len(entity_previews), len(fact_previews))
1346
+ return staging
1347
+
1348
+ # Post-extraction filter (precise, uses structured entities)
1349
+ if filter_config and (filter_config.semantic_rules or schema):
1350
+ post_result = post_extraction_filter(extractions, filter_config, schema=schema, embed_fn=_get_embed_fn())
1351
+ if post_result and post_result.status == "filtered":
1352
+ if on_stage:
1353
+ on_stage("filter_post", {"status": "filtered", "reason": post_result.reason})
1354
+ return BuildResult(errors=[f"Filtered (post-extraction): {post_result.reason}"])
1355
+
1356
+ # Stage 3b: ValidationGate — accept/quarantine/reject extracted entities
1357
+ _compiled_schema = None
1358
+ try:
1359
+ from ..schema.compiler import SchemaCompiler
1360
+ from ..schema.sdl import EnhancedSchema
1361
+ from ..schema.validation_gate import ValidationGate
1362
+ from pathlib import Path as _Path
1363
+ _schema_path = _Path(__file__).parent.parent / "config" / "schemas" / f"{schema.name}.yaml"
1364
+ if _schema_path.exists():
1365
+ import yaml
1366
+ with open(_schema_path) as _sf:
1367
+ _raw = yaml.safe_load(_sf)
1368
+ _enhanced = EnhancedSchema.from_dict(_raw)
1369
+ _compiled_schema = SchemaCompiler.compile(_enhanced)
1370
+ gate = ValidationGate(_compiled_schema)
1371
+ quarantined_count = 0
1372
+ rejected_count = 0
1373
+ for ext in extractions:
1374
+ accepted_entities = []
1375
+ for ent in ext.entities:
1376
+ verdict = gate.validate_node(ent)
1377
+ if verdict.verdict == "accept":
1378
+ accepted_entities.append(ent)
1379
+ elif verdict.verdict == "quarantine":
1380
+ ent.setdefault("properties", {})["_quarantine_reason"] = verdict.reason
1381
+ ent["properties"]["confidence"] = ent["properties"].get("confidence", 0.85) * 0.5
1382
+ accepted_entities.append(ent) # keep with penalty
1383
+ quarantined_count += 1
1384
+ else:
1385
+ rejected_count += 1
1386
+ ext.entities = accepted_entities
1387
+ if quarantined_count or rejected_count:
1388
+ logger.info("[GATE] Validation: %d quarantined, %d rejected", quarantined_count, rejected_count)
1389
+ if on_stage:
1390
+ on_stage("validate_gate", {"quarantined": quarantined_count, "rejected": rejected_count})
1391
+ except ImportError:
1392
+ pass # schema package not available — skip gate
1393
+ except Exception as e:
1394
+ logger.debug("[GATE] Validation gate skipped: %s", e)
1395
+
1396
+ # Stage 4: Link (build graph)
1397
+ if on_stage:
1398
+ on_stage("link", {"message": f"Building graph: {total_entities} entities, {total_facts} facts"})
1399
+ result = build_graph(clean_doc, chunks, extractions, db, schema, pipeline_name=pipeline,
1400
+ owner=owner, sensitivity=sensitivity, compiled_schema=_compiled_schema)
1401
+
1402
+ # Stage 5: Embed
1403
+ if on_stage:
1404
+ on_stage("embed", {"message": f"Embedding {len(result.passage_ids)} passages + {len(result.entity_ids)} entities into vector store"})
1405
+ _embed_nodes(result, db)
1406
+
1407
+ # Stage 5b: Semantic neighbors (pre-compute for LMDB hybrid search)
1408
+ graph_name = getattr(db, '_namespace', '') or getattr(db, 'namespace', '') or getattr(db, 'name', 'default')
1409
+ _compute_semantic_neighbors(result, db, graph_name)
1410
+
1411
+ # Stage 6: Index
1412
+ if on_stage:
1413
+ on_stage("index", {"message": "Building BM25 keyword search index"})
1414
+ _index_bm25(result, db)
1415
+ _assemble_context_units(result, db, graph_name, schema_name=schema.name if schema else "")
1416
+
1417
+ # Stage 6b: DerivationEngine — fire schema-defined rules against graph
1418
+ if _compiled_schema and _compiled_schema.derivation_rules:
1419
+ try:
1420
+ from ..schema.derivation import DerivationEngine
1421
+ engine = DerivationEngine(_compiled_schema.derivation_rules)
1422
+ actions = engine.evaluate(db)
1423
+ if actions:
1424
+ logger.info("[DERIVE] %d derivation actions fired", len(actions))
1425
+ if on_stage:
1426
+ on_stage("derivation", {"actions": len(actions),
1427
+ "types": [a["action"] for a in actions[:5]]})
1428
+ # Execute boost actions immediately (update projection priority)
1429
+ for action in actions:
1430
+ if action["action"] == "boost":
1431
+ nid = action.get("node_id", "")
1432
+ priority = action.get("priority", 1.5)
1433
+ if nid:
1434
+ try:
1435
+ node = db.csr_adapter.get_node(nid)
1436
+ if node:
1437
+ node.properties["_derivation_boost"] = priority
1438
+ db.csr_adapter.update_node_properties(nid, node.properties)
1439
+ except Exception:
1440
+ pass
1441
+ except ImportError:
1442
+ pass
1443
+ except Exception as e:
1444
+ logger.debug("[DERIVE] Derivation skipped: %s", e)
1445
+
1446
+ # Stage 7: Validate (legacy fallback — skipped if ValidationGate ran pre-build)
1447
+ if schema and _compiled_schema is None:
1448
+ if on_stage:
1449
+ on_stage("validate", {"message": "Validating nodes against schema + dedup check"})
1450
+ for key, eid in result.entity_ids.items():
1451
+ node = db.csr_adapter.get_node(eid)
1452
+ if node:
1453
+ node_dict = {"label": getattr(node, 'node_type', getattr(node, 'label', '')),
1454
+ "properties": dict(node.properties)}
1455
+ validated = validate_and_flag(node_dict, schema)
1456
+ for vk in ("validation_status", "validation_errors"):
1457
+ if vk in validated["properties"]:
1458
+ node.properties[vk] = validated["properties"][vk]
1459
+ db.csr_adapter.update_node_properties(eid, node.properties)
1460
+
1461
+ logger.info(
1462
+ "Ingestion complete: %s -> %d passages, %d entities, %d facts, %d links, %d edges",
1463
+ clean_doc.title[:40], len(result.passage_ids), len(result.entity_ids),
1464
+ len(result.fact_ids), len(result.link_ids), result.edge_count,
1465
+ )
1466
+
1467
+ # Rebuild context manifest (non-blocking)
1468
+ try:
1469
+ from ..context.quality import EntityIndex, ManifestBuilder
1470
+ graph_name = getattr(db, '_namespace', '') or getattr(db, 'namespace', '') or 'default'
1471
+ redis_client = None
1472
+ try:
1473
+ if hasattr(db, '_redis') and db._redis:
1474
+ redis_client = db._redis
1475
+ elif hasattr(db, 'csr_adapter') and hasattr(db.csr_adapter, '_redis'):
1476
+ redis_client = db.csr_adapter._redis
1477
+ except Exception:
1478
+ pass
1479
+
1480
+ eidx = EntityIndex(redis_client=redis_client)
1481
+ builder = ManifestBuilder(entity_index=eidx, redis_client=redis_client)
1482
+
1483
+ adapter = getattr(db, 'csr_adapter', None) or db
1484
+ qualities = []
1485
+ label_counts = {}
1486
+ for nid in list(result.entity_ids.values()) + list(result.fact_ids.values()) + list(result.passage_ids.values()):
1487
+ try:
1488
+ node = adapter.get_node(nid)
1489
+ if node:
1490
+ q = (node.properties or {}).get("_quality", 50)
1491
+ qualities.append(q)
1492
+ lbl = getattr(node, 'label', getattr(node, 'node_type', ''))
1493
+ label_counts[lbl] = label_counts.get(lbl, 0) + 1
1494
+ except Exception:
1495
+ pass
1496
+
1497
+ context_id = graph_name
1498
+ builder.build(graph_name, context_id, node_qualities=qualities, label_counts=label_counts)
1499
+ try:
1500
+ from ..context.quality import ResultCache
1501
+ ResultCache(redis_client=redis_client).build(graph_name, adapter, eidx)
1502
+ logger.info("[QUALITY] Manifest + result cache rebuilt for %s (%d nodes)", graph_name, len(qualities))
1503
+ except Exception:
1504
+ logger.info("[QUALITY] Manifest rebuilt for %s (%d nodes)", graph_name, len(qualities))
1505
+ except Exception as e:
1506
+ logger.debug("[QUALITY] Manifest rebuild skipped: %s", e)
1507
+
1508
+ return result
1509
+
1510
+
1511
+ def ingest_chat_export(
1512
+ file_path: str,
1513
+ db,
1514
+ graph_name: str,
1515
+ on_stage: Optional[Callable] = None,
1516
+ max_conversations: int = 100,
1517
+ ):
1518
+ """Ingest a chat history export (ZIP or JSON) through the full pipeline.
1519
+
1520
+ Pipeline stages:
1521
+ 1. PARSE_CHAT — extract ZIP → detect source (ChatGPT/Claude/Gemini) → parse conversations
1522
+ 2. BUILD_GRAPH — create Conversation/Message nodes + edges via connector
1523
+ 3. EXTRACT — run entity/fact extraction on conversation text via smart pipeline
1524
+ 4. INDEX — BM25 + vector indexing
1525
+ 5. CONTEXT_UNITS — cluster facts into CUs
1526
+
1527
+ Args:
1528
+ file_path: Path to ZIP or JSON file
1529
+ db: AIContextDB instance
1530
+ graph_name: Target graph namespace
1531
+ on_stage: Progress callback
1532
+ max_conversations: Max conversations to process
1533
+ """
1534
+ import zipfile
1535
+ import json as _json
1536
+ import os
1537
+ import tempfile
1538
+
1539
+ if on_stage:
1540
+ on_stage("parse_chat", {"message": "Parsing chat export..."})
1541
+
1542
+ # Step 1: PARSE — extract conversations.json from ZIP or read JSON directly
1543
+ conversations_path = file_path
1544
+ tmp_extracted = None
1545
+
1546
+ if file_path.lower().endswith('.zip'):
1547
+ try:
1548
+ with zipfile.ZipFile(file_path) as zf:
1549
+ conv_files = [n for n in zf.namelist()
1550
+ if 'conversations' in n.lower() and n.endswith('.json')]
1551
+ if not conv_files:
1552
+ return BuildResult(errors=["No conversations.json found in ZIP"])
1553
+ fd, tmp_extracted = tempfile.mkstemp(suffix='.json', prefix='chat_')
1554
+ os.write(fd, zf.read(conv_files[0]))
1555
+ os.close(fd)
1556
+ conversations_path = tmp_extracted
1557
+ logger.info("[CHAT] Extracted %s from ZIP (%d bytes)", conv_files[0], os.path.getsize(tmp_extracted))
1558
+ except Exception as e:
1559
+ return BuildResult(errors=[f"ZIP extraction failed: {e}"])
1560
+
1561
+ # Step 2: Detect source and create connector
1562
+ try:
1563
+ with open(conversations_path, 'r', encoding='utf-8') as f:
1564
+ data = _json.load(f)
1565
+ except Exception as e:
1566
+ if tmp_extracted:
1567
+ os.unlink(tmp_extracted)
1568
+ return BuildResult(errors=[f"JSON parse failed: {e}"])
1569
+
1570
+ conversations = data if isinstance(data, list) else data.get("conversations", data.get("items", []))
1571
+ if not conversations:
1572
+ if tmp_extracted:
1573
+ os.unlink(tmp_extracted)
1574
+ return BuildResult(errors=["No conversations found in file"])
1575
+
1576
+ # Auto-detect source
1577
+ sample = conversations[0] if conversations else {}
1578
+ if "mapping" in sample:
1579
+ source = "chatgpt"
1580
+ elif "chat_messages" in sample or "sender" in str(sample.get("messages", [{}])[0] if sample.get("messages") else {}):
1581
+ source = "claude"
1582
+ else:
1583
+ source = "chatgpt" # default
1584
+
1585
+ if on_stage:
1586
+ on_stage("parse_chat", {
1587
+ "message": f"Detected {source} export: {len(conversations)} conversations",
1588
+ "source": source,
1589
+ "conversations": len(conversations),
1590
+ })
1591
+
1592
+ logger.info("[CHAT] Detected %s export: %d conversations", source, len(conversations))
1593
+
1594
+ # Step 3: BUILD_GRAPH — use connector to create graph nodes
1595
+ if on_stage:
1596
+ on_stage("build_graph", {"message": f"Building graph from {source} conversations..."})
1597
+
1598
+ from .connectors import get_ingestor
1599
+ ingestor = get_ingestor(source, {
1600
+ "export_file": conversations_path,
1601
+ "max_conversations": max_conversations,
1602
+ }, {})
1603
+
1604
+ if not ingestor:
1605
+ if tmp_extracted:
1606
+ os.unlink(tmp_extracted)
1607
+ return BuildResult(errors=[f"No connector for source: {source}"])
1608
+
1609
+ connector_result = ingestor.pull_data(graph_name)
1610
+
1611
+ # Write connector nodes + edges to graph
1612
+ from ..core.hybrid_graph_storage import GraphNode, GraphEdge
1613
+ import uuid as _uuid
1614
+
1615
+ for node in connector_result.nodes:
1616
+ nid = node.get("id", str(_uuid.uuid4()))
1617
+ label = node.get("label", "Document")
1618
+ props = node.get("properties", {})
1619
+ db.add_node(GraphNode(id=nid, label=label, properties=props))
1620
+
1621
+ for edge in connector_result.edges:
1622
+ db.add_edge(GraphEdge(
1623
+ id=edge.get("id", str(_uuid.uuid4())),
1624
+ source=edge.get("source", ""), target=edge.get("target", ""),
1625
+ label=edge.get("label", "RELATED"), properties=edge.get("properties", {}),
1626
+ ))
1627
+
1628
+ stats = connector_result.stats or {}
1629
+ logger.info("[CHAT] Built %d nodes, %d edges from %s",
1630
+ stats.get("nodes", len(connector_result.nodes)),
1631
+ len(connector_result.edges), source)
1632
+
1633
+ if on_stage:
1634
+ on_stage("build_graph", {
1635
+ "message": f"Built {len(connector_result.nodes)} nodes from {source}",
1636
+ "nodes": len(connector_result.nodes),
1637
+ "edges": len(connector_result.edges),
1638
+ })
1639
+
1640
+ # Step 4: EXTRACT — run entity/fact extraction on conversation text
1641
+ if connector_result.data_items:
1642
+ if on_stage:
1643
+ on_stage("extract", {"message": f"Extracting entities from {len(connector_result.data_items)} conversations..."})
1644
+
1645
+ items_to_process = connector_result.data_items[:max_conversations]
1646
+ for i, item in enumerate(items_to_process):
1647
+ text = item.get("text", "")[:5000] # cap per conversation
1648
+ if not text.strip():
1649
+ continue
1650
+ try:
1651
+ ingest_text(
1652
+ text=text,
1653
+ db=db,
1654
+ title=item.get("metadata", {}).get("title", f"Conversation {i+1}"),
1655
+ pipeline="smart_text",
1656
+ on_stage=None,
1657
+ )
1658
+ except Exception as e:
1659
+ logger.debug("[CHAT] Extraction failed for conversation %d: %s", i, e)
1660
+
1661
+ if on_stage and (i + 1) % 10 == 0:
1662
+ on_stage("extract", {"message": f"Processed {i+1}/{len(items_to_process)} conversations"})
1663
+
1664
+ if on_stage:
1665
+ on_stage("index", {"message": "Indexing..."})
1666
+
1667
+ # Step 5: INDEX + CU assembly is handled by ingest_text calls above
1668
+
1669
+ # Cleanup
1670
+ if tmp_extracted:
1671
+ try:
1672
+ os.unlink(tmp_extracted)
1673
+ except Exception:
1674
+ pass
1675
+
1676
+ if on_stage:
1677
+ on_stage("complete", {
1678
+ "message": f"Imported {len(conversations[:max_conversations])} {source} conversations",
1679
+ "source": source,
1680
+ "conversations": len(conversations[:max_conversations]),
1681
+ "nodes": len(connector_result.nodes),
1682
+ })
1683
+
1684
+ logger.info("[CHAT] Pipeline complete: %d conversations, %d nodes", len(conversations[:max_conversations]), len(connector_result.nodes))
1685
+ return BuildResult()
1686
+
1687
+
1688
+ def ingest_text(
1689
+ text: str,
1690
+ db,
1691
+ title: str = "",
1692
+ source_url: str = "",
1693
+ schema: Optional[IngestionSchema] = None,
1694
+ pipeline: str = "smart_text",
1695
+ mode: str = "auto",
1696
+ filter_config: Optional[FilterConfig] = None,
1697
+ strategy: Optional[str] = None,
1698
+ on_stage: Optional[Callable] = None,
1699
+ debug: bool = False,
1700
+ owner: str = "",
1701
+ context_purpose: str = "",
1702
+ ):
1703
+ """Ingest raw text into a rich knowledge graph.
1704
+
1705
+ Same pipeline as ingest_url but skips HTML cleaning.
1706
+
1707
+ Returns:
1708
+ mode="auto": BuildResult (committed)
1709
+ mode="review": StagingResult (preview, not committed)
1710
+ """
1711
+ # Resolve named pipeline config if provided
1712
+ _pipeline_config = resolve_named_pipeline(pipeline)
1713
+ if _pipeline_config:
1714
+ if _pipeline_config.get("schema_name") and not schema:
1715
+ try:
1716
+ from .schema_extractor import load_schema_by_name
1717
+ schema = load_schema_by_name(_pipeline_config["schema_name"], db)
1718
+ except Exception:
1719
+ pass
1720
+ logger.info("[PIPELINE] Using named pipeline: %s (schema=%s)", pipeline, _pipeline_config.get("schema_name", ""))
1721
+
1722
+ if not schema:
1723
+ schema = load_schema(db)
1724
+
1725
+ # Route to universal pipeline if schema has extraction: block
1726
+ try:
1727
+ from ..schema.sdl import EnhancedSchema
1728
+ from ..schema.compiler import SchemaCompiler
1729
+ from pathlib import Path as _Path
1730
+ _schema_path = _Path(__file__).parent.parent / "config" / "schemas" / f"{schema.name}.yaml"
1731
+ if _schema_path.exists():
1732
+ import yaml
1733
+ with open(_schema_path) as _sf:
1734
+ _raw = yaml.safe_load(_sf)
1735
+ _enhanced = EnhancedSchema.from_dict(_raw)
1736
+ _compiled = SchemaCompiler.compile(_enhanced)
1737
+ if _compiled.execution_plan:
1738
+ from .universal.stage_executor import StageExecutor
1739
+ from .universal.ingest_content import IngestContent
1740
+ from .universal._operator_registry import resolve_operators
1741
+ from .universal.parsers.turn_parser import TurnParser
1742
+
1743
+ content = IngestContent(
1744
+ content_type="conversation" if _compiled.execution_plan.parser == "turn" else "text",
1745
+ text=text, title=title, source=source_url,
1746
+ )
1747
+
1748
+ if _compiled.execution_plan.parser == "turn":
1749
+ parser = TurnParser()
1750
+ session_meta, turns = parser.parse(text)
1751
+ chunks = parser.to_chunks(turns, conversation_title=title or "")
1752
+ content.messages = [{"role": t.role, "content": t.content} for t in turns]
1753
+ else:
1754
+ from .universal.ingest_content import Chunk
1755
+ from .chunker import chunk_document as _chunk_document_universal
1756
+ raw_chunks = _chunk_document_universal(text)
1757
+ chunks = [Chunk(content=c.content, index=i) for i, c in enumerate(raw_chunks)]
1758
+
1759
+ operators = resolve_operators(_compiled.execution_plan, _compiled)
1760
+ executor = StageExecutor(
1761
+ operators=operators, db=db,
1762
+ namespace=getattr(db, '_namespace', '') or getattr(db, 'namespace', '') or getattr(db, 'name', 'default'),
1763
+ compiled_schema=_compiled,
1764
+ )
1765
+ logger.info("[UNIVERSAL] Routed to universal pipeline: %s (%s, %d stages)",
1766
+ schema.name, _compiled.execution_plan.parser, len(operators))
1767
+ return executor.execute(content, chunks)
1768
+ except ImportError as e:
1769
+ logger.warning("[UNIVERSAL] Import error during routing: %s", e)
1770
+ except Exception as e:
1771
+ logger.warning("[UNIVERSAL] Routing failed, using legacy pipeline: %s", e, exc_info=True)
1772
+
1773
+ # Legacy pipeline below
1774
+ llm_fn = _get_llm_fn(db) if pipeline != "fast_ingest" else None
1775
+
1776
+ clean_doc = clean_text(text, title=title, source_url=source_url)
1777
+ if not clean_doc.body:
1778
+ return BuildResult(errors=["Empty text"])
1779
+
1780
+ # Stage 0: Content Fingerprint Dedup (Layer 1)
1781
+ try:
1782
+ fp = _get_content_fingerprint()
1783
+ dedup_result = fp.check(clean_doc.body, url=source_url)
1784
+ if dedup_result.status == "exact_duplicate":
1785
+ if on_stage:
1786
+ on_stage("dedup_rejected", {"status": "exact_duplicate"})
1787
+ logger.info("[DEDUP] Rejected exact duplicate content")
1788
+ return BuildResult(errors=["Duplicate content (already ingested)"])
1789
+ elif dedup_result.status == "content_changed":
1790
+ logger.info("[DEDUP] Content changed — versioning")
1791
+ except Exception as exc:
1792
+ logger.warning("[DEDUP] Fingerprint check failed (non-fatal): %s", exc)
1793
+
1794
+ # Auto-classify sensitivity
1795
+ from ..security.auto_tagger import AutoTagger
1796
+ _tagger = AutoTagger()
1797
+ _classification = _tagger.classify_text(clean_doc.body[:3000])
1798
+ sensitivity = _classification.sensitivity
1799
+
1800
+ # Structural pre-filter (cheap, catches CSV/code/JSON mismatches before LLM)
1801
+ if filter_config:
1802
+ struct_result = structural_pre_filter(clean_doc.body[:2000], filter_config, schema=schema)
1803
+ if struct_result and struct_result.status == "filtered":
1804
+ if on_stage:
1805
+ on_stage("filter_structural", {"status": "filtered", "reason": struct_result.reason})
1806
+ return BuildResult(errors=[f"Filtered (structural): {struct_result.reason}"])
1807
+
1808
+ # Filter chain
1809
+ if filter_config:
1810
+ debug_log = [] if debug else None
1811
+ f_result = filter_chain(clean_doc.title, clean_doc.body, filter_config,
1812
+ llm_fn=llm_fn, embed_fn=_get_embed_fn(), debug_log=debug_log)
1813
+ if debug_log and on_stage:
1814
+ on_stage("filter_debug", {"filter_decisions": debug_log, "result": f_result.status, "reason": f_result.reason})
1815
+ if f_result.status == "filtered":
1816
+ if mode == "review":
1817
+ staging = StagingResult(
1818
+ staging_id=str(_uuid.uuid4()),
1819
+ filter_log=[{"title": title, "status": "filtered", "reason": f_result.reason}],
1820
+ created_at=datetime.now(timezone.utc).isoformat(),
1821
+ )
1822
+ _staging_store[staging.staging_id] = staging
1823
+ return staging
1824
+ return BuildResult(errors=[f"Filtered: {f_result.reason}"])
1825
+ if f_result.status == "review" and mode == "auto":
1826
+ mode = "review"
1827
+
1828
+ link_dicts = [{"url": l.url, "anchor": l.anchor} for l in clean_doc.links]
1829
+ chunks = chunk_document(clean_doc.body, links=link_dicts)
1830
+ if not chunks:
1831
+ return BuildResult(errors=["No chunks produced"])
1832
+
1833
+ # Stage 2b: Semantic Dedup (Layer 2)
1834
+ try:
1835
+ _embed_fn_dedup = _get_embed_fn()
1836
+ if _embed_fn_dedup and chunks:
1837
+ sd = _get_semantic_dedup()
1838
+ first_chunk_text = chunks[0].content if hasattr(chunks[0], 'content') else chunks[0].body
1839
+ first_embedding = _embed_fn_dedup(first_chunk_text[:500])
1840
+ sem_result = sd.check(first_embedding, text=first_chunk_text)
1841
+ if sem_result.status == "semantic_duplicate":
1842
+ if on_stage:
1843
+ on_stage("dedup_semantic", {"status": "semantic_duplicate", "similarity": sem_result.similarity})
1844
+ logger.info("[DEDUP] Semantic duplicate (similarity=%.2f) — rejecting", sem_result.similarity)
1845
+ return BuildResult(errors=[f"Semantic duplicate (similarity={sem_result.similarity:.2f})"])
1846
+ elif sem_result.status == "factual_update":
1847
+ if on_stage:
1848
+ on_stage("dedup_factual_update", {"status": "factual_update", "similarity": sem_result.similarity, "numbers_changed": True})
1849
+ logger.info("[DEDUP] Factual update (similarity=%.2f, numbers changed) — versioning", sem_result.similarity)
1850
+ elif sem_result.status == "related_coverage":
1851
+ logger.info("[DEDUP] Related coverage (similarity=%.2f) — proceeding", sem_result.similarity)
1852
+ sd.add(first_embedding, doc_id=source_url or title, text=first_chunk_text)
1853
+ except Exception as exc:
1854
+ logger.warning("[DEDUP] Semantic dedup failed (non-fatal): %s", exc)
1855
+
1856
+ content_strategy = get_strategy(strategy) if strategy else _auto_detect_strategy(clean_doc.body)
1857
+
1858
+ extractions = []
1859
+ for chunk in chunks:
1860
+ ext = _extract_chunk(chunk, schema, llm_fn=llm_fn, use_regex=True, strategy=content_strategy)
1861
+ extractions.append(ext)
1862
+
1863
+ # Stage 3a: Quality Amplifier — score relevance against context purpose
1864
+ _embed_fn = _get_embed_fn()
1865
+ if context_purpose and _embed_fn:
1866
+ if on_stage:
1867
+ _te = sum(len(e.entities) for e in extractions)
1868
+ _tf = sum(len(e.facts) for e in extractions)
1869
+ on_stage("amplify", {"message": f"Scoring {_te} entities + {_tf} facts for relevance"})
1870
+ amp_result = amplify_extractions(
1871
+ extractions=extractions,
1872
+ context_purpose=context_purpose,
1873
+ embed_fn=_embed_fn,
1874
+ )
1875
+ if on_stage:
1876
+ on_stage("amplify_done", amp_result.stats)
1877
+ logger.info("[AMPLIFIER] %s", amp_result.stats)
1878
+
1879
+ # Stage 3b: Intelligence Tagger — sentiment, geography, domain, category, impact
1880
+ try:
1881
+ _llm_fn_for_tags = llm_fn or _get_llm_fn()
1882
+ chunk_texts = [c.content if hasattr(c, 'content') else c.body for c in chunks]
1883
+ if on_stage:
1884
+ on_stage("intelligence_tag", {"message": f"Tagging {len(chunks)} chunks with intelligence dimensions"})
1885
+ tag_result = _tag_extractions(
1886
+ extractions=extractions,
1887
+ chunk_texts=chunk_texts,
1888
+ llm_fn=_llm_fn_for_tags,
1889
+ )
1890
+ _apply_intelligence_tags(extractions, tag_result, chunk_texts)
1891
+ if on_stage:
1892
+ on_stage("intelligence_tag_done", tag_result.stats)
1893
+ logger.info("[TAGGER] %s", tag_result.stats)
1894
+ except Exception as exc:
1895
+ logger.warning("[TAGGER] Intelligence tagging failed (non-fatal): %s", exc)
1896
+
1897
+ # Stage 3c: Correlation Signals
1898
+ try:
1899
+ from ..intelligence.correlation_engine import CorrelationEngine
1900
+ from ..intelligence.correlation_template import list_templates, load_template
1901
+ _corr_engine = CorrelationEngine()
1902
+ for tmpl_name in list_templates():
1903
+ tmpl = load_template(tmpl_name)
1904
+ if tmpl:
1905
+ _corr_engine.register_template_object(tmpl)
1906
+
1907
+ _signal_entities = []
1908
+ for ext in extractions:
1909
+ for ent in ext.entities:
1910
+ props = ent.get("properties", {})
1911
+ _signal_entities.append({
1912
+ "name": props.get("name", ""),
1913
+ "label": ent.get("label", "Entity"),
1914
+ "_sentiment": props.get("_sentiment", "neutral"),
1915
+ })
1916
+
1917
+ for tmpl_name in _corr_engine.list_registered():
1918
+ tmpl = _corr_engine.get_template(tmpl_name)
1919
+ if tmpl:
1920
+ signals = _corr_engine.process_ingest(_signal_entities, tmpl)
1921
+ if signals:
1922
+ if on_stage:
1923
+ on_stage("correlation_signals", {
1924
+ "template": tmpl_name,
1925
+ "signals_fired": len(signals),
1926
+ "signals": [{"type": s.type, "entity": s.entity_name, "severity": s.severity} for s in signals[:5]],
1927
+ })
1928
+ logger.info("[CORR] %d signals fired from template '%s'", len(signals), tmpl_name)
1929
+
1930
+ # Reactive — trigger pipeline actions
1931
+ try:
1932
+ from ..intelligence.reactive import ReactiveController
1933
+ _reactive = ReactiveController()
1934
+ _reactive.add_default_rules()
1935
+ graph_name = getattr(db, '_namespace', '') or getattr(db, 'namespace', '') or 'default'
1936
+ for sig in signals:
1937
+ _reactive.react(sig, graph_name)
1938
+ except Exception:
1939
+ pass
1940
+
1941
+ except Exception as exc:
1942
+ logger.warning("[CORR] Correlation signal processing failed (non-fatal): %s", exc)
1943
+
1944
+ # Review mode: return preview
1945
+ if mode == "review":
1946
+ total_ents = sum(len(e.entities) for e in extractions)
1947
+ total_facts = sum(len(e.facts) for e in extractions)
1948
+ passage_previews = [{"content": c.content[:200], "token_count": c.token_count, "chunk_index": c.chunk_index} for c in chunks]
1949
+ entity_previews = []
1950
+ fact_previews = []
1951
+ edge_previews = []
1952
+ sid = 0
1953
+ for ext in extractions:
1954
+ for e in ext.entities:
1955
+ e["_staging_id"] = f"e_{sid}"
1956
+ entity_previews.append({"label": e.get("label", ""), "name": e.get("properties", {}).get("name", ""), "_staging_id": e["_staging_id"]})
1957
+ sid += 1
1958
+ for f in ext.facts:
1959
+ f["_staging_id"] = f"f_{sid}"
1960
+ fact_previews.append({"statement": f.get("properties", f).get("statement", ""), "_staging_id": f["_staging_id"]})
1961
+ sid += 1
1962
+ for r in ext.relationships:
1963
+ edge_previews.append({"label": r.get("label", ""), "source": r.get("source_name", ""), "target": r.get("target_name", "")})
1964
+
1965
+ from .graph_builder import _suggest_schema_updates
1966
+ suggestions = _suggest_schema_updates(extractions, schema) if schema else []
1967
+
1968
+ staging = StagingResult(
1969
+ staging_id=str(_uuid.uuid4()), clean_doc=clean_doc, chunks=chunks, extractions=extractions,
1970
+ passages=passage_previews, entities=entity_previews, facts=fact_previews,
1971
+ edges=edge_previews, links=[{"url": l.url, "anchor": l.anchor} for l in clean_doc.links] if clean_doc.links else [],
1972
+ quality_score=_calc_quality(passage_previews, entity_previews, fact_previews, edge_previews),
1973
+ schema_suggestions=[s.to_dict() for s in suggestions],
1974
+ schema_used=schema.name if schema else "default", pipeline=pipeline,
1975
+ created_at=datetime.now(timezone.utc).isoformat(),
1976
+ )
1977
+ _staging_store[staging.staging_id] = staging
1978
+ return staging
1979
+
1980
+ # Post-extraction filter (precise, uses structured entities)
1981
+ if filter_config and (filter_config.semantic_rules or schema):
1982
+ post_result = post_extraction_filter(extractions, filter_config, schema=schema, embed_fn=_get_embed_fn())
1983
+ if post_result and post_result.status == "filtered":
1984
+ if on_stage:
1985
+ on_stage("filter_post", {"status": "filtered", "reason": post_result.reason})
1986
+ return BuildResult(errors=[f"Filtered (post-extraction): {post_result.reason}"])
1987
+
1988
+ result = build_graph(clean_doc, chunks, extractions, db, schema, pipeline_name=pipeline,
1989
+ owner=owner, sensitivity=sensitivity, compiled_schema=None)
1990
+ _embed_nodes(result, db)
1991
+ _graph_name = getattr(db, '_namespace', '') or getattr(db, 'namespace', '') or getattr(db, 'name', 'default')
1992
+ _compute_semantic_neighbors(result, db, _graph_name)
1993
+ _index_bm25(result, db)
1994
+ _assemble_context_units(result, db, _graph_name, schema_name=schema.name if schema else "")
1995
+
1996
+ # Rebuild context manifest (non-blocking)
1997
+ try:
1998
+ from ..context.quality import EntityIndex, ManifestBuilder
1999
+ graph_name = getattr(db, '_namespace', '') or getattr(db, 'namespace', '') or 'default'
2000
+ redis_client = None
2001
+ try:
2002
+ if hasattr(db, '_redis') and db._redis:
2003
+ redis_client = db._redis
2004
+ elif hasattr(db, 'csr_adapter') and hasattr(db.csr_adapter, '_redis'):
2005
+ redis_client = db.csr_adapter._redis
2006
+ except Exception:
2007
+ pass
2008
+
2009
+ eidx = EntityIndex(redis_client=redis_client)
2010
+ builder = ManifestBuilder(entity_index=eidx, redis_client=redis_client)
2011
+
2012
+ adapter = getattr(db, 'csr_adapter', None) or db
2013
+ qualities = []
2014
+ label_counts = {}
2015
+ for nid in list(result.entity_ids.values()) + list(result.fact_ids.values()) + list(result.passage_ids.values()):
2016
+ try:
2017
+ node = adapter.get_node(nid)
2018
+ if node:
2019
+ q = (node.properties or {}).get("_quality", 50)
2020
+ qualities.append(q)
2021
+ lbl = getattr(node, 'label', getattr(node, 'node_type', ''))
2022
+ label_counts[lbl] = label_counts.get(lbl, 0) + 1
2023
+ except Exception:
2024
+ pass
2025
+
2026
+ context_id = graph_name
2027
+ builder.build(graph_name, context_id, node_qualities=qualities, label_counts=label_counts)
2028
+ logger.info("[QUALITY] Manifest rebuilt for %s (%d nodes scored)", graph_name, len(qualities))
2029
+ except Exception as e:
2030
+ logger.debug("[QUALITY] Manifest rebuild skipped: %s", e)
2031
+
2032
+ return result
2033
+
2034
+
2035
+ def ingest_crawl(
2036
+ start_url: str,
2037
+ db,
2038
+ max_pages: int = 20,
2039
+ schema: Optional[IngestionSchema] = None,
2040
+ pipeline: str = "smart_article",
2041
+ mode: str = "auto",
2042
+ filter_config: Optional[FilterConfig] = None,
2043
+ strategy: Optional[str] = None,
2044
+ on_stage: Optional[Callable] = None,
2045
+ debug: bool = False,
2046
+ owner: str = "",
2047
+ ) -> Dict[str, Any]:
2048
+ """Crawl a website and ingest matching pages — PARALLEL version.
2049
+
2050
+ Phase 1: Parallel fetch (ThreadPool) — discover all URLs + fetch HTML
2051
+ Phase 2: Parallel filter — run filter chain on all fetched pages
2052
+ Phase 3: Batch extract — ingest pages that passed filters
2053
+ """
2054
+ from .cleaner import clean_webpage
2055
+ from urllib.parse import urlparse, urljoin
2056
+ from concurrent.futures import ThreadPoolExecutor, as_completed
2057
+ import re
2058
+ import trafilatura
2059
+ import time
2060
+
2061
+ if not schema:
2062
+ schema = load_schema(db)
2063
+
2064
+ logger.info("[CRAWL] filter_config=%s, has_rules=%s",
2065
+ filter_config is not None,
2066
+ len(filter_config.semantic_rules) if filter_config else 0)
2067
+
2068
+ domain = urlparse(start_url).netloc
2069
+ results = {"ingested": [], "filtered": [], "failed": [], "total_crawled": 0}
2070
+ embed_fn = _get_embed_fn()
2071
+ llm_fn = _get_llm_fn(db) if pipeline != "fast_ingest" else None
2072
+
2073
+ def _extract_links_from_html(html: str, base_url: str) -> List[str]:
2074
+ links = set()
2075
+ for match in re.finditer(r'href=["\']([^"\']+)["\']', html):
2076
+ href = match.group(1)
2077
+ if href.startswith(('#', 'javascript:', 'mailto:')):
2078
+ continue
2079
+ full = urljoin(base_url, href)
2080
+ if urlparse(full).netloc == domain:
2081
+ clean = full.split('#')[0].split('?')[0].rstrip('/')
2082
+ links.add(clean)
2083
+ return list(links)
2084
+
2085
+ # ── Phase 1: Discover URLs (BFS) + parallel fetch ─────────────
2086
+ if on_stage:
2087
+ on_stage("crawl_discover", {"message": f"Discovering pages from {domain} (max {max_pages})"})
2088
+
2089
+ visited = set()
2090
+ queue = [start_url]
2091
+ urls_to_fetch = []
2092
+
2093
+ # BFS to discover URLs (quick — just fetches HTML headers/links)
2094
+ while queue and len(visited) < max_pages:
2095
+ url = queue.pop(0)
2096
+ if url in visited:
2097
+ continue
2098
+ visited.add(url)
2099
+ urls_to_fetch.append(url)
2100
+
2101
+ # Quick fetch just for link discovery (first page only for seed URLs)
2102
+ if len(visited) <= 3: # only deep-crawl first few pages for more links
2103
+ try:
2104
+ raw = trafilatura.fetch_url(url)
2105
+ if raw:
2106
+ for link in _extract_links_from_html(raw, url):
2107
+ if link not in visited:
2108
+ queue.append(link)
2109
+ except Exception:
2110
+ pass
2111
+
2112
+ # ── URL-level dedup: skip URLs already ingested into this graph ───
2113
+ _already_ingested = set()
2114
+ try:
2115
+ import os as _os
2116
+ import redis as _redis_dedup
2117
+ _rurl = _os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL")
2118
+ if _rurl:
2119
+ _rconn = _redis_dedup.from_url(_rurl)
2120
+ _graph_name = getattr(db, 'namespace', '') or getattr(db, '_namespace', '') or getattr(db, 'name', '')
2121
+ _dedup_key = f"contextcore:ingested_urls:{_graph_name}"
2122
+ _already_ingested = {u.decode() if isinstance(u, bytes) else u for u in _rconn.smembers(_dedup_key)}
2123
+ except Exception:
2124
+ pass
2125
+
2126
+ # Only dedup article URLs (with unique slugs), not listing/index pages
2127
+ # Listing pages (short paths like /india, /technology) get new content daily
2128
+ def _is_article_url(url: str) -> bool:
2129
+ from urllib.parse import urlparse
2130
+ path = urlparse(url).path.rstrip("/")
2131
+ # Short paths (0-2 segments) are likely listing/index pages
2132
+ segments = [s for s in path.split("/") if s]
2133
+ if len(segments) <= 2:
2134
+ return False
2135
+ # URLs with numbers/IDs are likely articles
2136
+ if any(c.isdigit() for c in path):
2137
+ return True
2138
+ # Long slugs are likely articles
2139
+ if len(path) > 40:
2140
+ return True
2141
+ return False
2142
+
2143
+ before_dedup = len(urls_to_fetch)
2144
+ if _already_ingested:
2145
+ # Skip article URLs already ingested; always re-crawl listing pages (they get new content)
2146
+ urls_to_fetch = [u for u in urls_to_fetch if not (_is_article_url(u) and u in _already_ingested)]
2147
+ skipped = before_dedup - len(urls_to_fetch)
2148
+ if skipped:
2149
+ logger.info("[CRAWL] URL dedup: skipped %d already-ingested article URLs (listing pages re-crawled)", skipped)
2150
+
2151
+ if on_stage:
2152
+ on_stage("crawl_fetch", {"message": f"Fetching {len(urls_to_fetch)} pages in parallel"})
2153
+
2154
+ if not urls_to_fetch:
2155
+ if on_stage:
2156
+ on_stage("crawl_done", {"message": "All URLs already ingested — nothing new to crawl"})
2157
+ return {"total_crawled": 0, "ingested": 0, "filtered": 0, "failed": [], "nodes_created": 0, "edges_created": 0}
2158
+
2159
+ # ── Phase 2: Parallel fetch + clean ───────────────────────────
2160
+ t0 = time.time()
2161
+ fetched_pages = [] # (url, CleanDocument)
2162
+
2163
+ def _fetch_one(url):
2164
+ try:
2165
+ raw = trafilatura.fetch_url(url)
2166
+ if not raw:
2167
+ return url, None, "fetch failed"
2168
+ # Also discover more links from this page
2169
+ new_links = _extract_links_from_html(raw, url)
2170
+ doc = clean_webpage(raw, source_url=url)
2171
+ if not doc.body or doc.word_count < 20:
2172
+ return url, None, "no content"
2173
+ return url, doc, new_links
2174
+ except Exception as e:
2175
+ return url, None, str(e)
2176
+
2177
+ with ThreadPoolExecutor(max_workers=5) as pool:
2178
+ futures = {pool.submit(_fetch_one, url): url for url in urls_to_fetch}
2179
+ for future in as_completed(futures):
2180
+ url, doc, extra = future.result()
2181
+ results["total_crawled"] += 1
2182
+ if doc is None:
2183
+ results["failed"].append({"url": url, "reason": extra if isinstance(extra, str) else "unknown"})
2184
+ else:
2185
+ fetched_pages.append((url, doc))
2186
+ # Add discovered links for more pages
2187
+ if isinstance(extra, list) and len(visited) < max_pages:
2188
+ for link in extra[:10]:
2189
+ if link not in visited:
2190
+ visited.add(link)
2191
+ # Quick fetch in background if we need more pages
2192
+ if len(fetched_pages) + len(results["failed"]) < max_pages:
2193
+ try:
2194
+ r = trafilatura.fetch_url(link)
2195
+ if r:
2196
+ d = clean_webpage(r, source_url=link)
2197
+ if d and d.body and d.word_count >= 20:
2198
+ fetched_pages.append((link, d))
2199
+ results["total_crawled"] += 1
2200
+ except Exception:
2201
+ pass
2202
+
2203
+ fetch_time = time.time() - t0
2204
+ if on_stage:
2205
+ on_stage("crawl_fetched", {"message": f"Fetched {len(fetched_pages)} pages in {fetch_time:.1f}s ({len(results['failed'])} failed)"})
2206
+
2207
+ # ── Phase 3: Filter all pages ─────────────────────────────────
2208
+ if filter_config and fetched_pages:
2209
+ if on_stage:
2210
+ on_stage("crawl_filter", {"message": f"Filtering {len(fetched_pages)} pages"})
2211
+
2212
+ passed_pages = []
2213
+ for url, doc in fetched_pages:
2214
+ f_result = filter_chain(doc.title, doc.body, filter_config,
2215
+ llm_fn=llm_fn, embed_fn=embed_fn)
2216
+ if f_result.status == "filtered":
2217
+ results["filtered"].append({
2218
+ "url": url, "title": doc.title,
2219
+ "reason": f_result.reason, "scores": f_result.scores,
2220
+ })
2221
+ else:
2222
+ passed_pages.append((url, doc))
2223
+
2224
+ if on_stage:
2225
+ on_stage("crawl_filtered", {"message": f"{len(passed_pages)} passed, {len(results['filtered'])} filtered"})
2226
+ else:
2227
+ passed_pages = fetched_pages
2228
+
2229
+ # ── Phase 4: Chunk + Extract all pages (batch) ─────────────────
2230
+ if on_stage:
2231
+ on_stage("crawl_chunk", {"message": f"Chunking {len(passed_pages)} pages"})
2232
+
2233
+ content_strategy = get_strategy(strategy) if strategy else get_strategy("news_article")
2234
+ all_page_data = [] # [(url, doc, chunks, extractions)]
2235
+
2236
+ # Chunk all pages (fast, no LLM)
2237
+ for url, doc in passed_pages:
2238
+ link_dicts = [{"url": l.url, "anchor": l.anchor} for l in doc.links] if doc.links else []
2239
+ chunks = chunk_document(doc.body, links=link_dicts)
2240
+ if chunks:
2241
+ all_page_data.append((url, doc, chunks, []))
2242
+
2243
+ skipped_pages = len(passed_pages) - len(all_page_data)
2244
+ total_chunks = sum(len(d[2]) for d in all_page_data)
2245
+ if on_stage:
2246
+ on_stage("crawl_chunk_done", {
2247
+ "message": (
2248
+ f"Chunked {len(all_page_data)} pages → {total_chunks} chunks"
2249
+ + (f" ({skipped_pages} pages skipped — empty content)" if skipped_pages else "")
2250
+ ),
2251
+ "pages_chunked": len(all_page_data),
2252
+ "pages_skipped": skipped_pages,
2253
+ "total_chunks": total_chunks,
2254
+ })
2255
+ on_stage("crawl_extract", {"message": f"Extracting entities from {total_chunks} chunks across {len(all_page_data)} pages (LLM: {'yes' if llm_fn else 'no'})"})
2256
+
2257
+ # Extract all chunks (LLM calls — this is the slow part)
2258
+ for i, (url, doc, chunks, _) in enumerate(all_page_data):
2259
+ if on_stage:
2260
+ on_stage("extract_page", {"message": f"[{i+1}/{len(all_page_data)}] Extracting: {doc.title[:40]} ({len(chunks)} chunks)"})
2261
+ page_extractions = []
2262
+ for chunk in chunks:
2263
+ ext = _extract_chunk(chunk, schema, llm_fn=llm_fn, use_regex=True, strategy=content_strategy)
2264
+ page_extractions.append(ext)
2265
+ all_page_data[i] = (url, doc, chunks, page_extractions)
2266
+
2267
+ # Log extraction results per page
2268
+ page_ents = sum(len(e.entities) for e in page_extractions)
2269
+ page_facts = sum(len(e.facts) for e in page_extractions)
2270
+ page_rels = sum(len(e.relationships) for e in page_extractions)
2271
+ ent_names = []
2272
+ for ext in page_extractions:
2273
+ for e in ext.entities:
2274
+ name = e.get("properties", {}).get("name", "")
2275
+ label = e.get("label", "")
2276
+ if name:
2277
+ ent_names.append(f"{label}:{name}")
2278
+ rel_descs = []
2279
+ for ext in page_extractions:
2280
+ for r in ext.relationships:
2281
+ rel_descs.append(f"{r.get('source_name','')} --{r.get('label','')}--> {r.get('target_name','')}")
2282
+
2283
+ if on_stage:
2284
+ on_stage("extract_result", {
2285
+ "message": f" Found {page_ents} entities, {page_facts} facts, {page_rels} relationships",
2286
+ "entities": ent_names[:15],
2287
+ "relationships": rel_descs[:10],
2288
+ })
2289
+
2290
+ # ── Phase 5: Build graphs + embed + index (batch) ─────────────
2291
+ if on_stage:
2292
+ on_stage("crawl_build", {"message": f"Building graph for {len(all_page_data)} pages"})
2293
+
2294
+ from .graph_builder import build_graph
2295
+ logger.info("[CRAWL_BUILD] db type: %s, has add_node: %s, has csr_adapter: %s",
2296
+ type(db).__name__, hasattr(db, 'add_node'), hasattr(db, 'csr_adapter'))
2297
+
2298
+ # Accumulate node IDs across all pages for LMDB indexing
2299
+ _all_passage_ids: dict = {}
2300
+ _all_entity_ids: dict = {}
2301
+ _all_fact_ids: dict = {}
2302
+
2303
+ for i, (url, doc, chunks, extractions) in enumerate(all_page_data):
2304
+ try:
2305
+ if on_stage:
2306
+ on_stage("build_page", {"message": f"[{i+1}/{len(all_page_data)}] Linking: {doc.title[:40]}"})
2307
+
2308
+ page_result = build_graph(doc, chunks, extractions, db, schema, pipeline_name=pipeline)
2309
+ _all_passage_ids.update(page_result.passage_ids or {})
2310
+ _all_entity_ids.update(page_result.entity_ids or {})
2311
+ _all_fact_ids.update(page_result.fact_ids or {})
2312
+ logger.info("[CRAWL_BUILD] Page '%s': doc_id=%s, passages=%d, entities=%d, facts=%d, edges=%d",
2313
+ doc.title[:30], page_result.document_id, len(page_result.passage_ids),
2314
+ len(page_result.entity_ids), len(page_result.fact_ids), page_result.edge_count)
2315
+
2316
+ if page_result.document_id:
2317
+ # Collect entity names for logging
2318
+ ent_detail = []
2319
+ for key, eid in list(page_result.entity_ids.items())[:10]:
2320
+ node = db.csr_adapter.get_node(eid)
2321
+ if node:
2322
+ ent_detail.append(f"[{getattr(node, 'node_type', getattr(node, 'label', ''))}] {node.properties.get('name', '')}")
2323
+
2324
+ results["ingested"].append({
2325
+ "url": url, "title": doc.title,
2326
+ "document_id": page_result.document_id,
2327
+ "passages": len(page_result.passage_ids),
2328
+ "entities": len(page_result.entity_ids),
2329
+ "facts": len(page_result.fact_ids),
2330
+ "edges": page_result.edge_count,
2331
+ "entity_names": ent_detail,
2332
+ })
2333
+ if on_stage:
2334
+ on_stage("build_result", {
2335
+ "message": f" Created: {len(page_result.passage_ids)} passages, {len(page_result.entity_ids)} entities, {len(page_result.fact_ids)} facts, {page_result.edge_count} edges",
2336
+ "entities": ent_detail,
2337
+ })
2338
+ else:
2339
+ results["failed"].append({"url": url, "reason": "build returned no document_id"})
2340
+ logger.warning("[CRAWL_BUILD] No document_id for '%s' — build_graph returned empty result", url[:60])
2341
+ if on_stage:
2342
+ on_stage("build_error", {"message": f" [WARN] No document created for: {doc.title[:50]}"})
2343
+ except Exception as e:
2344
+ results["failed"].append({"url": url, "reason": str(e)})
2345
+ logger.error("[CRAWL_BUILD] Exception building graph for '%s': %s", url[:60], e, exc_info=True)
2346
+ if on_stage:
2347
+ on_stage("build_error", {"message": f" [ERROR] {doc.title[:40]}: {str(e)[:80]}"})
2348
+
2349
+ # ── Phase 6: Batch embed + index ─────────────────────────────
2350
+ if results["ingested"]:
2351
+ if on_stage:
2352
+ on_stage("crawl_embed", {"message": f"Embedding nodes from {len(results['ingested'])} pages"})
2353
+ try:
2354
+ from ..context.vector_integration import get_session_vector_store
2355
+ svs = get_session_vector_store()
2356
+ ns = db.name
2357
+ if svs and svs.available:
2358
+ all_nodes = db.csr_adapter.get_all_nodes()
2359
+ embed_candidates = [
2360
+ n for n in all_nodes
2361
+ if getattr(n, 'node_type', getattr(n, 'label', '')) in
2362
+ ('Passage', 'Entity', 'Person', 'Organization', 'Location', 'Event', 'Fact')
2363
+ and not n.properties.get('_embedded')
2364
+ ]
2365
+ if on_stage:
2366
+ on_stage("crawl_embed_start", {
2367
+ "message": f"Embedding {len(embed_candidates)} nodes (vector store: {type(svs).__name__})",
2368
+ "nodes_to_embed": len(embed_candidates),
2369
+ })
2370
+ embedded = 0
2371
+ skipped_embed = 0
2372
+ for node in embed_candidates:
2373
+ label = getattr(node, 'node_type', getattr(node, 'label', ''))
2374
+ text = node.properties.get('content', node.properties.get('statement', ''))
2375
+ if not text:
2376
+ text = node.properties.get('name', '')
2377
+ if text and len(text) > 5:
2378
+ try:
2379
+ ok = svs.add_text(ns, text[:1000], node.id, metadata={
2380
+ "label": label, "name": node.properties.get("name", ""),
2381
+ })
2382
+ if ok:
2383
+ node.properties["_embedded"] = True
2384
+ db.csr_adapter.update_node_properties(node.id, node.properties)
2385
+ embedded += 1
2386
+ except Exception as e:
2387
+ logger.warning("Failed to embed node %s: %s", node.id[:12], e)
2388
+ else:
2389
+ skipped_embed += 1
2390
+ if on_stage:
2391
+ on_stage("crawl_embedded", {
2392
+ "message": (
2393
+ f"Embedded {embedded}/{len(embed_candidates)} nodes"
2394
+ + (f" ({skipped_embed} skipped — no text)" if skipped_embed else "")
2395
+ ),
2396
+ "embedded": embedded,
2397
+ "skipped": skipped_embed,
2398
+ })
2399
+ except Exception as e:
2400
+ logger.warning("Batch embed failed: %s", e)
2401
+
2402
+ if on_stage:
2403
+ on_stage("crawl_index", {"message": "Building BM25 search indexes"})
2404
+ try:
2405
+ class _CrawlResult:
2406
+ passage_ids = _all_passage_ids
2407
+ entity_ids = _all_entity_ids
2408
+ fact_ids = _all_fact_ids
2409
+ _index_bm25(_CrawlResult(), db)
2410
+ except Exception:
2411
+ pass
2412
+
2413
+ total_time = time.time() - t0
2414
+
2415
+ # Record ingested URLs in Redis for future dedup
2416
+ if results.get("ingested"):
2417
+ try:
2418
+ import os as _os
2419
+ import redis as _redis_dedup
2420
+ _rurl = _os.environ.get("CONTEXTSYNAPSE_REDIS_URL") or os.environ.get("AICONTEXTDB_REDIS_URL")
2421
+ if _rurl:
2422
+ _rconn = _redis_dedup.from_url(_rurl)
2423
+ _graph_name = getattr(db, 'namespace', '') or getattr(db, '_namespace', '') or getattr(db, 'name', '')
2424
+ _dedup_key = f"contextcore:ingested_urls:{_graph_name}"
2425
+ ingested_urls = [p["url"] for p in results["ingested"] if isinstance(p, dict) and p.get("url")]
2426
+ if not ingested_urls:
2427
+ ingested_urls = list(visited) # fallback to all visited URLs
2428
+ if ingested_urls:
2429
+ _rconn.sadd(_dedup_key, *ingested_urls)
2430
+ logger.info("[CRAWL] Recorded %d URLs as ingested for future dedup", len(ingested_urls))
2431
+ except Exception:
2432
+ pass
2433
+
2434
+ if on_stage:
2435
+ on_stage("crawl_done", {
2436
+ "message": f"Crawl complete in {total_time:.0f}s: {len(results['ingested'])} ingested, {len(results['filtered'])} filtered, {len(results['failed'])} failed out of {results['total_crawled']} pages"
2437
+ })
2438
+
2439
+ return results
2440
+
2441
+
2442
+ def get_staging(staging_id: str) -> Optional[StagingResult]:
2443
+ """Retrieve a staged preview by ID."""
2444
+ return _staging_store.get(staging_id)
2445
+
2446
+
2447
+ def list_pipelines() -> Dict[str, Dict]:
2448
+ """List available ingestion pipelines with descriptions."""
2449
+ return dict(PIPELINES)
2450
+
2451
+