Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Align guides with current source APIs (#676)

Mohd Kaif5db740100e84
diff --git a/docs/docs.json b/docs/docs.json
index a6eed795..95d11a5c 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -73,7 +73,29 @@
"group": "Guides",
"pages": [
"architecture",
- "learning-more"
+ "learning-more",
+ "guides/graphrag",
+ "guides/ingest",
+ "guides/llm-integrations",
+ "guides/pipeline",
+ "guides/multi-agent",
+ "guides/decision-intelligence",
+ "guides/context-graphs",
+ "guides/agent-memory",
+ "guides/provenance",
+ "guides/semantic-extraction",
+ "guides/ontology",
+ "guides/reasoning",
+ "guides/export",
+ "guides/deduplication",
+ "guides/mcp-server",
+ "guides/shacl-validation",
+ "guides/conflict-resolution",
+ "guides/change-management",
+ "guides/policy-engine",
+ "guides/visualization",
+ "guides/distance-intelligence",
+ "guides/graph-analytics"
]
},
{
@@ -120,6 +142,28 @@
{
"group": "Context & Intelligence",
"pages": [
+ "guides/graphrag",
+ "guides/ingest",
+ "guides/llm-integrations",
+ "guides/pipeline",
+ "guides/multi-agent",
+ "guides/decision-intelligence",
+ "guides/context-graphs",
+ "guides/agent-memory",
+ "guides/provenance",
+ "guides/semantic-extraction",
+ "guides/ontology",
+ "guides/reasoning",
+ "guides/export",
+ "guides/deduplication",
+ "guides/mcp-server",
+ "guides/shacl-validation",
+ "guides/conflict-resolution",
+ "guides/change-management",
+ "guides/policy-engine",
+ "guides/visualization",
+ "guides/distance-intelligence",
+ "guides/graph-analytics",
"reference/context",
"reference/kg",
"reference/temporal",
diff --git a/docs/guides/agent-memory.md b/docs/guides/agent-memory.md
new file mode 100644
index 00000000..3b4f0a01
--- /dev/null
+++ b/docs/guides/agent-memory.md
@@ -0,0 +1,617 @@
+---
+title: "Agent Memory"
+description: "How AgentContext stores, retrieves, and manages persistent agent memory — hierarchical short-term and long-term layers, FAISS-backed semantic retrieval, graph-enriched context, and cross-session persistence across defense, security, clinical, and financial deployments."
+icon: "brain"
+---
+
+`AgentContext` maintains a persistent memory layer for LLM agents — storing observations as vector embeddings, retrieving them by semantic similarity, and optionally blending graph proximity into the ranking. Use it when your agent needs to recall past findings across sessions without re-reading source material on every restart.
+
+<Info>
+ This guide covers the memory layer. For graph-enriched traversal and entity linking, see [Context Graphs](context-graphs). For decision accountability — recording, auditing, and causally tracing what the agent chose — see [Decision Intelligence](decision-intelligence).
+</Info>
+
+## Setting Up a Persistent Memory Context
+
+Configure the vector store, knowledge graph, and `AgentContext` together at startup so all three components persist to disk at the same path.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+# The FAISS index persists to disk at index_path — restart-safe
+ti_vs = VectorStore(
+ backend="faiss",
+ dimension=768,
+ index_path="ti_agent/memory.faiss",
+)
+
+# The ContextGraph holds entity nodes and their relationships
+ti_graph = ContextGraph(advanced_analytics=True)
+
+# AgentContext orchestrates everything
+ti_agent = AgentContext(
+ vector_store=ti_vs,
+ knowledge_graph=ti_graph,
+ retention_days=365, # CTI reports stay relevant for a year
+ max_memories=50000, # ring buffer ceiling — oldest evicted first
+ graph_expansion=True, # enable multi-hop graph traversal in retrieve()
+ max_expansion_hops=2,
+ hybrid_alpha=0.5, # 50% semantic score / 50% graph-structural score
+ decision_tracking=True, # enable record_decision() and find_precedents()
+ kg_algorithms=True, # Node2Vec embeddings, centrality, link prediction
+)
+```
+
+The `hybrid_alpha` parameter controls how retrieval blends semantic similarity (pure vector search) with graph-structural similarity (topology of the knowledge graph). At `0.5` the agent treats both signals equally. For a freshly ingested corpus with a sparse graph, you might start closer to `0.0` and increase as the graph fills in.
+
+## Storing What the Agent Learns
+
+### Single observations
+
+Every piece of intelligence the agent processes can be stored with a single call. The string is embedded and indexed immediately; the optional metadata travels with it and is available in every retrieval result.
+
+```python
+# Store a single finding from an OSINT feed
+memory_id = ti_agent.store(
+ "APT29 uses HAMMERTOSS for C2 communication over Twitter and GitHub",
+ metadata={
+ "source": "mandiant_apt29_report",
+ "actor": "APT29",
+ "technique": "T1102", # Web Service
+ "tlp": "WHITE",
+ },
+)
+# memory_id is a UUID string — use it to retrieve or forget this item later
+
+# Tag observations to an active incident so they can be retrieved as a group
+ti_agent.store(
+ "New C2 indicator: c2-upd4te[.]ru resolves to 185.220.101.47, cert hash a3f4b8c1...",
+ metadata={"type": "ioc", "confidence": 0.92, "source": "internal_hunt"},
+ conversation_id="incident_ir2025_0847",
+ user_id="analyst_zhang",
+)
+```
+
+The `conversation_id` acts as a namespace. Memories tagged with `incident_ir2025_0847` can be retrieved as a group later — useful for building a per-incident context window without polluting the global search index.
+
+### Ingesting document corpora
+
+When `store()` receives a list, it treats each element as a document, builds a graph of entities and relationships extracted from the text, and returns statistics about what was created.
+
+```python
+stats = ti_agent.store(
+ [
+ {
+ "content": "APT29 infrastructure cluster: 185.220.101.0/24, AS200651",
+ "metadata": {"source": "shadowserver", "actor": "APT29", "ioc_type": "network"},
+ },
+ {
+ "content": "SolarWinds supply chain compromise attributed to APT29, 2020",
+ "metadata": {"source": "us_cert_aa20-352a", "actor": "APT29", "campaign": "SUNBURST"},
+ },
+ {
+ "content": "NOBELIUM (APT29) leverages OAuth token theft against cloud workloads",
+ "metadata": {"source": "msft_blog_2023", "actor": "APT29", "technique": "T1528"},
+ },
+ ],
+ extract_entities=True, # extract actor, IP, CVE, technique nodes
+ extract_relationships=True, # link actor → campaign → technique → infrastructure
+ link_entities=True, # merge duplicate entity mentions across docs
+)
+
+print("Stored: {}, Graph nodes: {}, Graph edges: {}".format(
+ stats["stored_count"], # 3 — one per document
+ stats["graph_nodes"], # entities extracted and upserted into the graph
+ stats["graph_edges"], # relationships between those entities
+))
+```
+
+After this call the knowledge graph contains nodes for APT29, HAMMERTOSS, the infrastructure subnet, the SUNBURST campaign, and OAuth token theft — all linked to each other. Those graph links are what enable multi-hop retrieval: ask about "cloud OAuth attacks" and the agent can follow the graph from the technique node back to APT29 and then forward to the infrastructure indicators.
+
+## Retrieving Relevant Memory
+
+### Semantic retrieval
+
+The most direct retrieval call searches by semantic similarity — no keyword match required. The embedding of your query is compared against all stored memory embeddings, and the top matches are returned with scores.
+
+```python
+results = ti_agent.retrieve(
+ "cloud OAuth token theft campaigns",
+ max_results=8,
+ min_score=0.2,
+)
+
+for r in results:
+ actor = r.get("metadata", {}).get("actor", "unknown")
+ print("[{:.3f}] [{}] {}".format(r["score"], actor, r["content"][:80]))
+
+# [0.912] [APT29] NOBELIUM (APT29) leverages OAuth token theft against cloud workloads
+# [0.741] [APT29] SolarWinds supply chain compromise attributed to APT29, 2020
+# [0.683] [APT29] APT29 infrastructure cluster: 185.220.101.0/24, AS200651
+```
+
+The agent found the OAuth finding at the top — not because the query contained the exact phrase, but because the embedding space places "cloud OAuth token theft campaigns" close to "NOBELIUM leverages OAuth token theft against cloud workloads."
+
+### Graph-anchored retrieval with proximity scoring
+
+When you have a specific entity as the center of your investigation, anchor the retrieval to that node and blend semantic score with graph-proximity score.
+
+```python
+results = ti_agent.retrieve(
+ "cloud OAuth token theft campaigns",
+ max_results=10,
+ use_graph=True,
+ anchor_node="APT29", # BFS starts from this node in the knowledge graph
+ max_hops=3,
+ proximity_weight=0.35, # 65% semantic + 35% proximity — tune to your graph density
+ min_score=0.1,
+)
+
+for r in results:
+ # combined_score blends semantic score and graph proximity
+ score = r.get("combined_score", r["score"])
+ hop = r.get("hop_distance", "-")
+ band = r.get("distance_band", "-") # "direct", "near", "mid-range", "distant"
+ print("[{:.3f}] hop={} band={} {}".format(score, hop, band, r["content"][:70]))
+```
+
+The `proximity_weight` parameter is a per-call override — you can use heavy proximity weighting when pivoting on a specific actor and drop back to pure semantic search when exploring broadly.
+
+### Graph-grounded reasoning
+
+When you need a natural-language answer that synthesizes multiple memory items, use `query_with_reasoning()` to retrieve context from the graph and ask the LLM to ground its answer in those sources.
+
+```python
+from semantica.llms import Groq
+
+llm = Groq(model="llama-3.1-8b-instant", api_key="YOUR_GROQ_KEY")
+
+result = ti_agent.query_with_reasoning(
+ "Which threat actors are associated with SMB lateral movement in EMEA "
+ "and what infrastructure do they share with cloud OAuth campaigns?",
+ llm_provider=llm,
+ max_results=15,
+ max_hops=3,
+)
+
+print(result["response"]) # grounded natural-language answer
+print(result["confidence"]) # aggregated retrieval confidence score
+
+# Inspect the sources the answer is grounded in
+for src in result["sources"]:
+ print(" -", src["content"][:60])
+```
+
+The result includes a `reasoning_path` field that traces exactly which graph edges were traversed to reach the answer — useful for analyst review and audit.
+
+## Building a Working Memory Window
+
+Use the `conversation_id` filter to scope retrieval to the active session and combine incident-scoped history with global semantic search.
+
+```python
+incident_id = "ir2025_0847"
+
+# Store each new alert as it arrives, tagged to the incident
+ti_agent.store(
+ "Alert: lateral movement detected from WKSTN-047 to DC01 via SMB (PsExec artifact)",
+ metadata={"type": "alert", "severity": "critical", "technique": "T1021.002"},
+ conversation_id=incident_id,
+ user_id="analyst_zhang",
+)
+
+ti_agent.store(
+ "Analyst note: WKSTN-047 user jsmith flagged for suspicious login from 10.2.5.40 at 03:14 UTC",
+ metadata={"type": "analyst_note"},
+ conversation_id=incident_id,
+ user_id="analyst_zhang",
+)
+
+# Retrieve the full incident thread
+incident_history = ti_agent.conversation(
+ incident_id,
+ max_items=50,
+ reverse=False, # chronological order
+ include_metadata=True,
+)
+
+for item in incident_history:
+ role = item["metadata"].get("type", "note")
+ print("[{}] {}".format(role, item["content"][:80]))
+
+# Combine incident-scoped history with a semantic search across global memory
+context_items = ti_agent.retrieve(
+ "SMB lateral movement PsExec domain controller",
+ max_results=5,
+ use_graph=True,
+ conversation_id=incident_id, # filter to this incident's memories only
+)
+```
+
+This pattern lets the agent build a focused working memory window for each incident while the global vector index accumulates knowledge across all incidents over time.
+
+## Domain Examples
+
+<Tabs>
+<Tab title="Defense — CTI/Threat">
+A threat-intelligence fusion cell ingests OSINT feeds, MISP events, and internal hunt findings continuously. The agent must correlate new indicators against known actor profiles and produce attribution assessments grounded in accumulated intelligence — not just the latest report.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import Groq
+
+ti_graph = ContextGraph(advanced_analytics=True, node_embeddings=True)
+ti_agent = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768, index_path="ti_memory.faiss"),
+ knowledge_graph=ti_graph,
+ retention_days=365,
+ max_memories=50000,
+ hybrid_alpha=0.6,
+ decision_tracking=True,
+)
+
+# Ingest a fresh CTI report — entities and infrastructure flow into the graph
+ti_agent.store(
+ [
+ {"content": "APT29 infrastructure cluster: 185.220.101.0/24, AS200651",
+ "metadata": {"source": "shadowserver", "actor": "APT29", "tlp": "WHITE"}},
+ {"content": "SolarWinds supply chain compromise attributed to APT29, campaign SUNBURST",
+ "metadata": {"source": "us_cert_aa20-352a", "actor": "APT29", "campaign": "SUNBURST"}},
+ {"content": "NOBELIUM (APT29) leverages OAuth token theft against cloud workloads",
+ "metadata": {"source": "msft_blog_2023", "actor": "APT29", "technique": "T1528"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+# New hunt finding — is this C2 domain connected to APT29?
+ti_agent.store(
+ "New C2 indicator: c2-upd4te[.]ru resolves to 185.220.101.47, cert hash a3f4b8...",
+ metadata={"type": "ioc", "confidence": 0.92, "source": "internal_hunt"},
+ conversation_id="hunt_2025_q3",
+)
+
+# Graph-anchored attribution query: start from APT29, traverse 3 hops
+llm = Groq(model="llama-3.1-8b-instant", api_key="YOUR_GROQ_KEY")
+attribution = ti_agent.query_with_reasoning(
+ "Is c2-upd4te[.]ru connected to APT29 based on infrastructure overlap?",
+ llm_provider=llm,
+ max_results=10,
+ max_hops=3,
+)
+print(attribution["response"])
+print("Confidence: {:.0%}".format(attribution["confidence"]))
+
+# Persist intelligence base across analyst shifts
+ti_agent.save("ti_state/")
+```
+
+</Tab>
+<Tab title="Security — SOC/Incident">
+A SOC analyst assistant carries context across shift handoffs. Tier 1 logs the initial alert and triage verdict; Tier 2 picks up with full incident history already loaded, without reading back through a ticket trail. The agent surfaces relevant runbook steps and finds similar past incidents for MTTR estimation.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import Groq
+
+soc_graph = ContextGraph()
+soc_agent = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768, index_path="soc_memory.faiss"),
+ knowledge_graph=soc_graph,
+ retention_days=180,
+ max_memories=100000,
+ decision_tracking=True,
+)
+
+# Preload runbook knowledge base once — it persists across restarts
+soc_agent.store([
+ "T1021.002 (SMB/Windows Admin Shares): isolate host, reset service accounts, check for credential dumping",
+ "T1003.001 (LSASS Memory): collect memory dump, run Mimikatz signatures, notify IR team",
+ "T1190 (Exploit Public-Facing Application): check WAF logs, correlate with CVE feed, patch window 4h",
+])
+
+incident_id = "ir-2025-0847"
+
+# Tier 1 logs the alert
+soc_agent.store(
+ "Alert: host WKSTN-047 failed 14 Kerberos AS-REQ in 30s from 10.2.5.40",
+ metadata={"type": "alert", "severity": "high", "technique": "T1110.003"},
+ conversation_id=incident_id,
+ user_id="tier1_chen",
+)
+soc_agent.store(
+ "Lateral movement confirmed: 10.2.5.40 connected to DC01 via PsExec",
+ metadata={"type": "finding", "severity": "critical", "technique": "T1021.002"},
+ conversation_id=incident_id,
+ user_id="tier1_chen",
+)
+
+# Record the containment decision for audit and precedent matching
+decision_id = soc_agent.record_decision(
+ category="containment",
+ scenario="Confirmed lateral movement from WKSTN-047 to DC01 via SMB",
+ reasoning="PsExec artifact detected; immediate isolation prevents DC compromise",
+ outcome="isolated_wkstn047",
+ confidence=0.95,
+ entities=["WKSTN-047", "DC01"],
+ decision_maker="tier1_chen",
+)
+
+# Surface the matching runbook steps
+runbook = soc_agent.retrieve(
+ "SMB lateral movement with PsExec to domain controller",
+ max_results=3,
+ use_graph=True,
+)
+for step in runbook:
+ print("[{:.3f}] {}".format(step["score"], step["content"]))
+
+# Find similar past incidents — Tier 2 uses these to estimate resolution time
+precedents = soc_agent.find_precedents(
+ "lateral movement SMB domain controller compromise",
+ category="containment",
+ limit=3,
+)
+for p in precedents:
+ print("Past: {} -> {} ({:.0%})".format(p.scenario[:50], p.outcome, p.confidence))
+
+# Tier 2 loads the full incident context without reading the ticket
+soc_agent.save("soc_state/")
+```
+
+</Tab>
+<Tab title="Life Science — Clinical/Pharma">
+A clinical decision support agent maintains patient context across consultations and carries treatment history forward. The agent surfaces guideline contraindications before a prescribing decision, then records the decision with full causal tracing for MDT audit.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+clinical_graph = ContextGraph(advanced_analytics=True)
+clinical_agent = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768, index_path="clinical.faiss"),
+ knowledge_graph=clinical_graph,
+ retention_days=3650, # 10-year clinical record retention
+ max_memories=500000,
+ decision_tracking=True,
+)
+
+# Load guidelines once — ADA, BNF, NICE — persists across sessions
+clinical_agent.store([
+ {"content": "ACE inhibitors are first-line for hypertension in diabetic patients (ADA 2024)",
+ "metadata": {"source": "ADA_2024", "category": "guideline", "strength": "A"}},
+ {"content": "Metformin contraindicated in eGFR < 30 mL/min/1.73m2 — risk of lactic acidosis",
+ "metadata": {"source": "BNF_2024", "category": "contraindication", "strength": "absolute"}},
+ {"content": "SGLT2 inhibitors reduce cardiovascular events in T2DM with CKD stage 3a (CREDENCE trial)",
+ "metadata": {"source": "NEJM_CREDENCE", "category": "guideline", "strength": "A"}},
+], extract_entities=True, extract_relationships=True)
+
+patient_id = "PT-00841"
+
+# Build patient context for this consultation
+clinical_agent.store(
+ "Patient PT-00841: T2DM, hypertension, eGFR 28 mL/min/1.73m2, no penicillin allergy",
+ metadata={"type": "patient_summary", "patient_id": patient_id},
+ conversation_id="consult_2025_07_01",
+ user_id="dr_okonkwo",
+)
+clinical_agent.store(
+ "Current medications: lisinopril 10mg, atorvastatin 40mg, aspirin 75mg",
+ metadata={"type": "medication_list", "patient_id": patient_id},
+ conversation_id="consult_2025_07_01",
+)
+
+# Before prescribing metformin — check the guideline base
+contraindications = clinical_agent.retrieve(
+ "metformin prescribing with reduced kidney function eGFR",
+ max_results=5,
+ use_graph=True,
+ conversation_id="consult_2025_07_01",
+)
+for item in contraindications:
+ category = item.get("metadata", {}).get("category", "?")
+ print("[{:.3f}] [{}] {}".format(item["score"], category, item["content"][:80]))
+# [0.947] [contraindication] Metformin contraindicated in eGFR < 30 mL/min/1.73m2 ...
+# [0.821] [guideline] SGLT2 inhibitors reduce cardiovascular events in T2DM with CKD ...
+
+# Record the decision — eGFR 28 falls below the absolute contraindication threshold
+decision_id = clinical_agent.record_decision(
+ category="treatment_modification",
+ scenario="T2DM patient PT-00841 eGFR 28: metformin dose review required",
+ reasoning=(
+ "eGFR 28 falls below absolute contraindication threshold of 30 mL/min/1.73m2 "
+ "per BNF_2024. Discontinue metformin; initiate dapagliflozin review per CREDENCE."
+ ),
+ outcome="discontinued_metformin_initiated_dapagliflozin_review",
+ confidence=0.97,
+ entities=["PT-00841", "metformin", "dapagliflozin", "eGFR"],
+ decision_maker="dr_okonkwo",
+)
+
+# Explainability trace for MDT audit
+explanation = clinical_agent.trace_decision_explainability(decision_id)
+print("Guideline connections traced: {}".format(explanation.get("total_connections", 0)))
+
+clinical_agent.save("clinical_state/{}/".format(patient_id))
+```
+
+</Tab>
+<Tab title="Banking — Risk/Compliance">
+A mortgage underwriting agent carries regulatory knowledge and application context through the decisioning workflow. Every credit decision is recorded with the exact regulatory guidance that grounded it, producing a defensible audit trail for model risk governance review.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+credit_graph = ContextGraph(advanced_analytics=True)
+credit_agent = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768, index_path="credit.faiss"),
+ knowledge_graph=credit_graph,
+ retention_days=2555, # 7-year regulatory retention
+ max_memories=1000000,
+ decision_tracking=True,
+ kg_algorithms=True,
+)
+
+# Load regulatory knowledge base — Basel III, CRR, EBA guidelines
+credit_agent.store([
+ {"content": "Basel III: CET1 capital ratio minimum 4.5% + 2.5% conservation buffer",
+ "metadata": {"source": "BCBS_Basel3", "category": "capital_requirement"}},
+ {"content": "PD floor for retail exposures: 0.1% under IRB approach (CRR Art. 160)",
+ "metadata": {"source": "CRR_Art160", "category": "risk_parameter"}},
+ {"content": "DSTI ratio > 40% requires enhanced creditworthiness assessment per EBA GL 2020/06",
+ "metadata": {"source": "EBA_GL_2020_06", "category": "affordability"}},
+ {"content": "Adverse action notice required within 30 days of credit denial (ECOA Reg. B)",
+ "metadata": {"source": "ECOA_RegB", "category": "regulatory_obligation"}},
+], extract_entities=True, extract_relationships=True)
+
+app_id = "APP-2025-994421"
+
+# Load application context
+credit_agent.store(
+ "Applicant APP-2025-994421: gross income 82000 GBP, requested 320000 GBP 30yr mortgage, LTV 78%",
+ metadata={"type": "application_summary", "app_id": app_id},
+ conversation_id=app_id,
+)
+credit_agent.store(
+ "Credit bureau: score 714, 0 defaults in 7yr, 2 hard inquiries last 12mo, DSTI 38%",
+ metadata={"type": "bureau_data", "app_id": app_id},
+ conversation_id=app_id,
+)
+
+# Retrieve regulatory guidance relevant to this application
+guidance = credit_agent.retrieve(
+ "mortgage affordability DSTI 38% regulatory requirements LTV 78%",
+ max_results=5,
+ use_graph=True,
+ conversation_id=app_id,
+)
+for g in guidance:
+ source = g.get("metadata", {}).get("source", "?")
+ print("[{:.3f}] [{}] {}".format(g["score"], source, g["content"][:80]))
+# [0.891] [EBA_GL_2020_06] DSTI ratio > 40% requires enhanced creditworthiness ...
+# [0.724] [CRR_Art160] PD floor for retail exposures: 0.1% under IRB approach ...
+
+# Record the decision — DSTI 38% is below the 40% EBA threshold
+decision_id = credit_agent.record_decision(
+ category="mortgage_origination",
+ scenario="320k GBP 30yr mortgage, LTV 78%, DSTI 38%, credit score 714",
+ reasoning=(
+ "Score 714 exceeds 680 floor; DSTI 38% within EBA GL 2020/06 threshold of 40%; "
+ "LTV 78% requires standard LMI; no derogatory history in 7yr; "
+ "stress test at +300bps passes affordability."
+ ),
+ outcome="approved_conditional_lmi",
+ confidence=0.89,
+ entities=[app_id, "LTV_78pct", "DSTI_38pct"],
+ decision_maker="underwriting_model_v4",
+)
+
+# Find similar precedents for model governance review
+precedents = credit_agent.find_precedents(
+ "mortgage approval borderline DSTI affordability stress test",
+ category="mortgage_origination",
+ limit=5,
+)
+for p in precedents:
+ print("Precedent: {} -> {} ({:.0%})".format(p.scenario[:50], p.outcome, p.confidence))
+
+credit_agent.save("credit_state/{}/".format(app_id))
+```
+
+</Tab>
+</Tabs>
+
+## Persisting and Restoring State
+
+At the end of an analyst shift — or before a process restart — call `save()` to write the full context to disk. On next startup, call `load()` to restore it completely.
+
+```python
+# save() writes memory JSON plus backend-specific vector-store artifacts
+# under agent_state/vector_store/ and the graph export at knowledge_graph.json.
+# With the default VectorStore implementation this includes:
+# agent_state/agent_memory.json
+# agent_state/vector_store/store_data.pkl
+# agent_state/vector_store/index.bin
+# agent_state/knowledge_graph.json
+ti_agent.save("agent_state/")
+```
+
+When a new process starts — or a new analyst logs in — restore from that checkpoint:
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+# Create a fresh context with matching configuration
+ti_agent_restored = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768, index_path="ti_memory.faiss"),
+ knowledge_graph=ContextGraph(advanced_analytics=True),
+ retention_days=365,
+ decision_tracking=True,
+)
+
+# load() restores all three components from disk
+ti_agent_restored.load("agent_state/")
+
+# Every memory, graph edge, and decision precedent is now available
+results = ti_agent_restored.retrieve("APT29 OAuth token theft cloud infrastructure")
+```
+
+<Info>
+ `AgentMemory` itself is saved as JSON, but the vector store persists its own index and vector payload separately. `load()` restores those backend artifacts rather than re-embedding memories on demand, so keep the same vector-store backend, dimension, and scoring setup across sessions.
+</Info>
+
+## Taking Checkpoints During Analysis
+
+For long-running analysis loops, take named snapshots before and after key steps so you can diff what the agent added during each phase.
+
+```python
+# Snapshot before the analysis loop starts
+ti_agent.checkpoint("pre_enrichment")
+
+# ... store new evidence, extract entities, record decisions ...
+
+# Snapshot after enrichment completes
+ti_agent.checkpoint("post_enrichment")
+
+# See exactly what changed
+diff = ti_agent.diff_checkpoints("pre_enrichment", "post_enrichment")
+print("Decisions added: {}".format(len(diff["decisions_added"])))
+print("Relationships added: {}".format(len(diff["relationships_added"])))
+
+# Optionally persist via TemporalVersionManager (requires temporal_version_manager= at init)
+# ti_agent.flush_checkpoint("post_enrichment")
+```
+
+## Memory Lifecycle and Housekeeping
+
+Retention is applied automatically on every `store()` call — items older than `retention_days` are pruned without any manual intervention. You can also remove specific memories or clear a full conversation namespace.
+
+```python
+# Forget a specific memory by ID
+ti_agent.forget(memory_id="some-uuid-string")
+
+# Clear all memories tagged to a specific incident
+cleared = ti_agent.forget(conversation_id="incident_ir2025_0847")
+print("Cleared {} items".format(cleared))
+
+# Clear everything older than 90 days
+old_cleared = ti_agent.clear(days_old=90)
+
+# Get current memory statistics
+s = ti_agent.stats()
+print("Total memories: {}".format(s.get("total_items", 0)))
+```
+
+## Related Guides
+
+- [Context Graphs](context-graphs) — How the underlying `ContextGraph` stores entity nodes and decision nodes; temporal interval reasoning; deduplication before node insertion; ontology from graph.
+- [Decision Intelligence](decision-intelligence) — Recording decisions as graph nodes with causal chains and policy gating.
+- [Multi-Agent Systems](multi-agent) — Coordinating multiple agents through a shared `AgentContext` and save/load handoffs.
+- [LLM Integrations](llm-integrations) — Configuring the LLM provider passed to `query_with_reasoning()`.
+- [Deduplication Guide](deduplication) — Full reference for `DuplicateDetector`, `EntityMerger`, similarity methods, and cluster strategies.
+- [Ontology Management](ontology) — Generate and validate OWL ontologies from the knowledge graph; export to Turtle, OWL/XML, JSON-LD.
+- [Context Module Reference](../reference/context) — Full API: `AgentContext`, `AgentMemory`, `MemoryItem`, `ContextRetriever`.
+- [Vector Store Reference](../reference/vector_store) — FAISS, Qdrant, pgvector, Pinecone backends.
diff --git a/docs/guides/change-management.md b/docs/guides/change-management.md
new file mode 100644
index 00000000..2031f68d
--- /dev/null
+++ b/docs/guides/change-management.md
@@ -0,0 +1,404 @@
+---
+title: "Change Management & Versioning"
+description: "Snapshot, version, diff, and migrate knowledge graphs and ontologies over time — with SQLite persistence, checksum verification, and structured change logs."
+icon: "clock-rotate-left"
+---
+
+Knowledge graphs change constantly — threat actors get re-attributed, CVE scores update when exploits drop, clinical trial endpoints shift between phases. `TemporalVersionManager` gives your graph a verifiable history: named snapshots before every consequential change, diffs between any two states, one-call rollback, and SHA-256 checksum verification before publishing downstream.
+
+<Info>
+ `TemporalVersionManager` integrates with `AgentContext.flush_checkpoint()` — agent checkpoints and manual snapshots share the same storage format, so diffs work across both.
+</Info>
+
+## Creating Snapshots
+
+Take a snapshot before any consequential change: an ingestion sweep, a partner feed merge, or an automated enrichment run.
+
+```python
+from semantica.change_management import TemporalVersionManager
+from semantica.context import ContextGraph
+
+graph = ContextGraph()
+graph.add_node("apt29", "ThreatActor", "APT29 / NOBELIUM")
+graph.add_node("cve-2024-3400", "Vulnerability", "CVE-2024-3400 PAN-OS RCE")
+graph.add_edge("apt29", "cve-2024-3400", "exploits", weight=0.97)
+
+vm = TemporalVersionManager(storage_path="cti_versions.db")
+
+snap_pre = vm.create_snapshot(
+ graph = graph.to_dict(),
+ version_label = "q3_2025_baseline",
+ author = "analyst_zhang",
+ description = "CTI baseline before Q3 OSINT sweep",
+)
+
+print(snap_pre["label"]) # "q3_2025_baseline"
+print(snap_pre["checksum"]) # SHA-256 of the serialized graph
+print(snap_pre["timestamp"]) # ISO datetime
+print(snap_pre["author"]) # "analyst_zhang"
+print(len(snap_pre["nodes"])) # node count at snapshot time
+print(len(snap_pre["edges"])) # edge count at snapshot time
+```
+
+After running the ingestion, snapshot again to mark the post-change state:
+
+```python
+graph.add_node("cve-2024-21412", "Vulnerability", "CVE-2024-21412 Windows SmartScreen bypass")
+graph.add_node("apt40", "ThreatActor", "APT40 / BRONZE MOHAWK")
+graph.add_edge("apt40", "cve-2024-21412", "exploits", weight=0.88)
+
+snap_post = vm.create_snapshot(
+ graph = graph.to_dict(),
+ version_label = "q3_2025_post_nvd_sweep",
+ author = "osint_pipeline",
+ description = "After NVD weekly sweep — 2025-07-14",
+)
+```
+
+## Comparing Two Snapshots
+
+`compare_versions` returns a precise diff — nodes and edges added, removed, or modified — between any two named snapshots.
+
+```python
+diff = vm.compare_versions("q3_2025_baseline", "q3_2025_post_nvd_sweep")
+
+s = diff["summary"]
+print("Nodes added :", s["nodes_added"]) # 2
+print("Nodes removed :", s["nodes_removed"]) # 0
+print("Edges added :", s["edges_added"]) # 1
+
+for node in diff["nodes_added"]:
+ print(" +", node.get("id"), "/", node.get("content"))
+
+for edge in diff["edges_added"]:
+ print(" +", edge.get("source"), "→", edge.get("target"), "[" + edge.get("type", "") + "]")
+```
+
+You can also pass snapshot dicts directly instead of labels:
+
+```python
+diff = vm.compare_versions(snap_pre, snap_post)
+```
+
+## Verifying Integrity
+
+Before publishing a snapshot to a downstream system — SIEM, partner feed, regulatory submission — verify the SHA-256 checksum to confirm nothing was modified after the snapshot was written.
+
+```python
+snap = vm.get_version("q3_2025_post_nvd_sweep")
+
+if not vm.verify_checksum(snap):
+ raise RuntimeError("Checksum mismatch on q3_2025_post_nvd_sweep — aborting publish.")
+
+print("Integrity verified — safe to publish.")
+```
+
+## Rolling Back
+
+Pass the target label and `require_confirmation=False` (an explicit safety gate) to restore the graph to any prior snapshot.
+
+```python
+vm.restore_snapshot(
+ graph = graph,
+ target_version = "q3_2025_baseline",
+ require_confirmation = False,
+)
+
+# Record the rollback event as a new snapshot
+vm.create_snapshot(
+ graph = graph.to_dict(),
+ version_label = "q3_2025_rollback",
+ author = "analyst_zhang",
+ description = "Rolled back to baseline after corrupted OSINT batch",
+)
+```
+
+<Info>
+ `restore_snapshot` raises `ProcessingError` if `require_confirmation` is not explicitly `False`, preventing accidental rollbacks from automated scripts.
+</Info>
+
+## Building an Audit Changelog
+
+List all snapshots in chronological order and diff each one against its predecessor to produce a human-readable change log.
+
+```python
+versions = sorted(vm.list_versions(), key=lambda v: v["timestamp"])
+
+print("Graph Change Log")
+print("=" * 60)
+
+for i, v in enumerate(versions):
+ print("\n[{}] {} (by {})".format(v["timestamp"][:10], v["label"], v["author"]))
+ print(" " + v["description"])
+
+ if i > 0:
+ diff = vm.compare_versions(versions[i - 1]["label"], v["label"])
+ s = diff["summary"]
+ print(" Changes: +{} nodes -{} nodes +{} edges -{} edges".format(
+ s["nodes_added"], s["nodes_removed"],
+ s["edges_added"], s["edges_removed"],
+ ))
+```
+
+Sample output:
+
+```text
+Graph Change Log
+============================================================
+
+[2025-07-01] q3_2025_baseline (by analyst_zhang)
+ CTI baseline before Q3 OSINT sweep
+
+[2025-07-14] q3_2025_post_nvd_sweep (by osint_pipeline)
+ After NVD weekly sweep — 2025-07-14
+ Changes: +2 nodes -0 nodes +1 edges -0 edges
+
+[2025-07-14] q3_2025_rollback (by analyst_zhang)
+ Rolled back to baseline after corrupted OSINT batch
+ Changes: -2 nodes +0 nodes -1 edges +0 edges
+```
+
+## Tagging Milestones
+
+Attach a named tag to any snapshot to mark review gates, approved states, or regulatory submissions.
+
+```python
+vm.tag_version("q3_2025_post_nvd_sweep", "q3-approved")
+
+for tag_name, version_label in vm.list_tags().items():
+ print(f"{tag_name:20s} → {version_label}")
+# q3-approved → q3_2025_post_nvd_sweep
+```
+
+## Node History
+
+Attach `TemporalVersionManager` to a live `ContextGraph` to automatically record every individual mutation — every `add_node`, `add_edge`, and update call — not just snapshot-level diffs.
+
+```python
+vm.attach_to_graph(graph)
+
+graph.add_node("apt29-alias", "ThreatActor", "NOBELIUM (rebranding 2021)")
+graph.add_edge("apt29", "apt29-alias", "alias_of", weight=1.0)
+
+for record in vm.get_node_history("apt29"):
+ print("[{}] {} on {} payload={}".format(
+ record["timestamp"], record["operation"], record["entity_id"],
+ str(record["payload"])[:60],
+ ))
+```
+
+## AgentContext Integration
+
+Pass the version manager at `AgentContext` construction. Agent checkpoints and manual snapshots share the same storage, giving you one unified history.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.change_management import TemporalVersionManager
+
+graph = ContextGraph()
+vm = TemporalVersionManager(storage_path="agent_versions.db")
+
+context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ temporal_version_manager = vm,
+)
+
+context.store("APT29 targeting NATO infrastructure in Q3 2025")
+context.checkpoint("pre_analysis")
+
+# ... agent reasoning loop ...
+
+context.checkpoint("post_analysis")
+context.flush_checkpoint("post_analysis") # persists via vm
+
+diff = context.diff_checkpoints("pre_analysis", "post_analysis")
+print("Decisions added :", len(diff["decisions_added"]))
+print("Relationships added:", len(diff["relationships_added"]))
+```
+
+## Domain Examples
+
+<Tabs>
+ <Tab title="Defense — CTI Pipeline">
+ Daily NVD and ISAC feed ingestion with pre/post snapshots, a SOC change bulletin, and an integrity gate before publishing to the SIEM.
+
+```python
+from semantica.change_management import TemporalVersionManager
+from semantica.context import ContextGraph
+import datetime
+
+graph = ContextGraph()
+vm = TemporalVersionManager(storage_path="cti_versions.db")
+today = datetime.date.today().isoformat()
+
+snap_pre = vm.create_snapshot(
+ graph = graph.to_dict(),
+ version_label = f"pre_nvd_{today}",
+ author = "osint_pipeline",
+ description = "CTI baseline before NVD sweep",
+)
+
+# Ingestion
+graph.add_node("cve-2025-1337", "Vulnerability", "CVE-2025-1337 critical RCE")
+graph.add_node("apt29-q3-cluster", "ThreatActor", "APT29 Q3 2025 campaign cluster")
+graph.add_edge("apt29-q3-cluster", "cve-2025-1337", "weaponizes", weight=0.91)
+
+snap_post = vm.create_snapshot(
+ graph = graph.to_dict(),
+ version_label = f"post_nvd_{today}",
+ author = "osint_pipeline",
+ description = "After NVD sweep",
+)
+
+diff = vm.compare_versions(snap_pre["label"], snap_post["label"])
+s = diff["summary"]
+print(f"SOC Bulletin: +{s['nodes_added']} threat nodes, +{s['edges_added']} relationships")
+for n in diff["nodes_added"]:
+ print(f" + [{n.get('type')}] {n.get('content')}")
+
+if not vm.verify_checksum(snap_post):
+ raise RuntimeError("Checksum mismatch — aborting SIEM publish")
+print("Snapshot verified — publishing to SIEM feed.")
+```
+
+ </Tab>
+
+ <Tab title="Security — Incident Response">
+ Snapshot the incident graph at each major discovery during a live IR engagement so the post-mortem can replay exactly how the investigation evolved.
+
+```python
+from semantica.change_management import TemporalVersionManager
+from semantica.context import ContextGraph
+
+graph = ContextGraph()
+vm = TemporalVersionManager(storage_path="incident_ir042.db")
+
+# T+0: Initial triage
+graph.add_node("wkstn-047", "Host", "Compromised workstation WKSTN-047")
+graph.add_node("attacker-ip", "Network", "Attacker ingress 185.220.101.47")
+graph.add_edge("attacker-ip", "wkstn-047", "initial_access", weight=0.95)
+
+vm.create_snapshot(
+ graph = graph.to_dict(),
+ version_label = "ir042_t0_triage",
+ author = "analyst_chen",
+ description = "T+0 — one compromised host identified",
+)
+
+# T+2h: Lateral movement confirmed
+graph.add_node("dc01", "Host", "Domain controller DC01")
+graph.add_node("svc-backup", "Account", "Stolen service account SVC-BACKUP")
+graph.add_edge("wkstn-047", "svc-backup", "credential_theft", weight=0.88)
+graph.add_edge("svc-backup", "dc01", "lateral_move", weight=0.82)
+
+vm.create_snapshot(
+ graph = graph.to_dict(),
+ version_label = "ir042_t2h_lateral",
+ author = "analyst_chen",
+ description = "T+2h — lateral movement to DC01 via stolen SVC-BACKUP",
+)
+
+diff = vm.compare_versions("ir042_t0_triage", "ir042_t2h_lateral")
+s = diff["summary"]
+print(f"Post-mortem T+0→T+2h: +{s['nodes_added']} hosts/accounts, +{s['edges_added']} attack paths")
+for edge in diff["edges_added"]:
+ print(f" + {edge.get('source')} → {edge.get('target')} [{edge.get('type')}]")
+```
+
+ </Tab>
+
+ <Tab title="Life Science — Clinical Trial">
+ Version the trial knowledge graph across phases to produce a machine-verifiable diff between Phase II and Phase III submissions for regulatory review.
+
+```python
+from semantica.change_management import TemporalVersionManager
+from semantica.context import ContextGraph
+
+graph_ph2 = ContextGraph()
+graph_ph2.add_node("compound-xr401", "Compound", "XR-401")
+graph_ph2.add_node("endpoint-orr", "Endpoint", "Overall Response Rate")
+graph_ph2.add_node("disease-nsclc", "Disease", "NSCLC")
+
+graph_ph3 = ContextGraph()
+graph_ph3.add_node("compound-xr401", "Compound", "XR-401")
+graph_ph3.add_node("endpoint-orr", "Endpoint", "Overall Response Rate")
+graph_ph3.add_node("endpoint-pfs", "Endpoint", "Progression-Free Survival")
+graph_ph3.add_node("disease-nsclc", "Disease", "NSCLC")
+graph_ph3.add_node("comparator-doce", "Comparator", "Docetaxel")
+
+vm = TemporalVersionManager(storage_path="trial_xr401.db")
+
+vm.create_snapshot(
+ graph=graph_ph2.to_dict(), version_label="phase_ii_v1.0",
+ author="clinical_data_team", description="Phase II — ORR primary, NSCLC",
+)
+vm.create_snapshot(
+ graph=graph_ph3.to_dict(), version_label="phase_iii_v2.0",
+ author="clinical_data_team", description="Phase III — PFS co-primary, Docetaxel added",
+)
+
+diff = vm.compare_versions("phase_ii_v1.0", "phase_iii_v2.0")
+print("Regulatory diff Phase II → Phase III:")
+for n in diff["nodes_added"]:
+ print(f" + [{n.get('type')}] {n.get('content')}")
+
+snap = vm.get_version("phase_iii_v2.0")
+assert vm.verify_checksum(snap), "Checksum failed — cannot attach to dossier"
+print("Phase III snapshot verified — safe for regulatory submission.")
+```
+
+ </Tab>
+
+ <Tab title="Banking — Model Governance">
+ Version the Basel III credit risk model graph on each regulatory update and produce a machine-verifiable diff for the model governance committee before production deployment.
+
+```python
+from semantica.change_management import TemporalVersionManager
+from semantica.context import ContextGraph
+
+graph = ContextGraph()
+graph.add_node("metric-cet1", "CapitalMetric", "CET1 Capital Ratio")
+graph.add_node("metric-ltv", "RiskParameter", "LTV Ratio")
+graph.add_node("metric-pd", "RiskParameter", "Probability of Default")
+graph.add_node("metric-lgd", "RiskParameter", "Loss Given Default")
+graph.add_node("regulation-cre20", "Regulation", "Basel III CRE20")
+
+vm = TemporalVersionManager(storage_path="credit_risk_versions.db")
+
+vm.create_snapshot(
+ graph=graph.to_dict(), version_label="basel_v1.0",
+ author="risk_model_team", description="Basel III CRE20 initial graph",
+)
+
+# Regulatory update — DSCR becomes mandatory
+graph.add_node("metric-dscr", "RiskParameter", "Debt Service Coverage Ratio")
+graph.add_edge("regulation-cre20", "metric-dscr", "requires", weight=1.0)
+
+vm.create_snapshot(
+ graph=graph.to_dict(), version_label="basel_v1.1",
+ author="risk_model_team", description="DSCR added per EBA GL 2020/06",
+)
+
+diff = vm.compare_versions("basel_v1.0", "basel_v1.1")
+s = diff["summary"]
+print(f"Model governance diff v1.0→v1.1: +{s['nodes_added']} params, +{s['edges_added']} rules")
+for n in diff["nodes_added"]:
+ print(f" + [{n.get('type')}] {n.get('content')}")
+
+snap = vm.get_version("basel_v1.1")
+assert vm.verify_checksum(snap), "Checksum failed — aborting model deployment"
+print("Model v1.1 verified and approved for production.")
+```
+
+ </Tab>
+</Tabs>
+
+## Related Guides
+
+- [Context Graphs](context-graphs) — `ContextGraph.to_dict()` feeds `create_snapshot()`
+- [Ontology Management](ontology) — pair ontology versioning with graph versioning for a complete schema + data audit trail
+- [SHACL Validation](shacl-validation) — validate graph data at each version gate before snapshotting
+- [Provenance](provenance) — combine change management with W3C PROV-O lineage for a full audit trail
+- [Visualization](visualization) — `TemporalVisualizer.visualize_snapshot_comparison()` and `visualize_metrics_evolution()` render version diffs as interactive charts
diff --git a/docs/guides/conflict-resolution.md b/docs/guides/conflict-resolution.md
new file mode 100644
index 00000000..67d533c1
--- /dev/null
+++ b/docs/guides/conflict-resolution.md
@@ -0,0 +1,477 @@
+---
+title: "Conflict Detection & Resolution"
+description: "Detect value, type, and relationship conflicts across multi-source knowledge graphs and resolve them automatically with seven configurable strategies."
+icon: "code-merge"
+---
+
+`ConflictDetector` surfaces properties where multiple sources disagree on the same canonical entity, and `ConflictResolver` applies per-property strategies — credibility-weighted voting, most-recent, expert review, and others — to produce a single resolved value with a full audit trail. Run it after deduplication and before SHACL validation.
+
+<Info>
+Run conflict detection after deduplication and before SHACL validation. Deduplication removes duplicate nodes; conflict resolution reconciles disagreeing property values on the same canonical entity. Running them out of order — detecting conflicts before deduplication — will produce spurious conflicts between entities that should have been merged first.
+</Info>
+
+## Detecting the disagreement
+
+Start by loading your multi-source records for the same entity. `ConflictDetector` groups them by entity ID, then compares the values each source reports for a given property. Any entity where two or more sources report different values for the same property produces a `Conflict` object.
+
+```python
+from semantica.conflicts import ConflictDetector, ConflictResolver, ResolutionStrategy
+
+# Three authoritative sources on the same CVE — all credible, all disagreeing
+cve_records = [
+ {
+ "id": "cve-2024-3400",
+ "source": "nvd",
+ "cvss_score": 10.0,
+ "exploit_status": "unconfirmed",
+ "vector": "AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H",
+ "credibility_score": 0.98,
+ },
+ {
+ "id": "cve-2024-3400",
+ "source": "commercial_feed",
+ "cvss_score": 9.1,
+ "exploit_status": "in_wild",
+ "vector": "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
+ "credibility_score": 0.91,
+ },
+ {
+ "id": "cve-2024-3400",
+ "source": "vendor_paloalto",
+ "cvss_score": 9.5,
+ "exploit_status": "in_wild",
+ "vector": "AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:H",
+ "credibility_score": 0.87,
+ },
+]
+
+detector = ConflictDetector()
+
+# Detect disagreements on the CVSS score property
+score_conflicts = detector.detect_value_conflicts(cve_records, property_name="cvss_score")
+exploit_conflicts = detector.detect_value_conflicts(cve_records, property_name="exploit_status")
+
+print(f"CVSS score conflicts : {len(score_conflicts)}")
+print(f"Exploit status conflicts: {len(exploit_conflicts)}")
+
+for c in score_conflicts:
+ print(f"\nConflict: {c.conflict_id}")
+ print(f" Entity : {c.entity_id}")
+ print(f" Property : {c.property_name}")
+ print(f" Values : {c.conflicting_values}") # [10.0, 9.1, 9.5]
+ print(f" Severity : {c.severity}") # 'medium' — numeric difference < 1000
+ print(f" Sources : {[s['document'] for s in c.sources]}")
+ print(f" Action : {c.recommended_action}")
+```
+
+```text
+CVSS score conflicts : 1
+Exploit status conflicts: 1
+
+Conflict: cve-2024-3400_cvss_score_conflict
+ Entity : cve-2024-3400
+ Property : cvss_score
+ Values : [10.0, 9.1, 9.5]
+ Severity : medium
+ Sources : ['nvd', 'commercial_feed', 'vendor_paloalto']
+ Action : Compare source documents and use most recent or authoritative source
+```
+
+Each `Conflict` captures the full picture: which entity, which property, every disagreeing value, and which source reported each. This is already enough to build a review queue — but the goal is to resolve these automatically according to rules you set.
+
+## Setting per-property resolution rules
+
+The key method is `set_resolution_rule(entity_id, property_name, strategy)`. It takes three arguments: which entity, which property, and which `ResolutionStrategy` to apply when that combination appears in a conflict. Rules are stored in the resolver and automatically applied when you call `resolve_conflicts()` without passing an explicit strategy.
+
+```python
+resolver = ConflictResolver()
+
+# For this CVE, NVD is the most authoritative source on scoring.
+# CREDIBILITY_WEIGHTED will use the credibility_score field on each source record
+# to weight the vote — NVD at 0.98 will dominate over the commercial feed at 0.91.
+resolver.set_resolution_rule(
+ "cve-2024-3400",
+ "cvss_score",
+ ResolutionStrategy.CREDIBILITY_WEIGHTED,
+)
+
+# Exploitation status is time-sensitive: the commercial feed and vendor have both
+# observed in-the-wild exploitation, which is more current than NVD's initial
+# unconfirmed assessment. MOST_RECENT picks the value from the source with the
+# latest timestamp in its metadata.
+resolver.set_resolution_rule(
+ "cve-2024-3400",
+ "exploit_status",
+ ResolutionStrategy.MOST_RECENT,
+)
+```
+
+You can set rules before or after detection — the resolver applies them lazily when `resolve_conflicts()` is called.
+
+## Resolving the batch
+
+Pass all detected conflicts to `resolve_conflicts()`. For each conflict, the resolver looks up whether a property-specific rule is set for that entity and property combination. If one is found, it applies that strategy. If none is set, it falls back to the default strategy (voting, unless you override it in the constructor).
+
+```python
+all_conflicts = score_conflicts + exploit_conflicts
+
+results = resolver.resolve_conflicts(all_conflicts)
+
+for r in results:
+ status = "RESOLVED" if r.resolved else "REVIEW REQUIRED"
+ print(f"[{status}] {r.conflict_id}")
+ print(f" Resolved value : {r.resolved_value}")
+ print(f" Strategy used : {r.resolution_strategy}")
+ print(f" Confidence : {r.confidence:.0%}")
+ print(f" Sources used : {r.sources_used}")
+ print(f" Notes : {r.resolution_notes}")
+ print()
+```
+
+```text
+[RESOLVED] cve-2024-3400_cvss_score_conflict
+ Resolved value : 10.0
+ Strategy used : credibility_weighted
+ Confidence : 72%
+ Sources used : ['nvd', 'commercial_feed', 'vendor_paloalto']
+ Notes : Resolved by credibility-weighted voting (weight: 0.98)
+
+[RESOLVED] cve-2024-3400_exploit_status_conflict
+ Resolved value : in_wild
+ Strategy used : most_recent
+ Confidence : 80%
+ Sources used : ['commercial_feed']
+ Notes : Resolved by most recent value
+```
+
+NVD wins the CVSS score — its credibility weight (0.98) edges out the commercial feed (0.91) and the vendor (0.87), so 10.0 becomes the canonical score. The exploitation status resolves to `in_wild` — the commercial feed and vendor advisory are both more recent than NVD's initial triage, and both report active exploitation.
+
+## Handling conflicts that need human judgment
+
+Not every conflict can be auto-resolved. A disagreement about the legal classification of a financial instrument, or about a patient's current medication list, is too consequential to resolve by algorithm. Flag these for review without blocking the rest of the batch:
+
+```python
+from semantica.conflicts import ConflictDetector, ConflictResolver, ResolutionStrategy
+
+# Drug trial data: efficacy agreed, primary endpoint disputed
+trial_records = [
+ {"id": "dapagliflozin", "source": "declare_timi58",
+ "primary_endpoint": "MACE", "hba1c_reduction_pct": 0.54,
+ "credibility_score": 0.92},
+ {"id": "dapagliflozin", "source": "dapa_hf",
+ "primary_endpoint": "HF_hospitalization", "hba1c_reduction_pct": 0.48,
+ "credibility_score": 0.95},
+ {"id": "dapagliflozin", "source": "meta_analysis",
+ "primary_endpoint": "HbA1c_reduction", "hba1c_reduction_pct": 0.52,
+ "credibility_score": 0.88},
+]
+
+detector = ConflictDetector()
+efficacy_conflicts = detector.detect_value_conflicts(trial_records, "hba1c_reduction_pct")
+endpoint_conflicts = detector.detect_value_conflicts(trial_records, "primary_endpoint")
+
+resolver = ConflictResolver()
+
+# Efficacy: credibility-weighted across trials — the meta-analysis (0.88) and
+# the two RCTs (0.92, 0.95) will produce a weighted resolution.
+resolver.set_resolution_rule(
+ "dapagliflozin", "hba1c_reduction_pct", ResolutionStrategy.CREDIBILITY_WEIGHTED
+)
+
+# Primary endpoint: each trial measured a different thing. This is not a conflict
+# to auto-resolve — a clinician must decide which endpoint applies to the use case.
+resolver.set_resolution_rule(
+ "dapagliflozin", "primary_endpoint", ResolutionStrategy.EXPERT_REVIEW
+)
+
+all_conflicts = efficacy_conflicts + endpoint_conflicts
+results = resolver.resolve_conflicts(all_conflicts)
+
+auto_resolved = [r for r in results if r.resolved]
+for_review = [r for r in results if not r.resolved]
+
+print(f"Auto-resolved : {len(auto_resolved)}")
+print(f"Expert review : {len(for_review)}")
+
+# Export the review queue for the clinical team
+import json
+review_queue = [
+ {
+ "conflict_id": r.conflict_id,
+ "notes": r.resolution_notes,
+ "metadata": r.metadata,
+ }
+ for r in for_review
+]
+with open("expert_review_queue.json", "w") as fh:
+ json.dump(review_queue, fh, indent=2, default=str)
+```
+
+```text
+Auto-resolved : 1
+Expert review : 1 # primary_endpoint — EXPERT_REVIEW means resolved=False
+```
+
+`EXPERT_REVIEW` sets `resolved=False` on the result. The conflict stays in the graph unresolved, the metadata field carries `requires_expert_review: True`, and the review queue JSON gives your clinical team exactly what they need to make the call.
+
+## Reviewing the full audit trail
+
+After a resolution run, `get_resolution_history()` returns every decision made since the resolver was instantiated. This is your compliance log:
+
+```python
+history = resolver.get_resolution_history()
+
+print(f"Total resolutions logged: {len(history)}")
+for r in history:
+ status = "RESOLVED" if r.resolved else "PENDING"
+ print(f"[{status}] {r.conflict_id}")
+ print(f" Strategy : {r.resolution_strategy}")
+ print(f" Value : {r.resolved_value}")
+ print(f" Confidence : {r.confidence:.0%}")
+```
+
+Pair this with the full conflict report from the detector to get aggregate statistics across all runs:
+
+```python
+report = detector.get_conflict_report()
+
+print(f"Total conflicts detected : {report['total_conflicts']}")
+print(f"By type : {report['by_type']}")
+print(f"By severity : {report['by_severity']}")
+# Total conflicts detected : 2
+# By type : {'value_conflict': 2}
+# By severity : {'medium': 2}
+```
+
+The report aggregates every conflict the detector has seen across its lifetime — useful for pipeline monitoring and for identifying which entity types or data sources generate the most disagreements.
+
+## Detecting relationship conflicts
+
+Value conflicts live on properties. Relationship conflicts live on edges — two sources asserting contradictory connections between the same node pair:
+
+```python
+# Two intelligence sources disagree about whether APT29 exploits this CVE
+relationships = [
+ {"source": "apt29", "target": "cve-2024-3400",
+ "type": "EXPLOITS", "origin": "mandiant"},
+ {"source": "apt29", "target": "cve-2024-3400",
+ "type": "UNRELATED_TO", "origin": "crowdstrike"},
+]
+
+rel_conflicts = detector.detect_relationship_conflicts(relationships)
+for c in rel_conflicts:
+ print(f"Relationship conflict: {c.conflict_id}")
+ print(f" Edge type values: {c.conflicting_values}")
+ print(f" Severity: {c.severity}")
+```
+
+Relationship conflicts typically require expert review rather than voting, because conflicting edge types often reflect genuinely different intelligence assessments rather than data entry errors.
+
+## Domain examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+A threat intelligence platform merges actor profiles from Mandiant, CrowdStrike, and an open-source blog. The three sources agree that APT29 is Russian and espionage-motivated, but disagree on when it was first observed and — critically — one source attributes it to China. The low-credibility source (the blog, at 0.30) should lose to the high-credibility sources (Mandiant at 0.95, CrowdStrike at 0.92) when those sources are in agreement.
+
+Credibility-weighted resolution handles this cleanly: the blog's misattribution is drowned out by the combined weight of the two authoritative vendors. The `first_seen` date disagreement (2008 vs 2009) is also resolved by credibility weight, giving Mandiant's 2008 date the win.
+
+```python
+from semantica.conflicts import ConflictDetector, ConflictResolver, ResolutionStrategy
+
+actor_profiles = [
+ {"id": "apt29", "source": "mandiant", "nation_state": "Russia",
+ "first_seen": "2008", "credibility_score": 0.95},
+ {"id": "apt29", "source": "crowdstrike", "nation_state": "Russia",
+ "first_seen": "2009", "credibility_score": 0.92},
+ {"id": "apt29", "source": "oss_blog", "nation_state": "China", # wrong
+ "first_seen": "2015", "credibility_score": 0.30},
+]
+
+detector = ConflictDetector()
+nation_conflicts = detector.detect_value_conflicts(actor_profiles, "nation_state")
+first_seen_conflicts = detector.detect_value_conflicts(actor_profiles, "first_seen")
+
+resolver = ConflictResolver()
+resolver.set_resolution_rule("apt29", "nation_state", ResolutionStrategy.CREDIBILITY_WEIGHTED)
+resolver.set_resolution_rule("apt29", "first_seen", ResolutionStrategy.CREDIBILITY_WEIGHTED)
+
+results = resolver.resolve_conflicts(nation_conflicts + first_seen_conflicts)
+for r in results:
+ print(f"{r.conflict_id}: {r.resolved_value!r} [{r.confidence:.0%} confidence]")
+ # apt29_nation_state_conflict: 'Russia' [83% confidence]
+ # apt29_first_seen_conflict: '2008' [73% confidence]
+ # The blog's China attribution (weight 0.30) loses to Mandiant+CrowdStrike (0.95+0.92).
+
+history = resolver.get_resolution_history()
+print(f"Audit log entries: {len(history)}")
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+A vulnerability management system ingests CVSS scores from NVD, MITRE, and a vendor advisory for the same CVE. NVD and MITRE are both authoritative; the vendor has self-interest in scoring conservatively. Credibility-weighted resolution gives NVD (0.98) and MITRE (0.96) dominance over the vendor (0.90), producing a canonical score that reflects the consensus of independent authorities.
+
+The CVSS vector string also conflicts — the scope field (`S:C` vs `S:U`) reflects a genuine interpretive disagreement that affects whether the CVE is classified as a network pivot risk. Both conflicts get the same credibility-weighted treatment.
+
+```python
+from semantica.conflicts import ConflictDetector, ConflictResolver, ResolutionStrategy
+
+cve_records = [
+ {"id": "cve-2024-3400", "source": "nvd",
+ "cvss_score": 10.0, "vector": "AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H",
+ "credibility_score": 0.98},
+ {"id": "cve-2024-3400", "source": "mitre",
+ "cvss_score": 9.8, "vector": "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
+ "credibility_score": 0.96},
+ {"id": "cve-2024-3400", "source": "paloalto",
+ "cvss_score": 9.5, "vector": "AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:H",
+ "credibility_score": 0.90},
+]
+
+detector = ConflictDetector()
+score_conflicts = detector.detect_value_conflicts(cve_records, "cvss_score")
+vector_conflicts = detector.detect_value_conflicts(cve_records, "vector")
+
+resolver = ConflictResolver()
+resolver.set_resolution_rule(
+ "cve-2024-3400", "cvss_score", ResolutionStrategy.CREDIBILITY_WEIGHTED
+)
+resolver.set_resolution_rule(
+ "cve-2024-3400", "vector", ResolutionStrategy.CREDIBILITY_WEIGHTED
+)
+
+results = resolver.resolve_conflicts(score_conflicts + vector_conflicts)
+for r in results:
+ if r.resolved:
+ print(f"Canonical {r.conflict_id.split('_')[2]}: {r.resolved_value} "
+ f"({r.confidence:.0%} confidence)")
+ # Canonical cvss_score: 10.0 (72% confidence) — NVD wins
+ # Canonical vector: AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H (54% confidence)
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+A drug safety knowledge graph merges dapagliflozin trial data from three studies: DECLARE-TIMI 58, DAPA-HF, and a meta-analysis. The HbA1c reduction values differ across trials because each enrolled a different population. The primary endpoint differs because each trial was designed to answer a different clinical question — a genuine scientific distinction, not a data error.
+
+Efficacy numbers can be credibility-weighted; disputed endpoints must go to expert review. This split handling — auto-resolve what you can, escalate what you can't — is the pattern for regulated data environments.
+
+```python
+from semantica.conflicts import ConflictDetector, ConflictResolver, ResolutionStrategy
+
+drug_records = [
+ {"id": "dapagliflozin", "source": "declare_timi58",
+ "hba1c_reduction_pct": 0.54, "primary_endpoint": "MACE",
+ "credibility_score": 0.92},
+ {"id": "dapagliflozin", "source": "dapa_hf",
+ "hba1c_reduction_pct": 0.48, "primary_endpoint": "HF_hospitalization",
+ "credibility_score": 0.95},
+ {"id": "dapagliflozin", "source": "meta_analysis",
+ "hba1c_reduction_pct": 0.52, "primary_endpoint": "HbA1c_reduction",
+ "credibility_score": 0.88},
+]
+
+detector = ConflictDetector()
+efficacy_conflicts = detector.detect_value_conflicts(drug_records, "hba1c_reduction_pct")
+endpoint_conflicts = detector.detect_value_conflicts(drug_records, "primary_endpoint")
+
+resolver = ConflictResolver()
+resolver.set_resolution_rule(
+ "dapagliflozin", "hba1c_reduction_pct", ResolutionStrategy.CREDIBILITY_WEIGHTED
+)
+resolver.set_resolution_rule(
+ "dapagliflozin", "primary_endpoint", ResolutionStrategy.EXPERT_REVIEW
+ # resolved=False — queued for clinician review, not auto-resolved
+)
+
+results = resolver.resolve_conflicts(efficacy_conflicts + endpoint_conflicts)
+auto = [r for r in results if r.resolved]
+review = [r for r in results if not r.resolved]
+
+print(f"Auto-resolved : {len(auto)}")
+for r in auto:
+ print(f" {r.conflict_id}: {r.resolved_value} [{r.confidence:.0%}]")
+ # dapagliflozin_hba1c_reduction_pct_conflict: 0.48 [38%]
+
+print(f"Expert queue : {len(review)}")
+for r in review:
+ print(f" {r.conflict_id} — {r.resolution_notes}")
+ # dapagliflozin_primary_endpoint_conflict — Flagged for expert review
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+A credit risk graph merges corporate client data from a CRM, the global LEI registry, and a credit bureau. The LEI registry is the legal authority on entity names and industry codes — its credibility should be set to 1.0 (or treated as definitive). The CRM and bureau may have stale or abbreviated names; the LEI registry has the officially registered legal name.
+
+Setting `CREDIBILITY_WEIGHTED` resolution for `legal_name` and `sic_code` with the LEI registry carrying a 0.99 credibility score ensures the legally authoritative value always wins, with full audit evidence for the next regulatory examination.
+
+```python
+from semantica.conflicts import ConflictDetector, ConflictResolver, ResolutionStrategy
+
+client_records = [
+ {"id": "corp-acme-uk", "source": "crm",
+ "legal_name": "ACME UK Ltd", "sic_code": "7372",
+ "credibility_score": 0.75},
+ {"id": "corp-acme-uk", "source": "lei_registry",
+ "legal_name": "ACME United Kingdom Limited", "sic_code": "7371",
+ "credibility_score": 0.99}, # LEI registry is authoritative
+ {"id": "corp-acme-uk", "source": "credit_bureau",
+ "legal_name": "ACME UK Ltd", "sic_code": "7372",
+ "credibility_score": 0.85},
+]
+
+detector = ConflictDetector()
+name_conflicts = detector.detect_value_conflicts(client_records, "legal_name")
+sic_conflicts = detector.detect_value_conflicts(client_records, "sic_code")
+
+resolver = ConflictResolver()
+resolver.set_resolution_rule(
+ "corp-acme-uk", "legal_name", ResolutionStrategy.CREDIBILITY_WEIGHTED
+)
+resolver.set_resolution_rule(
+ "corp-acme-uk", "sic_code", ResolutionStrategy.CREDIBILITY_WEIGHTED
+)
+
+results = resolver.resolve_conflicts(name_conflicts + sic_conflicts)
+for r in results:
+ print(f"Canonical {r.conflict_id.split('_')[2]}: {r.resolved_value!r} "
+ f"[{r.confidence:.0%}]")
+ # Canonical legal_name: 'ACME United Kingdom Limited' [53%] — LEI registry wins
+ # Canonical sic_code: '7371' [53%] — LEI registry wins
+
+# Aggregate conflict statistics for the compliance report
+report = detector.get_conflict_report()
+print(f"\nConflict audit:")
+print(f" Total detected : {report['total_conflicts']}")
+print(f" By severity : {report['by_severity']}")
+```
+
+</Tab>
+
+</Tabs>
+
+## Resolution strategies at a glance
+
+| Strategy | How it decides | Best when |
+| :--- | :--- | :--- |
+| `VOTING` | Most frequent value wins | 3+ independent sources; no clear authority |
+| `CREDIBILITY_WEIGHTED` | Values weighted by source `credibility_score` | Sources have known reliability rankings |
+| `MOST_RECENT` | Value from the source with the latest timestamp | Data decays quickly — threat intel, market prices |
+| `FIRST_SEEN` | Value from the first source to assert it | Primary sources are more reliable than derivatives |
+| `HIGHEST_CONFIDENCE` | Value from the source with the highest `confidence` field | Automated extractors emit per-record confidence scores |
+| `MANUAL_REVIEW` | Flags the conflict; `resolved=False` | Low-volume, high-stakes decisions |
+| `EXPERT_REVIEW` | Flags for domain expert queue; `resolved=False` | Scientific or legal disambiguation required |
+
+## Related Guides
+
+- [Deduplication](deduplication) — remove duplicate nodes before running conflict detection
+- [Provenance](provenance) — track which source each resolved value came from, and verify the audit trail cryptographically
+- [SHACL Validation](shacl-validation) — enforce structural constraints after conflicts are resolved
+- [Change Management](change-management) — snapshot the graph before and after conflict resolution runs
+- [Ontology Management](ontology) — align entity types to a shared vocabulary to reduce type conflicts at the schema level
diff --git a/docs/guides/context-graphs.md b/docs/guides/context-graphs.md
new file mode 100644
index 00000000..15631df3
--- /dev/null
+++ b/docs/guides/context-graphs.md
@@ -0,0 +1,617 @@
+---
+title: "Context Graphs"
+description: "How Semantica stores, links, searches, and traverses knowledge as a thread-safe in-memory property graph — with temporal validity, cross-graph navigation, proximity-blended retrieval, and conversation-to-graph construction."
+icon: "diagram-project"
+---
+
+`ContextGraph` is a thread-safe, in-memory property graph with temporal validity windows on every node and edge, built-in BFS traversal, a FAISS vector index for semantic search, and proximity-blended retrieval through `AgentContext`. Use it when multiple agents or threads write to a shared knowledge base while analysts query it in real time.
+
+<Info>
+ For analytical operations on top of a populated graph — centrality rankings, community detection, node embeddings, link prediction — see the [Graph Analytics guide](graph-analytics). For recording and querying decisions stored as nodes, see the [Decision Intelligence guide](decision-intelligence).
+</Info>
+
+## Constructing the Graph
+
+The simplest possible graph needs no arguments:
+
+```python
+from semantica.context import ContextGraph
+
+graph = ContextGraph()
+```
+
+For a threat intelligence workload that will also run analytics, enable the sub-components at construction time — they initialize lazily but must be declared upfront:
+
+```python
+graph = ContextGraph(
+ advanced_analytics = True,
+ centrality_analysis = True,
+ community_detection = True,
+ node_embeddings = True,
+)
+```
+
+The graph is backed entirely by Python dicts and a re-entrant lock (`threading.RLock`). No external service, no database connection, no network call. You can stand up a fully functional intelligence graph in a unit test with a single import.
+
+## Adding Your First Entities
+
+Every entity goes in as a node with a type, optional content string, and any number of metadata kwargs:
+
+```python
+# add_node(node_id, node_type, content=None, **properties) -> None
+# All extra kwargs land in ContextNode.metadata
+
+graph.add_node(
+ "APT29",
+ "ThreatActor",
+ "Russian state-sponsored group, also known as COZY BEAR",
+ origin="Russia",
+ motivation="espionage",
+ first_seen="2008",
+)
+
+graph.add_node(
+ "SUNBURST",
+ "Malware",
+ "Supply-chain backdoor embedded in SolarWinds Orion updates",
+ family="backdoor",
+ first_seen="2019-10",
+ platforms=["Windows"],
+)
+
+graph.add_node(
+ "CVE-2020-10148",
+ "Vulnerability",
+ "SolarWinds Orion API authentication bypass",
+ cvss=10.0,
+ affected_product="SolarWinds Orion",
+)
+
+graph.add_node(
+ "45.142.212.100",
+ "C2Domain",
+ "Command-and-control server observed in SUNBURST campaign",
+ asn="AS29550",
+ country="Netherlands",
+)
+
+graph.add_node(
+ "SolarWinds",
+ "Victim",
+ "SolarWinds Corporation — software supply chain victim",
+ sector="Technology",
+)
+```
+
+<Info>
+ There is no `properties={}` parameter. Pass all metadata fields as direct keyword arguments. Calling `add_node("x", "t", properties={"k": "v"})` would store the dict under a key literally named `properties` in metadata — not what you want.
+</Info>
+
+Now connect them with typed, weighted edges:
+
+```python
+# add_edge(source_id, target_id, edge_type="related_to", weight=1.0, **properties) -> None
+
+graph.add_edge("APT29", "SUNBURST", "uses", weight=1.0)
+graph.add_edge("SUNBURST", "CVE-2020-10148", "exploits", weight=0.95)
+graph.add_edge("SUNBURST", "SolarWinds", "targets", weight=1.0)
+graph.add_edge("APT29", "45.142.212.100", "operates", weight=0.9)
+graph.add_edge("SUNBURST", "45.142.212.100", "beacons_to", weight=0.85)
+graph.add_edge("CVE-2020-10148", "SolarWinds", "affects", weight=1.0)
+```
+
+Check what you have:
+
+```python
+s = graph.stats()
+print(f"Nodes: {s['node_count']}, Edges: {s['edge_count']}, Density: {s['density']:.4f}")
+# Nodes: 5, Edges: 6, Density: 0.3000
+
+print("Node types:", s["node_types"]) # {"ThreatActor": 1, "Malware": 1, ...}
+print("Edge types:", s["edge_types"]) # {"uses": 1, "exploits": 1, ...}
+```
+
+## Temporal Validity — Intel Has an Expiry Date
+
+Use `valid_from` and `valid_until` to mark nodes and edges with activity windows so temporal queries exclude stale data:
+
+```python
+# The C2 domain was only active during the campaign window
+graph.add_node(
+ "45.142.212.100",
+ "C2Domain",
+ "SUNBURST C2 — active during campaign",
+ asn="AS29550",
+ valid_from="2019-10-01T00:00:00",
+ valid_until="2020-12-17T00:00:00", # DarkHalo C2 shutdown date
+)
+
+# A detection rule with a limited effectiveness window
+graph.add_node(
+ "SIGMA-SUNBURST-001",
+ "DetectionRule",
+ "Sigma rule: SUNBURST beacon pattern",
+ rule_type="sigma",
+ valid_from="2020-12-13T00:00:00",
+ valid_until="2021-06-30T23:59:59", # deprecated after updated TTPs observed
+)
+
+# Temporal edges work the same way
+graph.add_edge(
+ "APT29", "45.142.212.100", "operates",
+ weight=0.9,
+ valid_from="2019-10-01T00:00:00",
+ valid_until="2020-12-17T00:00:00",
+)
+```
+
+Now ask: which nodes were active on December 1, 2020 (during the campaign)?
+
+```python
+from datetime import datetime
+
+# at_time must be a datetime object — not an ISO string
+active = graph.find_active_nodes(
+ node_type="C2Domain",
+ at_time=datetime(2020, 12, 1, 0, 0, 0),
+)
+print(f"Active C2 domains on 2020-12-01: {len(active)}")
+# Active C2 domains on 2020-12-01: 1 (45.142.212.100 is still in its window)
+
+# Compare to today — the C2 is expired
+active_now = graph.find_active_nodes(node_type="C2Domain") # defaults to datetime.now()
+print(f"Active C2 domains today: {len(active_now)}")
+# Active C2 domains today: 0
+
+# Full temporal snapshot — only nodes and edges valid at a given moment
+snapshot = graph.state_at(datetime(2020, 12, 1, 0, 0, 0))
+print(f"Active nodes: {len(snapshot['nodes'])}")
+print(f"Active edges: {len(snapshot['edges'])}")
+```
+
+This is how you prevent a query today from returning "APT29 currently operates 45.142.212.100" — the edge is outside its validity window and won't appear in temporal queries.
+
+## Finding Nodes
+
+`find_node()` retrieves by ID, and `find_nodes()` filters by type or metadata:
+
+```python
+# find_node(node_id) -> Optional[Dict]
+# Returns keys: "id", "type", "content", "metadata" — NOT "node_id" or "node_type"
+
+actor = graph.find_node("APT29")
+if actor:
+ print(actor["id"]) # "APT29"
+ print(actor["type"]) # "ThreatActor"
+ print(actor["content"]) # "Russian state-sponsored group..."
+ print(actor["metadata"]) # {"origin": "Russia", "motivation": "espionage", ...}
+
+# find_nodes(node_type=None, skip=0, limit=None) -> List[Dict]
+all_actors = graph.find_nodes(node_type="ThreatActor")
+all_vulns = graph.find_nodes(node_type="Vulnerability")
+```
+
+## Traversing the Graph
+
+BFS traversal answers reachability questions directly:
+
+```python
+# get_neighbors(node_id, hops=1, relationship_types=None,
+# min_weight=0.0, include_distance_metadata=False) -> List[Dict]
+# Each result: {"id", "type", "content", "relationship", "weight", "hop"}
+
+neighbors = graph.get_neighbors("APT29", hops=2)
+for n in neighbors:
+ print(f" hop={n['hop']} [{n['relationship']}] {n['id']} ({n['type']})")
+
+# hop=1 [uses] SUNBURST (Malware)
+# hop=1 [operates] 45.142.212.100 (C2Domain)
+# hop=2 [exploits] CVE-2020-10148 (Vulnerability)
+# hop=2 [targets] SolarWinds (Victim)
+# hop=2 [beacons_to] 45.142.212.100 (C2Domain) — also reachable via hop-1
+```
+
+Filter to only follow specific edge types — useful when you want to trace just the exploitation chain without noise from other relationship types:
+
+```python
+exploit_chain = graph.get_neighbors(
+ "APT29",
+ hops=3,
+ relationship_types=["uses", "exploits", "affects"],
+)
+```
+
+When you need to understand how confident a connection is based on graph distance, enable distance metadata. Each result gains a `confidence_decay` multiplier — nodes further away are weighted down:
+
+```python
+neighbors = graph.get_neighbors(
+ "APT29",
+ hops=3,
+ include_distance_metadata=True,
+)
+for n in neighbors:
+ print(f" {n['id']:30s} band={n['distance_band']:8s} decay={n['confidence_decay']:.3f}")
+
+# APT29's direct SUNBURST edge: band=direct decay=1.000
+# CVE reached via SUNBURST: band=near decay=0.850
+# SolarWinds reached via CVE: band=mid decay=0.700
+```
+
+For point-to-point routing, use the shortest path finder:
+
+```python
+# shortest_path(source_id, target_id, edge_types=None) -> Optional[List[str]]
+path = graph.shortest_path("APT29", "SolarWinds")
+if path:
+ print(" → ".join(path))
+# APT29 → SUNBURST → SolarWinds
+```
+
+When you need to analyze a sub-cluster in isolation, `extract_subgraph()` gives you a new independent `ContextGraph` instance:
+
+```python
+# extract_subgraph(node_ids, include_edges=True) -> ContextGraph
+campaign_nodes = ["APT29", "SUNBURST", "CVE-2020-10148", "45.142.212.100", "SolarWinds"]
+subgraph = graph.extract_subgraph(campaign_nodes)
+
+s = subgraph.stats()
+print(f"Subgraph: {s['node_count']} nodes, {s['edge_count']} edges")
+# Subgraph: 5 nodes, 6 edges
+```
+
+## Handling Concurrent Writes
+
+`ContextGraph` handles concurrent writes with a re-entrant lock (`threading.RLock`) that wraps every mutation — you do not need to add your own synchronization:
+
+```python
+import threading
+from semantica.context import ContextGraph
+
+graph = ContextGraph()
+
+def misp_ingest_worker(events):
+ for event in events:
+ graph.add_node(event["id"], event["type"], event["value"])
+ for attr in event.get("attributes", []):
+ graph.add_edge(event["id"], attr["value"], "has_attribute")
+
+def nvd_ingest_worker(cves):
+ for cve in cves:
+ graph.add_node(cve["id"], "Vulnerability", cve["description"], cvss=cve["cvss"])
+ graph.add_edge(cve["id"], cve["product"], "affects")
+
+# Both threads write safely to the same graph
+t1 = threading.Thread(target=misp_ingest_worker, args=(misp_events,))
+t2 = threading.Thread(target=nvd_ingest_worker, args=(nvd_batch,))
+t1.start(); t2.start()
+t1.join(); t2.join()
+
+print(graph.stats())
+```
+
+The lock is re-entrant, so internal calls that themselves acquire the lock (for example, `add_edge()` calling `find_node()` internally) won't deadlock.
+
+## Semantic Search via AgentContext
+
+`AgentContext` wraps the graph with a FAISS vector index and lets you retrieve by semantic similarity, with optional blending of graph proximity:
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+graph = ContextGraph()
+# ... (populated with CTI nodes as above)
+
+context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ hybrid_alpha = 0.5, # 50% semantic / 50% structural weighting
+ decision_tracking = True,
+)
+
+# Store intel summaries — these become searchable
+context.store("APT29 operated SUNBURST backdoor via SolarWinds supply chain compromise")
+context.store("45.142.212.100 is a C2 server associated with the SUNBURST campaign")
+context.store("CVE-2020-10148 allows unauthenticated API access in SolarWinds Orion")
+
+# Retrieve with graph proximity blending
+# anchor_node="APT29" means nodes close to APT29 in the graph score higher
+results = context.retrieve(
+ "APT29 infrastructure and C2 servers",
+ max_results = 10,
+ anchor_node = "APT29",
+ max_hops = 2,
+ proximity_weight = 0.3, # 30% graph proximity, 70% semantic score
+ use_graph = True,
+)
+
+for r in results:
+ # "score" — base semantic similarity (always present)
+ # "combined_score" — blended score (present when proximity_weight > 0)
+ # "distance_band" — "direct" / "near" / "mid" / "far"
+ score = r.get("combined_score", r.get("score", 0))
+ print(f"[{score:.3f}] {r.get('content', '')[:70]}")
+```
+
+`proximity_weight` is a **per-call parameter** on `retrieve()`, not a constructor setting. This means different queries can use different blending ratios on the same context object — a broad semantic search uses `proximity_weight=0.0`, while a neighborhood-focused traversal uses `proximity_weight=0.5`.
+
+## Cross-Graph Navigation
+
+`link_graph()` connects two separate graphs, and `cross_graph_path()` finds paths that span the boundary:
+
+```python
+from semantica.context import ContextGraph
+
+actor_graph = ContextGraph()
+victim_graph = ContextGraph()
+
+actor_graph.add_node("APT29", "ThreatActor", "APT29")
+actor_graph.add_node("SUNBURST", "Malware", "SUNBURST backdoor")
+actor_graph.add_edge("APT29", "SUNBURST", "uses")
+
+victim_graph.add_node("SolarWinds", "Victim", "SolarWinds Corporation")
+victim_graph.add_node("Treasury", "Victim", "US Department of Treasury")
+victim_graph.add_edge("SolarWinds", "Treasury", "supply_chain_compromised")
+
+link_id = actor_graph.link_graph(
+ victim_graph,
+ "APT29",
+ "SolarWinds",
+ link_type="targets",
+)
+
+other_graph, target_node_id = actor_graph.navigate_to(link_id)
+
+sw = other_graph.find_node(target_node_id)
+if sw:
+ print("Reached:", sw["id"])
+
+result = actor_graph.cross_graph_path(
+ "APT29",
+ victim_graph,
+ "Treasury",
+)
+
+if result.get("reachable"):
+ print(f"Reached in {result['hop_count']} hops")
+# APT29 → SUNBURST → SolarWinds → Treasury
+```
+
+## Serialization and Persistence
+
+After each ingest cycle, save the graph to disk. On restart, restore it — the entire node and edge set is preserved:
+
+```python
+# Save
+graph.save_to_file("cti_graph.json")
+
+# Restore
+restored = ContextGraph(advanced_analytics=True)
+restored.load_from_file("cti_graph.json")
+
+print(restored.stats())
+
+# to_dict() gives you the raw serializable dict
+d = graph.to_dict()
+# d["nodes"] → list of node dicts
+# d["edges"] → list of edge dicts
+# d["statistics"] → {"node_count": int, "edge_count": int}
+```
+
+For full session persistence (graph + FAISS vector index + memory), use `AgentContext.save()` / `AgentContext.load()`:
+
+```python
+context.save("agent_state/")
+
+# Later, on restart:
+context2 = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = ContextGraph(),
+)
+context2.load("agent_state/")
+```
+
+## Domain Examples
+
+<Tabs>
+ <Tab title="Defense — CTI/Threat">
+ Three separate ingest workers write to a shared `ContextGraph` simultaneously (MISP, NVD, classified STIX). Temporal validity prevents stale campaign data from appearing in current-threat queries.
+
+```python
+from semantica.context import ContextGraph, AgentContext
+from semantica.vector_store import VectorStore
+from datetime import datetime
+
+graph = ContextGraph(advanced_analytics=True, community_detection=True)
+
+# Core CTI entities
+graph.add_node("APT29", "ThreatActor", "Russian GRU unit, COZY BEAR",
+ origin="Russia", motivation="espionage")
+graph.add_node("SUNBURST", "Malware", "SolarWinds supply chain backdoor",
+ family="backdoor", platforms=["Windows"])
+graph.add_node("CVE-2020-10148", "Vulnerability",
+ "SolarWinds Orion API auth bypass", cvss=10.0)
+
+# Time-bound C2 infrastructure
+graph.add_node("avsvmcloud.com", "C2Domain",
+ "SUNBURST DNS C2 domain",
+ valid_from="2019-10-01T00:00:00",
+ valid_until="2020-12-18T00:00:00")
+
+graph.add_edge("APT29", "SUNBURST", "deploys", weight=1.0)
+graph.add_edge("SUNBURST", "CVE-2020-10148", "exploits", weight=0.95)
+graph.add_edge("SUNBURST", "avsvmcloud.com", "beacons_to", weight=0.9,
+ valid_from="2019-10-01T00:00:00",
+ valid_until="2020-12-18T00:00:00")
+
+# What C2 infrastructure is active right NOW?
+active_c2 = graph.find_active_nodes(node_type="C2Domain")
+print(f"Currently active C2 domains: {len(active_c2)}")
+# Currently active C2 domains: 0 — avsvmcloud.com expired in 2020
+
+# Historical query: what was active during the campaign?
+campaign_c2 = graph.find_active_nodes(
+ node_type="C2Domain",
+ at_time=datetime(2020, 6, 1),
+)
+print(f"C2 domains active June 2020: {len(campaign_c2)}")
+# C2 domains active June 2020: 1 — avsvmcloud.com was active
+
+# Traversal: full blast radius from APT29
+blast_radius = graph.get_neighbors("APT29", hops=3,
+ include_distance_metadata=True)
+for n in blast_radius:
+ print(f" hop={n['hop']} decay={n['confidence_decay']:.2f} {n['id']}")
+```
+
+ </Tab>
+
+ <Tab title="Security — SOC/Incident">
+ During an active incident, hosts are nodes and observed lateral connections are edges. The graph answers which hosts are on the critical path and what the attacker's reachable network looks like from the initial foothold.
+
+```python
+from semantica.context import ContextGraph
+
+graph = ContextGraph(advanced_analytics=True)
+
+# Affected hosts
+for host in ["ws-finance-04", "srv-dc-01", "srv-file-02",
+ "ws-hr-11", "srv-backup-01"]:
+ graph.add_node(host, "Host", f"Windows host: {host}")
+
+# Implants observed
+graph.add_node("COBALT-STRIKE-BEACON-01", "Implant",
+ "Cobalt Strike beacon, staged from ws-finance-04")
+graph.add_node("MIMIKATZ-DUMP-01", "Tool",
+ "Credential dump observed on srv-dc-01")
+
+# Lateral movement edges
+graph.add_edge("ws-finance-04", "srv-dc-01", "lateral_move", weight=0.9)
+graph.add_edge("srv-dc-01", "srv-file-02", "lateral_move", weight=0.85)
+graph.add_edge("srv-dc-01", "srv-backup-01", "lateral_move", weight=0.8)
+graph.add_edge("ws-finance-04", "COBALT-STRIKE-BEACON-01", "hosts", weight=1.0)
+graph.add_edge("srv-dc-01", "MIMIKATZ-DUMP-01", "executes", weight=1.0)
+
+# Blast radius from initial foothold
+reachable = graph.get_neighbors("ws-finance-04", hops=3,
+ relationship_types=["lateral_move"])
+print("Reachable via lateral movement:")
+for n in reachable:
+ print(f" hop={n['hop']} {n['id']}")
+
+# Critical path to the backup server
+path = graph.shortest_path("ws-finance-04", "srv-backup-01")
+print(" → ".join(path))
+# ws-finance-04 → srv-dc-01 → srv-backup-01
+
+# Isolate incident subgraph for reporting
+incident_nodes = [n["id"] for n in reachable] + ["ws-finance-04"]
+subgraph = graph.extract_subgraph(incident_nodes)
+print(f"Incident scope: {subgraph.stats()['node_count']} hosts")
+```
+
+ </Tab>
+
+ <Tab title="Life Science — Clinical/Pharma">
+ A clinical trial knowledge graph tracks drugs, biomarkers, patient populations, adverse events, and regulatory milestones. Each regulatory milestone has a validity window — queries must respect those windows to prevent stale efficacy data from being cited alongside current safety findings.
+
+```python
+from semantica.context import ContextGraph
+from datetime import datetime
+
+graph = ContextGraph(advanced_analytics=True)
+
+# Entities
+graph.add_node("dapagliflozin", "Drug", "SGLT2 inhibitor, AstraZeneca")
+graph.add_node("HbA1c-reduction", "Biomarker", "Primary endpoint: HbA1c change from baseline")
+graph.add_node("T2D-adults-65plus", "Population", "Type 2 diabetes, adults 65+, DECLARE-TIMI 58")
+graph.add_node("DKA", "AdverseEvent","Diabetic ketoacidosis, known SGLT2 risk")
+
+# Phase III data node — valid once submission accepted
+graph.add_node("DECLARE-TIMI58-results", "ClinicalData",
+ "Phase III CVOT results: dapagliflozin vs placebo",
+ phase="III",
+ primary_endpoint_met=True,
+ valid_from="2019-01-11T00:00:00") # NEJM publication date
+
+graph.add_edge("dapagliflozin", "HbA1c-reduction", "primary_endpoint", weight=1.0)
+graph.add_edge("dapagliflozin", "T2D-adults-65plus", "studied_in", weight=1.0)
+graph.add_edge("dapagliflozin", "DKA", "risk_of", weight=0.7)
+graph.add_edge("DECLARE-TIMI58-results", "dapagliflozin", "evaluates", weight=1.0)
+
+# Only retrieve trial data available as of a given regulatory review date
+active_data = graph.find_active_nodes(
+ node_type="ClinicalData",
+ at_time=datetime(2019, 6, 1),
+)
+print(f"Published trial data available June 2019: {len(active_data)}")
+# Published trial data available June 2019: 1
+
+# Traverse: what is known about dapagliflozin within 2 hops?
+drug_neighbors = graph.get_neighbors("dapagliflozin", hops=2)
+for n in drug_neighbors:
+ print(f" [{n['relationship']}] {n['id']} ({n['type']})")
+```
+
+ </Tab>
+
+ <Tab title="Banking — Risk/Compliance">
+ A counterparty risk graph connects banks, SPVs, exposure instruments, guarantors, and regulatory entities. Entities have reporting-period validity — a counterparty's CDS exposure node is valid only for the quarter it was reported.
+
+```python
+from semantica.context import ContextGraph
+from datetime import datetime
+
+graph = ContextGraph(advanced_analytics=True, community_detection=True)
+
+# Entities
+graph.add_node("BankA", "Counterparty", "Tier-1 bank, EUR exposure 4.2B")
+graph.add_node("SPV-EUR-01", "SPV", "Structured vehicle, BankA sponsored")
+graph.add_node("BankB", "Counterparty", "Tier-2 bank, USD exposure 0.8B")
+graph.add_node("CCP-LME", "CCP", "Central counterparty — LME metals")
+
+# Q4 2024 exposure node — valid for the reporting quarter only
+graph.add_node("BankA-BankB-CDS-Q42024", "Exposure",
+ "CDS notional 400M, BankA writes protection on BankB",
+ notional_eur=400_000_000,
+ valid_from="2024-10-01T00:00:00",
+ valid_until="2024-12-31T23:59:59")
+
+graph.add_edge("BankA", "SPV-EUR-01", "sponsors", weight=1.0)
+graph.add_edge("BankA", "BankB", "exposed_to", weight=0.8)
+graph.add_edge("BankA", "BankA-BankB-CDS-Q42024", "holds", weight=1.0)
+graph.add_edge("SPV-EUR-01", "CCP-LME", "clears_via", weight=0.9)
+graph.add_edge("BankB", "CCP-LME", "member_of", weight=1.0)
+
+# Contagion path: if BankA defaults, who is downstream?
+downstream = graph.get_neighbors("BankA", hops=3, include_distance_metadata=True)
+print("Contagion reach from BankA:")
+for n in downstream:
+ print(f" hop={n['hop']} decay={n['confidence_decay']:.2f} {n['id']}")
+
+# Q4 exposure picture — only include nodes valid in Q4 2024
+q4_exposures = graph.find_active_nodes(
+ node_type="Exposure",
+ at_time=datetime(2024, 11, 15),
+)
+print(f"\nActive Q4 2024 exposures: {len(q4_exposures)}")
+
+# Extract stress-test subgraph
+stress_nodes = ["BankA", "SPV-EUR-01", "BankB", "CCP-LME"]
+subgraph = graph.extract_subgraph(stress_nodes)
+print(f"Stress-test scope: {subgraph.stats()['node_count']} entities, "
+ f"{subgraph.stats()['edge_count']} exposures")
+```
+
+ </Tab>
+</Tabs>
+
+## Related Guides
+
+- [Graph Analytics](graph-analytics) — centrality rankings, community detection, node embeddings, and link prediction on a populated `ContextGraph`
+- [Decision Intelligence](decision-intelligence) — recording decisions as typed nodes, causal chain analysis, precedent search, and policy enforcement
+- [Ingest](ingest) — loading data from PDFs, APIs, databases, STIX bundles, and RSS feeds into the graph
+- [Deduplication](deduplication) — detecting and merging near-duplicate nodes before insertion to prevent graph fragmentation
+- [Reasoning](reasoning) — temporal interval algebra (Allen relations), forward/backward chaining, and SPARQL over the knowledge graph
+- [Ontology Management](ontology) — deriving formal OWL ontologies from `graph.to_dict()` for downstream reasoning engines
+- [Context Module Reference](../reference/context) — full API for `AgentContext`, `ContextGraph`, `ContextNode`, `ContextEdge`
diff --git a/docs/guides/decision-intelligence.md b/docs/guides/decision-intelligence.md
new file mode 100644
index 00000000..f52f1903
--- /dev/null
+++ b/docs/guides/decision-intelligence.md
@@ -0,0 +1,578 @@
+---
+title: "Decision Intelligence"
+description: "How Semantica records, stores, traces, and queries AI agent decisions as first-class knowledge graph objects — with causal chains, precedent search, policy enforcement, and full explainability."
+icon: "scale-balanced"
+---
+
+`AgentContext.record_decision()` stores every AI decision as a node in the knowledge graph, linked by causal edges to the decisions that preceded it and the outcomes that followed. Use it to build an auditable reasoning trail — one that lets you reconstruct, six months later, exactly which classification caused which escalation, and which policy was checked before it was recorded.
+
+<Info>
+ Decision tracking requires both a `VectorStore` (for embedding-based precedent search) and a `ContextGraph` (for causal graph storage). Set `decision_tracking=True` on `AgentContext` — omitting either component raises `RuntimeError` at call time.
+</Info>
+
+## Recording the First Decision
+
+The most common entry point is `AgentContext.record_decision()`. It writes a `Decision` node into the graph, generates embeddings for hybrid similarity search, and returns a UUID you use to link subsequent decisions causally.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ decision_tracking=True,
+)
+
+# The system has just classified a new threat cluster.
+# Record the classification decision before taking any action.
+classification_id = context.record_decision(
+ category = "threat_classification",
+ scenario = "Unattributed C2 cluster using HAMMERTOSS-like Twitter dead-drop pattern",
+ reasoning = "Infrastructure overlaps known APT29 hosting ASN; TTP T1102 matches NOBELIUM playbook with 0.88 cosine similarity",
+ outcome = "classified_as_apt29_cluster",
+ confidence = 0.88,
+ decision_maker = "cti_pipeline_v2",
+ entities = ["apt29", "hammertoss", "twitter_c2"],
+)
+
+print("Decision recorded:", classification_id)
+# → "Decision recorded: dec_a3f2b1c4-..."
+```
+
+The `Decision` dataclass that backs this node has the following fields — these are what get stored and searched:
+
+```python
+from semantica.context import Decision
+from datetime import datetime
+
+# Constructing a Decision explicitly (alternative to record_decision)
+d = Decision(
+ decision_id = "dec_001", # UUID — auto-generated if omitted via record_decision
+ category = "threat_classification",
+ scenario = "Unattributed C2 cluster",
+ reasoning = "Infrastructure overlaps APT29 ASN",
+ outcome = "classified_as_apt29_cluster",
+ confidence = 0.88, # float 0.0–1.0
+ timestamp = datetime.now(),
+ decision_maker = "cti_pipeline_v2",
+ # optional fields:
+ valid_from = "2025-07-01T00:00:00", # ISO datetime
+ valid_until = "2025-09-30T23:59:59", # ISO datetime
+ metadata = {"source_feed": "isac_partner_b"},
+)
+graph.add_decision(d)
+```
+
+## Searching Precedents Before Deciding
+
+Before making a significant call, the system should search past decisions for similar scenarios. This is how you prevent the same cluster being classified differently across two agent runs — the second agent finds the first agent's decision and uses it as a prior.
+
+```python
+# Search before classifying a new unattributed cluster
+precedents = context.find_precedents(
+ "unattributed C2 cluster Twitter dead-drop infrastructure",
+ limit=5,
+)
+
+for p in precedents:
+ print("[{:.2f} confidence] {} → {}".format(p.confidence, p.category, p.outcome))
+ print(" Reasoning: {}".format(p.reasoning[:80]))
+ print(" Similarity: {:.3f}".format(p.metadata.get("similarity_score", 0)))
+```
+
+Hybrid search blends two signals: semantic similarity over the `scenario` and `reasoning` text (weight 0.7), and structural graph proximity via Node2Vec embeddings (weight 0.3). The result is a ranked list of `Decision` objects — the most similar past decisions float to the top regardless of how differently they were phrased.
+
+## Building a Causal Chain
+
+Decisions rarely exist in isolation. A classification decision causes an escalation decision, which causes a containment decision. Linking them with causal edges lets you traverse the chain in either direction — upstream to understand what caused an outcome, downstream to see what an early decision triggered.
+
+```python
+# The classification above caused an escalation
+escalation_id = context.record_decision(
+ category = "escalation",
+ scenario = "APT29 cluster confirmed — active C2 beaconing to NATO contractor subnet",
+ reasoning = "Classification confidence 0.88 exceeds 0.80 escalation threshold; active C2 requires immediate SOC notification",
+ outcome = "escalated_to_soc_tier2",
+ confidence = 0.95,
+ decision_maker = "escalation_engine",
+)
+
+# Link the two decisions: classification caused the escalation
+graph.add_causal_relationship(classification_id, escalation_id, "CAUSED")
+
+# The escalation influenced a patch prioritization decision
+patch_id = context.record_decision(
+ category = "patch_priority",
+ scenario = "CVE-2024-3400 present in two NATO contractor VPN appliances",
+ reasoning = "Active exploitation by classified APT29 cluster elevates CVE-2024-3400 to P0 regardless of base CVSS",
+ outcome = "prioritized_cve_2024_3400_p0",
+ confidence = 0.97,
+ decision_maker = "patch_engine",
+)
+
+graph.add_causal_relationship(escalation_id, patch_id, "INFLUENCED")
+```
+
+Now trace the chain from the patch decision back to its root cause:
+
+```python
+upstream = context.get_causal_chain(
+ patch_id,
+ direction = "upstream",
+ max_depth = 5,
+)
+
+print("Causal chain upstream from patch prioritization:")
+for d in upstream:
+ depth = d.metadata.get("causal_distance", "?")
+ print(" [depth {}] {} → {} (confidence={:.2f})".format(
+ depth, d.category, d.outcome, d.confidence
+ ))
+# [depth 1] escalation → escalated_to_soc_tier2 (confidence=0.95)
+# [depth 2] threat_classification → classified_as_apt29_cluster (confidence=0.88)
+```
+
+And trace downstream from the original classification to see everything it triggered:
+
+```python
+downstream = context.get_causal_chain(
+ classification_id,
+ direction = "downstream",
+ max_depth = 5,
+)
+print("Downstream decisions triggered:", len(downstream))
+for d in downstream:
+ print(" → {} [{}]".format(d.outcome, d.category))
+```
+
+## Generating an Explainability Report
+
+`trace_decision_explainability` gives you the full picture in one call: upstream causes, downstream effects, and total connection count. This is what you attach to a post-mortem or audit report.
+
+```python
+explanation = context.trace_decision_explainability(patch_id)
+
+print("Decision:", patch_id)
+print("Total graph connections :", explanation["total_connections"])
+print("Upstream causes :", len(explanation.get("upstream_decisions", [])))
+print("Downstream effects :", len(explanation.get("downstream_decisions", [])))
+```
+
+For deeper causal analysis with confidence decay and distance bands, use `trace_decision_causality` on the graph directly:
+
+```python
+chains = graph.trace_decision_causality(patch_id, max_depth=5)
+
+for chain in chains:
+ print("Chain: {} hops | band={} | decay={:.3f}".format(
+ chain["hop_count"], chain["distance_band"], chain["confidence_decay"]
+ ))
+ print(" Interpretation:", chain["interpretation"])
+ # e.g. "Decision chain spans 2 hops in the 'near' band with 84% confidence
+ # — causal attribution is reliable."
+```
+
+## Gating Decisions Against Policy
+
+Before recording a high-stakes decision, check it against a versioned policy. The `PolicyEngine` stores `Policy` nodes in the graph and gates `Decision` objects against their rules.
+
+```python
+from semantica.context import PolicyEngine, Policy, Decision
+from datetime import datetime
+
+engine = PolicyEngine(graph_store=graph)
+
+engine.add_policy(Policy(
+ policy_id = "cti_confidence_gate",
+ name = "CTI Minimum Confidence Policy",
+ description = "All threat classifications must have confidence >= 0.80",
+ rules = {"min_confidence": 0.80, "requires_reasoning": True},
+ category = "threat_classification",
+ version = "1.0",
+ created_at = datetime.now(),
+ updated_at = datetime.now(),
+))
+
+d = Decision(
+ decision_id = "dec_low_conf",
+ category = "threat_classification",
+ scenario = "Possible APT29 activity — weak signals only",
+ reasoning = "Single IP overlap, no TTP match",
+ outcome = "classified_as_apt29_tentative",
+ confidence = 0.62, # below the 0.80 threshold
+ timestamp = datetime.now(),
+ decision_maker = "cti_pipeline_v2",
+)
+
+if engine.check_compliance(d, "cti_confidence_gate"):
+ graph.add_decision(d)
+ engine.record_policy_application(d.decision_id, "cti_confidence_gate", "1.0")
+ print("Decision recorded — policy compliant.")
+else:
+ print("Decision blocked — confidence 0.62 below policy minimum 0.80.")
+ # → "Decision blocked — confidence 0.62 below policy minimum 0.80."
+```
+
+When a high-urgency situation requires bypassing the policy gate, record the exception with the approver identity and justification:
+
+```python
+from semantica.context import DecisionRecorder
+
+recorder = DecisionRecorder(graph_store=graph)
+
+exception_id = recorder.record_exception(
+ decision_id = "dec_low_conf",
+ policy_id = "cti_confidence_gate",
+ reason = "Active exploitation in progress — cannot wait for higher-confidence attribution",
+ approver = "ciso_director",
+ approval_method = "slack_dm",
+ justification = "Time-critical incident response; manual CISO sign-off obtained at 03:14 UTC",
+)
+print("Policy exception recorded:", exception_id)
+```
+
+For multi-level approval workflows, use `DecisionRecorder.record_approval_chain()` with a graph database backend (for example Neo4j/FalkorDB). The in-memory `ContextGraph` examples used in this guide do not support approval-chain persistence via `execute_query()`.
+
+
+
+## Generating a Decision Audit Report
+
+At the end of a shift or incident, `get_decision_insights` produces a statistical summary of every decision in the graph — useful for shift handover notes and compliance reporting.
+
+```python
+insights = graph.get_decision_insights()
+
+print("Total decisions today :", insights["total_decisions"])
+print("Confidence — mean={:.2f} min={:.2f} max={:.2f}".format(
+ insights["confidence_stats"]["mean"],
+ insights["confidence_stats"]["min"],
+ insights["confidence_stats"]["max"],
+))
+print("\nDecisions by category:")
+for cat, count in sorted(insights["categories"].items(), key=lambda x: -x[1]):
+ print(" {:35s} {}".format(cat, count))
+print("\nOutcomes:")
+for outcome, count in sorted(insights["outcomes"].items(), key=lambda x: -x[1]):
+ print(" {:35s} {}".format(outcome, count))
+```
+
+Sample output:
+
+```text
+Total decisions today : 47
+Confidence — mean=0.87 min=0.62 max=0.99
+
+Decisions by category:
+ threat_classification 18
+ patch_priority 12
+ escalation 9
+ containment 8
+
+Outcomes:
+ classified_as_apt29_cluster 11
+ prioritized_p0_patch 12
+ escalated_to_soc_tier2 9
+ isolated_host 8
+```
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+A CTI pipeline classifies threat clusters, records each classification with confidence and reasoning, links classification decisions to escalation decisions causally, and generates a daily audit report for the threat intelligence lead.
+
+```python
+from semantica.context import AgentContext, ContextGraph, PolicyEngine, Policy
+from semantica.vector_store import VectorStore
+from datetime import datetime
+
+graph = ContextGraph(advanced_analytics=True)
+engine = PolicyEngine(graph_store=graph)
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ decision_tracking=True,
+)
+
+engine.add_policy(Policy(
+ policy_id = "cti_gate",
+ name = "CTI Attribution Confidence Gate",
+ description = "Attributions require confidence >= 0.80",
+ rules = {"min_confidence": 0.80},
+ category = "threat_classification",
+ version = "1.0",
+ created_at = datetime.now(),
+ updated_at = datetime.now(),
+))
+
+# Check precedents before classifying
+precedents = context.find_precedents(
+ "Twitter dead-drop C2 pattern overlapping APT29 infrastructure",
+ limit=3,
+)
+for p in precedents:
+ print("Prior: {} → {} ({:.0%})".format(p.scenario[:40], p.outcome, p.confidence))
+
+# Record the classification
+class_id = context.record_decision(
+ category = "threat_classification",
+ scenario = "New C2 cluster: Twitter dead-drop, AS200651 hosting, TTP T1102",
+ reasoning = "IP block overlaps APT29 cluster; T1102 matches HAMMERTOSS playbook",
+ outcome = "classified_apt29_march_cluster",
+ confidence = 0.88,
+ decision_maker = "cti_pipeline_v2",
+ entities = ["apt29", "hammertoss"],
+)
+
+# Link to downstream escalation
+esc_id = context.record_decision(
+ category = "escalation",
+ scenario = "APT29 cluster active — beaconing to NATO subnet 10.30.0.0/16",
+ reasoning = "Active C2 with high-confidence attribution requires immediate SOC notification",
+ outcome = "escalated_tier2_soc",
+ confidence = 0.97,
+ decision_maker = "escalation_engine",
+)
+graph.add_causal_relationship(class_id, esc_id, "CAUSED")
+
+# Post-shift audit report
+insights = graph.get_decision_insights()
+print("Decisions recorded:", insights["total_decisions"])
+print("Mean confidence :", round(insights["confidence_stats"]["mean"], 2))
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+During an incident, the SOC records containment decisions with causal links to the detection decisions that triggered them. Six hours later the post-mortem can replay the exact decision sequence from first alert to final containment.
+
+```python
+from semantica.context import AgentContext, ContextGraph, DecisionRecorder
+from semantica.vector_store import VectorStore
+
+graph = ContextGraph()
+recorder = DecisionRecorder(graph_store=graph)
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ decision_tracking=True,
+)
+
+# T+0: Detection decision
+detect_id = context.record_decision(
+ category = "detection",
+ scenario = "WKSTN-047: wmiprvse.exe spawned scheduled task — T1053.005",
+ reasoning = "Scheduled task creation by WMI provider host is high-fidelity lateral movement indicator",
+ outcome = "flagged_wkstn047_suspicious",
+ confidence = 0.93,
+ decision_maker = "edr_engine",
+)
+
+# T+8min: Containment decision caused by detection
+contain_id = context.record_decision(
+ category = "containment",
+ scenario = "WKSTN-047 confirmed compromised — lateral movement to DC01 via SMB",
+ reasoning = "PsExec artefact on DC01; isolate before domain-wide credential compromise",
+ outcome = "isolated_wkstn047",
+ confidence = 0.95,
+ decision_maker = "analyst_chen",
+)
+graph.add_causal_relationship(detect_id, contain_id, "CAUSED")
+
+# Post-mortem: trace the full chain
+chain = context.get_causal_chain(contain_id, direction="upstream", max_depth=5)
+print("Post-mortem — causal chain for isolation decision:")
+for d in chain:
+ print(" [depth {}] {} → {} (confidence={:.2f}, maker={})".format(
+ d.metadata.get("causal_distance", "?"),
+ d.category, d.outcome, d.confidence, d.decision_maker,
+ ))
+
+# Full explainability for the containment decision
+explanation = context.trace_decision_explainability(contain_id)
+print("Upstream causes :", len(explanation.get("upstream_decisions", [])))
+print("Total connections :", explanation["total_connections"])
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+A clinical AI assistant records treatment modification decisions with guideline precedents, links them causally to the diagnostic decisions that preceded them, and generates a structured decision record for MDT review and regulatory audit.
+
+```python
+from semantica.context import AgentContext, ContextGraph, PolicyEngine, Policy
+from semantica.context import Decision, DecisionRecorder
+from semantica.vector_store import VectorStore
+from datetime import datetime
+
+graph = ContextGraph()
+engine = PolicyEngine(graph_store=graph)
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ decision_tracking=True,
+)
+
+engine.add_policy(Policy(
+ policy_id = "clinical_confidence_gate",
+ name = "Clinical Decision Confidence Gate",
+ description = "Treatment decisions require confidence >= 0.90",
+ rules = {"min_confidence": 0.90},
+ category = "treatment_modification",
+ version = "1.0",
+ created_at = datetime.now(),
+ updated_at = datetime.now(),
+))
+
+# Diagnostic decision precedes treatment decision
+diag_id = context.record_decision(
+ category = "diagnosis_assessment",
+ scenario = "Patient eGFR 28 mL/min/1.73m2, CKD Stage 4, current metformin 1000mg BD",
+ reasoning = "eGFR 28 confirms CKD Stage 4; below 30 threshold for metformin contraindication",
+ outcome = "confirmed_ckd_stage4_metformin_contraindicated",
+ confidence = 0.99,
+ decision_maker = "clinical_ai_v3",
+)
+
+# Treatment modification caused by diagnostic assessment
+treat_id = context.record_decision(
+ category = "treatment_modification",
+ scenario = "Metformin discontinuation required — eGFR 28 below contraindication threshold",
+ reasoning = "NICE NG28 and BNF both contraindicate metformin at eGFR < 30; switch to gliclazide MR 30mg OD",
+ outcome = "discontinue_metformin_initiate_gliclazide",
+ confidence = 0.97,
+ decision_maker = "clinical_ai_v3",
+)
+graph.add_causal_relationship(diag_id, treat_id, "CAUSED")
+
+# MDT audit report
+chain = context.get_causal_chain(treat_id, direction="upstream", max_depth=3)
+print("MDT Decision Audit — Treatment Modification")
+print("=" * 50)
+for d in chain:
+ print("Caused by: [{}] {} (confidence={:.0%})".format(
+ d.category, d.outcome, d.confidence
+ ))
+
+insights = graph.get_decision_insights()
+cs = insights["confidence_stats"]
+print("\nSession decisions: {} | mean confidence: {:.2f}".format(
+ insights["total_decisions"], cs["mean"]
+))
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+A credit decisioning system records every loan decision against a versioned lending policy, links borderline approvals to stress-test decisions causally, and exports a complete decision audit trail for SR 11-7 model governance review.
+
+```python
+from semantica.context import AgentContext, ContextGraph, PolicyEngine, Policy
+from semantica.context import Decision, DecisionRecorder
+from semantica.vector_store import VectorStore
+from datetime import datetime
+
+graph = ContextGraph()
+engine = PolicyEngine(graph_store=graph)
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ decision_tracking=True,
+)
+
+engine.add_policy(Policy(
+ policy_id = "lending_policy_v3",
+ name = "Lending Compliance Policy v3",
+ description = "Credit decisions require confidence >= 0.85 and documented reasoning",
+ rules = {"min_confidence": 0.85, "requires_reasoning": True},
+ category = "loan_approval",
+ version = "3.0",
+ created_at = datetime.now(),
+ updated_at = datetime.now(),
+))
+
+# Check precedents before approving
+precedents = context.find_precedents(
+ "first-time buyer mortgage borderline DSTI stressed rate scenario",
+ limit=3,
+)
+for p in precedents:
+ print("Prior: {} → {} ({:.0%})".format(p.scenario[:40], p.outcome, p.confidence))
+
+# Stress-test decision precedes approval decision
+stress_id = context.record_decision(
+ category = "stress_test",
+ scenario = "APP-2025-994421: LTV 78%, DSTI 38% at current rate; DSTI rises to 44% at +300bps",
+ reasoning = "DSTI 44% under stress exceeds 35% guideline threshold — requires LMI and income verification",
+ outcome = "stress_test_conditional_pass",
+ confidence = 0.88,
+ decision_maker = "risk_model_v3",
+)
+
+# Approval decision influenced by stress test
+d = Decision(
+ decision_id = "loan_dec_994421",
+ category = "loan_approval",
+ scenario = "APP-2025-994421: first-time buyer, LTV 78%, credit score 714, 30yr fixed",
+ reasoning = "Credit score 714 exceeds 700 minimum; LTV within 80% cap; conditional on LMI given stress-test DSTI",
+ outcome = "approved_conditional_lmi_required",
+ confidence = 0.89,
+ timestamp = datetime.now(),
+ decision_maker = "credit_model_v3",
+)
+
+if engine.check_compliance(d, "lending_policy_v3"):
+ loan_id = context.record_decision(
+ category=d.category, scenario=d.scenario,
+ reasoning=d.reasoning, outcome=d.outcome, confidence=d.confidence,
+ decision_maker=d.decision_maker,
+ )
+ graph.add_causal_relationship(stress_id, loan_id, "INFLUENCED")
+ engine.record_policy_application(d.decision_id, "lending_policy_v3", "3.0")
+ print("Loan decision recorded — policy compliant.")
+
+ # SR 11-7 explainability report
+ explanation = context.trace_decision_explainability(loan_id)
+ print("Upstream influences:", len(explanation.get("upstream_decisions", [])))
+ print("Total connections :", explanation["total_connections"])
+```
+
+</Tab>
+
+</Tabs>
+
+## Persisting Decisions Across Restarts
+
+When using the local `ContextGraph`, save at the end of every session and load at the start of the next. All decision nodes, causal edges, and FAISS embeddings are restored.
+
+```python
+# End of session
+context.save("agent_state/")
+# Writes: agent_state/knowledge_graph.json + FAISS index
+
+# Start of next session
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768, index_path="decisions.faiss"),
+ knowledge_graph=ContextGraph(),
+ decision_tracking=True,
+)
+context.load("agent_state/")
+
+# All past decisions are searchable immediately
+results = context.find_precedents("APT29 infrastructure attribution", limit=5)
+```
+
+## Related Guides
+
+- [Context Graphs](context-graphs) — how `ContextGraph` stores decision nodes and causal edges
+- [Distance Intelligence](distance-intelligence) — `trace_decision_causality()` annotates causal chains with confidence decay and distance bands
+- [Provenance](provenance) — W3C PROV-O audit trail that wraps decision records in standards-compliant provenance
+- [MCP Server](mcp-server) — expose decision recording and precedent search to LLM agents via the `record_decision` and `find_precedents` tools
+- [Change Management](change-management) — checkpoint decision state with `flush_checkpoint()` for versioned snapshots
diff --git a/docs/guides/deduplication.md b/docs/guides/deduplication.md
new file mode 100644
index 00000000..544a9ada
--- /dev/null
+++ b/docs/guides/deduplication.md
@@ -0,0 +1,453 @@
+---
+title: "Deduplication & Entity Merging"
+description: "Detect duplicate entities using multi-factor similarity, merge them with configurable strategies, and keep your knowledge graph clean at scale."
+---
+
+The deduplication module detects duplicate entities across multi-source knowledge graphs using six complementary similarity algorithms — exact match, Levenshtein, Jaro-Winkler, cosine, property comparison, and vector embedding — then merges them into a single canonical entity while preserving full provenance. Use it to collapse alias clusters (e.g. "APT29", "Cozy Bear", "Midnight Blizzard") before running graph analytics or conflict resolution.
+
+<Info>
+Run deduplication after ingestion and before conflict resolution. Deduplication collapses duplicate nodes into one canonical entity. Conflict resolution then reconciles disagreeing property values on that canonical entity. The pipeline order matters: deduplicate first, then resolve conflicts, then validate with SHACL.
+</Info>
+
+## Finding your duplicates: the first scan
+
+Start with `detect_duplicates()`. Point it at your threat actor entities and let the pairwise algorithm compare every pair. For a dataset of a few thousand nodes this runs in seconds — the O(n²) cost only matters above ten thousand entities.
+
+```python
+from semantica.deduplication import detect_duplicates
+
+# Threat actors ingested from four different CTI feeds — same actors, different names
+threat_actors = [
+ {"id": "ta-nvd-001", "name": "APT29", "type": "ThreatActor",
+ "country": "Russia", "source": "MISP"},
+ {"id": "ta-of-002", "name": "APT-29", "type": "ThreatActor",
+ "country": "Russia", "source": "OpenCTI"},
+ {"id": "ta-rf-003", "name": "Cozy Bear", "type": "ThreatActor",
+ "aliases": ["APT29"], "country": "Russia", "source": "RecordedFuture"},
+ {"id": "ta-sx-004", "name": "The Dukes", "type": "ThreatActor",
+ "aliases": ["APT29", "Cozy Bear"], "country": "Russia", "source": "STIX-partner"},
+ {"id": "ta-ms-005", "name": "Midnight Blizzard", "type": "ThreatActor",
+ "aliases": ["NOBELIUM", "APT29"], "country": "Russia", "source": "Microsoft"},
+ {"id": "ta-ap-006", "name": "APT28", "type": "ThreatActor",
+ "country": "Russia", "source": "MISP"}, # different actor — should NOT match
+]
+
+candidates = detect_duplicates(
+ threat_actors,
+ method="pairwise", # compare every pair
+ similarity_threshold=0.6, # minimum score to flag as a candidate
+ confidence_threshold=0.5, # minimum confidence in the match
+)
+
+for c in candidates:
+ print(f"{c.entity1['name']!r} ~ {c.entity2['name']!r}")
+ print(f" similarity={c.similarity_score:.2f} confidence={c.confidence:.2f}")
+ print(f" signals: {c.reasons}")
+ print()
+```
+
+```text
+'APT29' ~ 'APT-29'
+ similarity=0.89 confidence=0.81
+ signals: ['levenshtein', 'jaro_winkler']
+
+'APT29' ~ 'Cozy Bear'
+ similarity=0.63 confidence=0.71
+ signals: ['property', 'relationship'] # alias field matched
+
+'Cozy Bear' ~ 'The Dukes'
+ similarity=0.61 confidence=0.68
+ signals: ['property'] # shared alias "APT29"
+
+'APT29' ~ 'Midnight Blizzard'
+ similarity=0.65 confidence=0.73
+ signals: ['property'] # alias "APT29" in Midnight Blizzard record
+```
+
+The scores tell a clear story. "APT29" and "APT-29" score 0.89 — the hyphen is the only difference, pure edit-distance signal. "Cozy Bear" and "The Dukes" score lower (0.61) because the names are completely dissimilar, but the property signal fires because both records carry `"APT29"` in their aliases list. "APT28" never appears in the results because it shares only the country field — not enough to cross the 0.6 threshold.
+
+## Understanding the candidate object
+
+Each `DuplicateCandidate` carries the two entities, their scores, and a `reasons` list explaining which signals fired. This is your audit trail for the detection decision:
+
+```python
+from semantica.deduplication import calculate_similarity
+
+# Inspect a single pair in detail before committing to a merge
+e1 = threat_actors[0] # APT29
+e2 = threat_actors[2] # Cozy Bear
+
+result = calculate_similarity(e1, e2, method="multi_factor")
+
+print(f"Overall score : {result.score:.2f}")
+print(f"Method : {result.method}")
+print(f"Components :")
+for algo, score in result.components.items():
+ print(f" {algo:<20} {score:.2f}")
+```
+
+```text
+Overall score : 0.63
+Method : multi_factor
+Components :
+ exact 0.00 # names are completely different strings
+ levenshtein 0.12 # high edit distance between "APT29" and "Cozy Bear"
+ jaro_winkler 0.21 # no shared prefix
+ property 0.94 # alias match is nearly definitive
+ relationship 0.71 # share relationships to overlapping malware families
+ embedding 0.78 # semantic vectors land in the same cluster
+```
+
+The property component (0.94) is doing most of the work here. "Cozy Bear"'s record carries `aliases: ["APT29"]`, which creates an almost-definitive signal. When you see a pattern like this — a weak name score but a strong property score — you're looking at a real alias relationship, not a false positive.
+
+## Grouping duplicates before merging
+
+For a small dataset you can merge pairs directly. For a larger graph where the same entity might appear under six different names across twelve feeds, use `detect_duplicate_groups()`. It runs Union-Find clustering to collect all aliases of the same underlying entity into a single group, regardless of whether every pair individually crosses the threshold:
+
+```python
+from semantica.deduplication import DuplicateDetector, EntityMerger
+
+detector = DuplicateDetector(
+ similarity_threshold=0.6,
+ confidence_threshold=0.5,
+ use_clustering=True, # enable Union-Find grouping
+)
+
+groups = detector.detect_duplicate_groups(threat_actors)
+
+print(f"Found {len(groups)} duplicate groups:")
+for group in groups:
+ names = [e["name"] for e in group.entities]
+ print(f" Group (confidence={group.confidence:.2f}): {names}")
+ if group.representative:
+ print(f" Representative: {group.representative['name']!r}")
+```
+
+```text
+Found 2 duplicate groups:
+ Group (confidence=0.74): ['APT29', 'APT-29', 'Cozy Bear', 'The Dukes', 'Midnight Blizzard']
+ Representative: 'APT29' # highest completeness score in the group
+
+ Group (confidence=0.81): ['APT28', 'Fancy Bear']
+ Representative: 'APT28'
+```
+
+The group result shows the problem clearly: five separate nodes that should be one. The `representative` field is the entity the merger will use as the base — the one with the most filled properties, in this case "APT29" from the MISP feed which carries the fullest attribute set.
+
+## Merging: collapsing the group without losing data
+
+Now merge. The `keep_most_complete` strategy keeps the entity with the highest property count as the canonical node and fills in any missing fields from the other sources. With `preserve_provenance=True`, the merge operation records which source contributed every field in the merged result:
+
+```python
+merger = EntityMerger(preserve_provenance=True)
+
+for group in groups:
+ if len(group.entities) < 2:
+ continue
+
+ operations = merger.merge_duplicates(group.entities, strategy="keep_most_complete")
+
+ for op in operations:
+ canonical = op.merged_entity
+ source_ids = [e["id"] for e in op.source_entities]
+ print(f"Merged {len(op.source_entities)} entities → canonical: {canonical['name']!r}")
+ print(f" Source IDs retired : {source_ids}")
+ print(f" Merge strategy : {op.merge_result}")
+ print(f" Timestamp : {op.timestamp}")
+```
+
+```text
+Merged 5 entities → canonical: 'APT29'
+ Source IDs retired : ['ta-nvd-001', 'ta-of-002', 'ta-rf-003', 'ta-sx-004', 'ta-ms-005']
+ Merge strategy : MergeResult.KEPT_MOST_COMPLETE
+ Timestamp : 2026-06-21T09:14:02.443Z
+```
+
+The five source entities are replaced by one. Every relationship those five nodes carried — to campaigns, malware families, TTPs, infrastructure — now attaches to the canonical "APT29" node. Nothing is lost; the provenance records show exactly which feed contributed which attribute.
+
+## Reviewing merge history for audit
+
+After a batch merge, pull the full history to review every decision made:
+
+```python
+history = merger.get_merge_history()
+
+print(f"Total merge operations: {len(history)}")
+for op in history:
+ print(f" {op.merged_entity['name']!r} ← {len(op.source_entities)} sources")
+ print(f" strategy: {op.merge_result}")
+```
+
+This history is what you present when a feed owner asks why their entity was merged into another one. Every decision is recorded.
+
+## Streaming ingestion: incremental deduplication
+
+When your pipeline is ingesting continuously — new STIX bundles arriving hourly — you don't want to re-run pairwise comparison over the entire graph on every batch. Use `incremental_detect()` to compare only the new entities against the existing set:
+
+```python
+# Existing graph entities (already deduplicated)
+existing_actors = [
+ {"id": "ta-nvd-001", "name": "APT29", "type": "ThreatActor", "country": "Russia"},
+]
+
+# New batch arriving from a fresh feed
+new_batch = [
+ {"id": "ta-new-007", "name": "NOBELIUM", "type": "ThreatActor",
+ "aliases": ["APT29"], "country": "Russia", "source": "MSTIC-2026-06"},
+ {"id": "ta-new-008", "name": "Scattered Spider", "type": "ThreatActor",
+ "country": "Unknown", "source": "CrowdStrike"},
+]
+
+incremental = detector.incremental_detect(new_batch, existing_actors)
+
+print(f"New duplicates found in this batch: {len(incremental)}")
+for c in incremental:
+ print(f" {c.entity1['name']!r} matches existing {c.entity2['name']!r}")
+ print(f" score={c.similarity_score:.2f}")
+```
+
+```text
+New duplicates found in this batch: 1
+ 'NOBELIUM' matches existing 'APT29'
+ score=0.67 # alias field carries "APT29" — property signal fires
+```
+
+NOBELIUM goes to the merge queue. Scattered Spider scores below threshold against every existing actor and gets added to the graph as a new node.
+
+## Scaling to large entity sets
+
+For graphs above ten thousand nodes, pairwise comparison becomes too slow. Use `build_clusters()` to run vectorized batch comparison, then merge each cluster:
+
+```python
+from semantica.deduplication import build_clusters
+
+# Ten thousand CVE entities from NVD, Vulhub, and vendor feeds
+# (not shown — assume `all_vulns` is a list of 10k+ dicts)
+
+cluster_result = build_clusters(
+ all_vulns,
+ method="graph_based", # Union-Find over similarity graph
+ similarity_threshold=0.75,
+)
+
+print(f"Clusters found : {len(cluster_result.clusters)}")
+print(f"Unclustered : {len(cluster_result.unclustered)}")
+print(f"Quality metrics : {cluster_result.quality_metrics}")
+
+# Merge each cluster
+merger = EntityMerger(preserve_provenance=True)
+for cluster in cluster_result.clusters:
+ if len(cluster.entities) > 1:
+ merger.merge_duplicates(cluster.entities, strategy="keep_most_complete")
+```
+
+For even larger sets, switch to `method="hierarchical"` which uses agglomerative bottom-up clustering and scales to hundreds of thousands of entities at the cost of some precision.
+
+## Domain examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+A threat intelligence platform ingests actor profiles from Mandiant, CrowdStrike, MITRE ATT&CK, and partner ISAC feeds. The same actors appear under vendor-specific names: "Cozy Bear" (CrowdStrike), "APT29" (MITRE), "Midnight Blizzard" (Microsoft), "The Dukes" (F-Secure). Before any analyst query runs, these aliases must collapse to a single canonical node so that relationships — malware used, infrastructure operated, campaigns attributed — all attach to one place.
+
+The alias field is the key signal here. Property-based similarity will fire strongly when any record carries the canonical name in its `aliases` list. Setting a moderate threshold (0.6) catches alias-based matches that name similarity alone would miss.
+
+```python
+from semantica.deduplication import DuplicateDetector, EntityMerger
+
+actors = [
+ {"id": "ta-cs-001", "name": "Cozy Bear", "type": "ThreatActor",
+ "aliases": ["APT29", "The Dukes"], "country": "Russia", "source": "CrowdStrike"},
+ {"id": "ta-mt-002", "name": "APT29", "type": "ThreatActor",
+ "aliases": [], "country": "Russia", "source": "MITRE"},
+ {"id": "ta-ms-003", "name": "Midnight Blizzard", "type": "ThreatActor",
+ "aliases": ["NOBELIUM", "APT29"], "country": "Russia", "source": "Microsoft"},
+ {"id": "ta-fs-004", "name": "The Dukes", "type": "ThreatActor",
+ "aliases": ["APT29", "Cozy Bear"], "country": "Russia", "source": "F-Secure"},
+ {"id": "ta-mt-005", "name": "APT28", "type": "ThreatActor",
+ "aliases": ["Fancy Bear"], "country": "Russia", "source": "MITRE"},
+]
+
+detector = DuplicateDetector(similarity_threshold=0.6, confidence_threshold=0.5)
+groups = detector.detect_duplicate_groups(actors)
+
+merger = EntityMerger(preserve_provenance=True)
+for group in groups:
+ if len(group.entities) < 2:
+ continue
+ ops = merger.merge_duplicates(group.entities, strategy="keep_most_complete")
+ for op in ops:
+ feeds = [e["source"] for e in op.source_entities]
+ print(f"Canonical: {op.merged_entity['name']!r} (merged from: {feeds})")
+ # Canonical: 'APT29' (merged from: ['CrowdStrike', 'MITRE', 'Microsoft', 'F-Secure'])
+ # All four actor nodes collapse to one — every relationship they held now
+ # attaches to the canonical APT29 node.
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+A SOC vulnerability management database ingests CVEs from NVD, Vulhub, CISA KEV, and vendor advisories. The same CVE often arrives as "CVE-2024-3400" from NVD, "PAN-OS GlobalProtect RCE" from a Tenable plugin, and "Critical PAN-OS 0day" from a blog post aggregator. Name similarity alone won't match these — the CVE ID in the `cve_id` field is the definitive signal.
+
+```python
+from semantica.deduplication import detect_duplicates, merge_entities
+
+vulns = [
+ {"id": "v-nvd-001", "name": "CVE-2024-3400",
+ "description": "PAN-OS GlobalProtect command injection RCE",
+ "cvss": 10.0, "source": "NVD", "type": "Vulnerability"},
+ {"id": "v-cisa-002", "name": "CVE-2024-3400",
+ "description": "Critical PAN-OS vulnerability in active exploitation",
+ "cvss": 10.0, "source": "CISA-KEV", "type": "Vulnerability"},
+ {"id": "v-ten-003", "name": "PAN-OS GlobalProtect RCE",
+ "cve_id": "CVE-2024-3400",
+ "cvss": 10.0, "source": "Tenable", "type": "Vulnerability"},
+ {"id": "v-nvd-004", "name": "CVE-2023-44487",
+ "description": "HTTP/2 Rapid Reset DDoS amplification",
+ "cvss": 7.5, "source": "NVD", "type": "Vulnerability"},
+]
+
+# Low threshold because name similarity between "CVE-2024-3400" and
+# "PAN-OS GlobalProtect RCE" is near zero — we need property signals to fire
+candidates = detect_duplicates(
+ vulns,
+ method="pairwise",
+ similarity_threshold=0.5,
+ confidence_threshold=0.4,
+)
+
+for c in candidates:
+ print(f"{c.entity1['name']!r} ~ {c.entity2['name']!r}")
+ print(f" score={c.similarity_score:.2f} signals={c.reasons}")
+ # 'CVE-2024-3400' ~ 'PAN-OS GlobalProtect RCE'
+ # score=0.61 signals=['property', 'exact'] # cve_id field match
+
+# Merge the three CVE-2024-3400 variants
+cve_group = [v for v in vulns if "3400" in v["name"] or v.get("cve_id") == "CVE-2024-3400"]
+ops = merge_entities(cve_group, method="keep_most_complete", preserve_provenance=True)
+for op in ops:
+ print(f"Canonical CVE: {op.merged_entity['name']} CVSS={op.merged_entity.get('cvss')}")
+ # Canonical CVE: CVE-2024-3400 CVSS=10.0
+ # One node now carries all three source records' provenance.
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+A clinical trial knowledge graph ingests drug entities from the WHO INN list, PubChem, brand name databases, and trial registries. Warfarin appears as "warfarin" (INN), "Coumadin" (brand, Bristol-Myers Squibb), "warfarin sodium" (PubChem chemical form), and "81-81-2" (CAS number). The CAS number is the ground truth — if two records share a CAS number, they are the same compound regardless of what name they carry.
+
+```python
+from semantica.deduplication import DuplicateDetector, EntityMerger, calculate_similarity
+
+compounds = [
+ {"id": "c-inn-001", "name": "warfarin", "type": "Drug",
+ "cas": "81-81-2", "source": "WHO-INN"},
+ {"id": "c-bms-002", "name": "Coumadin", "type": "Drug",
+ "cas": "81-81-2", "source": "BMS-brand"},
+ {"id": "c-pc-003", "name": "warfarin sodium", "type": "Drug",
+ "source": "PubChem"}, # no CAS — less complete record
+ {"id": "c-inn-004", "name": "metoprolol", "type": "Drug",
+ "cas": "37350-58-6","source": "WHO-INN"},
+ {"id": "c-nov-005", "name": "Lopressor", "type": "Drug",
+ "cas": "37350-58-6","source": "Novartis-brand"},
+]
+
+# The property method scores CAS number matches extremely high
+sim = calculate_similarity(compounds[0], compounds[1], method="property")
+print(f"warfarin vs Coumadin: {sim.score:.2f}")
+# warfarin vs Coumadin: 0.91 — CAS match dominates
+
+detector = DuplicateDetector(similarity_threshold=0.6, confidence_threshold=0.5)
+groups = detector.detect_duplicate_groups(compounds)
+
+merger = EntityMerger(preserve_provenance=True)
+for group in groups:
+ if len(group.entities) < 2:
+ continue
+ ops = merger.merge_duplicates(group.entities, strategy="keep_most_complete")
+ for op in ops:
+ print(f"Canonical: {op.merged_entity['name']!r} CAS={op.merged_entity.get('cas')}")
+ print(f" Sources: {[e['source'] for e in op.source_entities]}")
+ # Canonical: 'warfarin' CAS=81-81-2
+ # Sources: ['WHO-INN', 'BMS-brand', 'PubChem']
+ # All three warfarin records merge; WHO-INN record wins as most complete.
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+A risk management system resolves corporate clients across CRM, KYC, and trading systems before building the counterparty exposure graph. The Legal Entity Identifier (LEI) is the definitive identifier — a 20-character ISO 17442 code that uniquely identifies every legal entity globally. If two records share an LEI, they are the same legal entity regardless of how the name is formatted.
+
+Three BlackRock records — "BlackRock Inc." (CRM), "BlackRock, Inc." (KYC, with comma), "Blackrock" (trading system, lowercase b) — must collapse to one canonical counterparty before credit exposure is aggregated. The property similarity method, which scores LEI matches near 1.0, handles this even when name similarity is moderate.
+
+```python
+from semantica.deduplication import build_clusters, EntityMerger
+
+clients = [
+ {"id": "crm-001", "name": "BlackRock Inc.", "type": "Client",
+ "lei": "549300HLPTRASHS0E726", "source": "CRM"},
+ {"id": "kyc-001", "name": "BlackRock, Inc.", "type": "Client",
+ "lei": "549300HLPTRASHS0E726", "source": "KYC"},
+ {"id": "trd-001", "name": "Blackrock", "type": "Client",
+ "lei": "549300HLPTRASHS0E726", "source": "TradeOps"},
+ {"id": "crm-002", "name": "Vanguard Group", "type": "Client",
+ "lei": "549300IH7BVXP9VN3J07", "source": "CRM"},
+ {"id": "kyc-002", "name": "The Vanguard Group, Inc.", "type": "Client",
+ "lei": "549300IH7BVXP9VN3J07", "source": "KYC"},
+]
+
+cluster_result = build_clusters(
+ clients,
+ method="graph_based",
+ similarity_threshold=0.65, # LEI match alone scores above this
+)
+
+merger = EntityMerger(preserve_provenance=True)
+for cluster in cluster_result.clusters:
+ if len(cluster.entities) < 2:
+ continue
+ ops = merger.merge_duplicates(cluster.entities, strategy="keep_most_complete")
+ for op in ops:
+ sources = [e["source"] for e in op.source_entities]
+ print(f"Canonical: {op.merged_entity['name']!r} (from {sources})")
+ # Canonical: 'BlackRock Inc.' (from ['CRM', 'KYC', 'TradeOps'])
+ # Canonical: 'Vanguard Group' (from ['CRM', 'KYC'])
+
+print(f"\nBefore: {len(clients)} client records")
+print(f"After : {len(cluster_result.clusters)} canonical counterparties")
+print(f"Quality: {cluster_result.quality_metrics}")
+```
+
+</Tab>
+
+</Tabs>
+
+## Choosing the right threshold
+
+The similarity threshold controls sensitivity. Start at 0.7 and examine false positives before adjusting:
+
+- **0.95 and above** — near-exact string matches only. Use for codes and IDs (LEI, CAS, CVE-ID) where name format is consistent across feeds.
+- **0.80–0.95** — catches typographic variants: "Apple Inc." vs "Apple, Inc.", "BlackRock" vs "BlackRock Inc."
+- **0.65–0.80** — catches abbreviations and short forms. Necessary for organization names that appear in both long and short forms across feeds.
+- **0.50–0.65** — semantic similarity territory. Requires property or embedding signals to compensate for weak name similarity. Use this range for alias-based matching where names may be completely different strings referring to the same entity.
+
+## Choosing a merge strategy
+
+| Strategy | Use when |
+| :--- | :--- |
+| `keep_most_complete` | You don't have a designated authoritative source; maximize information density. Default choice. |
+| `keep_first` | Your first source is a golden-record system (MDM, LEI registry) whose data should never be overwritten. |
+| `keep_highest_confidence` | Your entities carry explicit confidence scores and you trust them as a quality signal. |
+| `merge_all` | You want a superset of all properties; acceptable when you'll run conflict resolution afterwards to reconcile disagreements. |
+
+## Related Guides
+
+- [Ingest Anything](ingest) — multi-source ingestion creates the duplicates this module resolves
+- [Context Graphs](context-graphs) — store deduplicated entities directly in the knowledge graph
+- [Conflict Resolution](conflict-resolution) — after merging, reconcile disagreeing property values on the canonical entity
+- [Provenance](provenance) — track merge lineage so every canonical entity traces back to its original sources
+- [Pipeline](pipeline) — chain ingest, deduplicate, and store as a `PipelineBuilder` workflow
diff --git a/docs/guides/distance-intelligence.md b/docs/guides/distance-intelligence.md
new file mode 100644
index 00000000..6312f5b1
--- /dev/null
+++ b/docs/guides/distance-intelligence.md
@@ -0,0 +1,492 @@
+---
+title: "Distance Intelligence"
+description: "Classify graph proximity into distance bands, compute confidence decay along paths, run multi-algorithm path finding, and blend semantic similarity with structural proximity in retrieval."
+icon: "route"
+---
+
+`ContextGraph` distance intelligence answers the structural question that pure semantic similarity cannot: given two nodes, what is their precise relationship in terms of graph topology, path weight, and inferential confidence? Use it to annotate attribution chains with hop counts and confidence decay, rank retrieval results by structural proximity to an anchor node, and surface implied connections for analyst review.
+
+<Info>
+ Distance Intelligence feeds into proximity-blended retrieval (`proximity_weight` on `retrieve()`), causal chain analysis (`trace_decision_causality()`), and advanced precedent search (`find_precedents_hybrid()`). Enable it by passing `include_distance_metadata=True` on neighbor queries or `proximity_weight > 0` on retrieval calls.
+</Info>
+
+## Distance Bands: Turning Hop Counts into Meaning
+
+The first tool in distance intelligence is `classify_path_distance` — it maps any BFS depth to a human-readable band that carries semantic meaning.
+
+```python
+from semantica.utils.helpers import classify_path_distance
+
+print(classify_path_distance(0)) # "direct" — same node
+print(classify_path_distance(1)) # "direct" — single edge
+print(classify_path_distance(2)) # "near" — two-hop neighbourhood
+print(classify_path_distance(3)) # "near"
+print(classify_path_distance(5)) # "mid-range"
+print(classify_path_distance(9)) # "distant" — treat with caution
+```
+
+| Band | Hop Range | What it means in practice |
+| :--- | :-------- | :------------------------ |
+| `"direct"` | 0–1 | Direct relationship — high confidence inferences |
+| `"near"` | 2–3 | Two-hop neighbourhood — closely related, reliable |
+| `"mid-range"` | 4–6 | Reachable but semantically separated |
+| `"distant"` | 7+ | Weakly coupled — treat inferences with caution |
+
+These bands appear automatically on every result that uses `include_distance_metadata=True`, `proximity_weight > 0`, or `trace_decision_causality()`. You do not compute them manually — they are attached to the result.
+
+## Confidence Decay: How Trust Erodes Along a Path
+
+Each hop along a path multiplies the accumulated confidence by the edge weight. The product — `confidence_decay` — is the single most useful signal for deciding whether a multi-hop inference is trustworthy.
+
+```python
+from semantica.context import ContextGraph
+
+graph = ContextGraph()
+graph.add_node("apt29", "ThreatActor", "APT29 / NOBELIUM")
+graph.add_node("hammertoss", "Malware", "HAMMERTOSS C2 tool")
+graph.add_node("twitter_c2", "Infrastructure","APT29 Twitter C2 channel")
+graph.add_node("nato_target", "Target", "NATO defense contractor")
+
+graph.add_edge("apt29", "hammertoss", "deploys", weight=0.95)
+graph.add_edge("hammertoss", "twitter_c2", "uses", weight=0.88)
+graph.add_edge("twitter_c2", "nato_target", "reaches", weight=0.80)
+
+# Request neighbors with full distance metadata attached
+neighbors = graph.get_neighbors(
+ "apt29",
+ hops=3,
+ include_distance_metadata=True,
+)
+
+for n in neighbors:
+ print("{:20s} band={:10s} decay={:.3f} hop={}".format(
+ n["id"],
+ n["distance_band"],
+ n["confidence_decay"],
+ n["hop"],
+ ))
+```
+
+Output:
+
+```text
+hammertoss band=direct decay=0.950 hop=1
+twitter_c2 band=near decay=0.836 hop=2
+nato_target band=near decay=0.669 hop=3
+```
+
+The `nato_target` node is reachable — but with only 0.669 confidence decay. That means any inference drawn from the connection between APT29 and the NATO contractor carries a 33% uncertainty budget accumulated across three hops. At "near" band, the inference is still usable; at "distant" band with similar decay, you would flag it for human review.
+
+## Getting All Neighbors with Distance Metadata
+
+`get_neighbor_distances` returns every reachable node up to a given hop depth, filtered by a minimum confidence threshold, ordered by nearest hops first and strongest decay first within each hop.
+
+```python
+neighbors = graph.get_neighbor_distances(
+ "apt29",
+ hops=4,
+ relationship_types=["deploys", "uses", "reaches"],
+ min_confidence=0.60, # drop nodes where confidence_decay < 0.60
+)
+
+# Each result dict contains:
+# "id", "type", "content" — node identity
+# "relationship" — edge type of the last hop
+# "weight" — edge weight of the last hop
+# "hop" — BFS depth from anchor
+# "distance_band" — "direct" / "near" / "mid-range" / "distant"
+# "confidence_decay" — product of all edge weights along the path
+# "path_to_anchor" — full node ID list from anchor to this node
+
+for n in neighbors:
+ print("[{:10s}] {:20s} decay={:.3f} path={}".format(
+ n["distance_band"],
+ n["id"],
+ n["confidence_decay"],
+ " → ".join(n["path_to_anchor"]),
+ ))
+```
+
+## Finding the Shortest Path Between Two Nodes
+
+`PathFinder` exposes five path algorithms. The right one depends on whether you need the single cheapest path, multiple alternative paths, or all paths from a source.
+
+```python
+from semantica.kg import PathFinder
+
+pf = PathFinder()
+```
+
+**Dijkstra — weighted shortest path.** Use this as the default. It finds the path where the sum of edge weights is minimised.
+
+```python
+path = pf.dijkstra_shortest_path(
+ graph = graph,
+ source = "apt29",
+ target = "nato_target",
+)
+length = pf.path_length(graph, path)
+print("Shortest path:", " → ".join(path))
+print("Path length :", round(length, 3))
+```
+
+**BFS — unweighted shortest path.** Use when you want fewest hops regardless of edge weights.
+
+```python
+path = pf.bfs_shortest_path(graph, "apt29", "nato_target")
+print("Hop count:", len(path) - 1)
+```
+
+**K-shortest paths — Yen's algorithm.** Use when you need alternative attribution chains, redundancy analysis, or corroboration routes. Finding the three shortest paths and showing they all converge on the same target is stronger evidence than a single path.
+
+```python
+k_paths = pf.find_k_shortest_paths(graph, "apt29", "nato_target", k=3)
+
+for i, path in enumerate(k_paths, 1):
+ length = pf.path_length(graph, path)
+ band = classify_path_distance(len(path) - 1)
+ print("Path {} [{}] length={:.3f}: {}".format(
+ i, band, length, " → ".join(path)
+ ))
+```
+
+**All shortest paths from a source.** Use when you want to map everything reachable from an anchor node and understand the structural layout.
+
+```python
+all_paths = pf.all_shortest_paths(graph, source="apt29")
+
+for target, paths in all_paths.items():
+ path = paths[0]
+ print("{:20s} hops={} path={}".format(
+ target, len(path) - 1, " → ".join(path)
+ ))
+```
+
+## Proximity-Blended Retrieval
+
+Standard semantic retrieval ranks results by text similarity to the query. Proximity-blended retrieval adds a second signal: how structurally close is each result to an anchor node in the graph? The `proximity_weight` parameter controls the blend.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ hybrid_alpha=0.5,
+)
+
+context.store([
+ "APT29 exploited CVE-2024-3400 in PAN-OS targeting NATO governments.",
+ "HAMMERTOSS is APT29's C2 tool using Twitter as a covert channel.",
+ "SUNBURST was a supply chain implant targeting SolarWinds Orion.",
+], extract_entities=True, extract_relationships=True)
+
+# 70% semantic + 30% graph proximity, anchored at APT29
+results = context.retrieve(
+ "nation-state C2 infrastructure",
+ max_results = 8,
+ use_graph = True,
+ anchor_node = "APT29",
+ max_hops = 3,
+ proximity_weight = 0.30,
+ min_score = 0.20,
+)
+
+for r in results:
+ print("[{:.3f}] band={:10s} hop={} decay={:.3f} {}".format(
+ r.get("combined_score", r["score"]),
+ r.get("distance_band", "-"),
+ r.get("hop_distance", "-"),
+ r.get("confidence_decay", 0),
+ r["content"][:70],
+ ))
+```
+
+When `proximity_weight > 0`, each result gains `proximity_score`, `combined_score`, `hop_distance`, `distance_band`, `confidence_decay`, and `path_to_anchor` — giving you a complete picture of why each result ranked where it did.
+
+## Finding Structurally Similar Nodes
+
+When you want to know which other nodes in the graph behave like a given node — same connectivity pattern or similar text — `find_similar_nodes` exposes the modes implemented on `ContextGraph` today.
+
+```python
+# Content similarity — text overlap on node content fields
+content_similar = graph.find_similar_nodes(
+ "CVE-2024-3400",
+ similarity_type = "content",
+ top_k = 5,
+)
+
+# Structural similarity — nodes with similar neighbourhood topology
+struct_similar = graph.find_similar_nodes(
+ "CVE-2024-3400",
+ similarity_type = "structural",
+ top_k = 5,
+)
+
+for n in content_similar:
+ print("[{:.3f}] {} {}".format(n["score"], n["type"], n["id"]))
+```
+
+`similarity_type="content"` compares node text/content, while `similarity_type="structural"` compares neighbourhood topology. Other values currently fall back to content similarity, so reserve `"embedding"` for lower-level KG APIs rather than `ContextGraph.find_similar_nodes()`.
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+Finding the primary attribution path from a C2 IP to a threat actor, then finding all alternative corroboration paths to strengthen the attribution case before it goes into an intelligence product.
+
+```python
+from semantica.context import ContextGraph
+from semantica.kg import PathFinder
+from semantica.utils.helpers import classify_path_distance
+
+graph = ContextGraph(advanced_analytics=True)
+
+for node_id, ntype, content in [
+ ("apt29", "ThreatActor", "APT29 / NOBELIUM / Cozy Bear"),
+ ("hammertoss", "Malware", "HAMMERTOSS C2 backdoor"),
+ ("twitter_c2", "Infrastructure","APT29 Twitter C2 (steganography)"),
+ ("github_c2", "Infrastructure","APT29 GitHub dead-drop resolver"),
+ ("as200651", "Network", "APT29 hosting cluster AS200651"),
+ ("nato_gov", "Target", "NATO government agency"),
+]:
+ graph.add_node(node_id, ntype, content)
+
+graph.add_edge("apt29", "hammertoss", "deploys", weight=0.95)
+graph.add_edge("hammertoss","twitter_c2", "c2_via", weight=0.88)
+graph.add_edge("hammertoss","github_c2", "c2_via", weight=0.82)
+graph.add_edge("twitter_c2","as200651", "hosted_on", weight=0.90)
+graph.add_edge("github_c2", "as200651", "resolves", weight=0.76)
+graph.add_edge("as200651", "nato_gov", "targets", weight=0.85)
+
+pf = PathFinder()
+
+# Primary attribution path
+primary = pf.dijkstra_shortest_path(graph, "apt29", "nato_gov")
+length = pf.path_length(graph, primary)
+band = classify_path_distance(len(primary) - 1)
+print("Primary [{}] length={:.3f}: {}".format(band, length, " → ".join(primary)))
+
+# Three corroboration paths
+k_paths = pf.find_k_shortest_paths(graph, "apt29", "nato_gov", k=3)
+for i, path in enumerate(k_paths, 1):
+ l = pf.path_length(graph, path)
+ b = classify_path_distance(len(path) - 1)
+ print("Alt {}: {} [{}, length={:.3f}]".format(i, " → ".join(path), b, l))
+
+# All reachable from APT29 with confidence >= 60%
+neighbors = graph.get_neighbor_distances("apt29", hops=4, min_confidence=0.60)
+print("\nReachable from APT29 (confidence >= 60%):")
+for n in neighbors:
+ print(" [{:10s}] decay={:.3f} {}".format(
+ n["distance_band"], n["confidence_decay"], n["id"]
+ ))
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+Mapping the lateral movement attack graph, finding all alternative routes an attacker could take to the domain controller, and scoring each route by confidence decay to prioritise which paths to block first.
+
+```python
+from semantica.context import ContextGraph
+from semantica.kg import PathFinder
+
+graph = ContextGraph()
+
+for node_id, ntype, content in [
+ ("attacker_ip", "ExternalHost", "Attacker 185.220.101.47"),
+ ("wkstn047", "Host", "Compromised workstation WKSTN-047"),
+ ("svc_backup", "Account", "Stolen service account SVC-BACKUP"),
+ ("jump_server", "Host", "Jump server JUMP-01"),
+ ("dc01", "Host", "Domain controller DC01"),
+ ("ad_forest", "Asset", "Active Directory forest root"),
+]:
+ graph.add_node(node_id, ntype, content)
+
+graph.add_edge("attacker_ip","wkstn047", "initial_access", weight=0.90)
+graph.add_edge("wkstn047", "svc_backup", "credential_theft", weight=0.85)
+graph.add_edge("svc_backup", "jump_server", "lateral_move", weight=0.78)
+graph.add_edge("jump_server","dc01", "lateral_move", weight=0.88)
+graph.add_edge("wkstn047", "dc01", "direct_smb", weight=0.60)
+graph.add_edge("dc01", "ad_forest", "controls", weight=0.98)
+
+pf = PathFinder()
+
+# All routes to DC01 — which to block first?
+routes = pf.find_k_shortest_paths(graph, "attacker_ip", "dc01", k=3)
+for i, route in enumerate(routes, 1):
+ length = pf.path_length(graph, route)
+ print("Route {} (length={:.3f}): {}".format(i, length, " → ".join(route)))
+
+# What is exposed if DC01 is compromised?
+exposed = graph.get_neighbor_distances("dc01", hops=2, min_confidence=0.70)
+for n in exposed:
+ print("Exposed: {:15s} [{:8s}] decay={:.3f}".format(
+ n["id"], n["distance_band"], n["confidence_decay"]
+ ))
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+Mapping drug-enzyme inhibition chains, computing confidence decay for multi-step metabolic pathways, and using proximity-blended retrieval to surface the most structurally relevant drug interaction evidence.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.kg import PathFinder
+
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ graph_expansion=True,
+)
+
+for node_id, ntype, content in [
+ ("warfarin", "Drug", "Warfarin — anticoagulant, narrow therapeutic window"),
+ ("amiodarone", "Drug", "Amiodarone — antiarrhythmic"),
+ ("cyp2c9", "Enzyme", "CYP2C9 — hepatic cytochrome P450"),
+ ("bleeding", "ADE", "Major bleeding adverse event"),
+ ("cyp3a4", "Enzyme", "CYP3A4 — major metabolising enzyme"),
+ ("simvastatin", "Drug", "Simvastatin — HMG-CoA reductase inhibitor"),
+]:
+ graph.add_node(node_id, ntype, content)
+
+graph.add_edge("amiodarone", "cyp2c9", "inhibits", weight=0.92)
+graph.add_edge("cyp2c9", "warfarin", "metabolises", weight=0.95)
+graph.add_edge("warfarin", "bleeding", "risk_of", weight=0.88)
+graph.add_edge("amiodarone", "cyp3a4", "inhibits", weight=0.80)
+graph.add_edge("cyp3a4", "simvastatin","metabolises", weight=0.90)
+
+pf = PathFinder()
+
+# Interaction chain: amiodarone → bleeding (3 hops, decay = 0.92 × 0.95 × 0.88 = 0.769)
+path = pf.dijkstra_shortest_path(graph, "amiodarone", "bleeding")
+length = pf.path_length(graph, path)
+print("Interaction chain: {} (length: {:.3f})".format(" → ".join(path), length))
+
+# All paths from amiodarone — what does it reach?
+all_paths = pf.all_shortest_paths(graph, "amiodarone")
+for target, paths in all_paths.items():
+ p = paths[0]
+ print(" {:15s} hops={} path={}".format(target, len(p)-1, " → ".join(p)))
+
+# Proximity-blended retrieval anchored at amiodarone
+context.store([
+ "CYP2C9 inhibition by amiodarone reduces warfarin metabolism, raising INR.",
+ "Patients on warfarin and amiodarone have 4-fold increased major bleeding risk.",
+], extract_entities=True, extract_relationships=True)
+
+results = context.retrieve(
+ "anticoagulant enzyme inhibition",
+ anchor_node = "amiodarone",
+ max_hops = 3,
+ proximity_weight = 0.35,
+ max_results = 5,
+)
+for r in results:
+ print("[{:.3f}] {:10s} {}".format(
+ r.get("combined_score", r["score"]),
+ r.get("distance_band", "-"),
+ r["content"][:80],
+ ))
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+Scoring causal distance from a macroeconomic shock to specific loan portfolios, finding all exposure routes, and recording a stress-test decision with full causal chain annotation.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.kg import PathFinder
+from semantica.utils.helpers import classify_path_distance
+
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ graph_expansion=True,
+ decision_tracking=True,
+)
+
+for node_id, ntype, content in [
+ ("rate_hike", "MacroEvent", "Central bank +300bps rate cycle"),
+ ("real_estate", "Sector", "UK residential real estate"),
+ ("cre_sector", "Sector", "UK commercial real estate"),
+ ("ltv_stress", "RiskFactor", "LTV ratios deteriorate under higher rates"),
+ ("dscr_stress", "RiskFactor", "DSCR falls below 1.0 at +300bps"),
+ ("resi_portfolio", "Portfolio", "Retail mortgage book £4.2bn"),
+ ("cre_portfolio", "Portfolio", "CRE lending book £1.8bn"),
+ ("provision", "Impact", "Expected credit loss provision increase"),
+]:
+ graph.add_node(node_id, ntype, content)
+
+graph.add_edge("rate_hike", "real_estate", "depresses", weight=0.88)
+graph.add_edge("rate_hike", "cre_sector", "depresses", weight=0.85)
+graph.add_edge("real_estate", "ltv_stress", "causes", weight=0.78)
+graph.add_edge("cre_sector", "dscr_stress", "causes", weight=0.82)
+graph.add_edge("ltv_stress", "resi_portfolio", "exposes", weight=0.90)
+graph.add_edge("dscr_stress", "cre_portfolio", "exposes", weight=0.88)
+graph.add_edge("resi_portfolio","provision", "increases", weight=0.75)
+graph.add_edge("cre_portfolio", "provision", "increases", weight=0.80)
+
+pf = PathFinder()
+
+# How does a rate hike reach ECL provisions?
+k_routes = pf.find_k_shortest_paths(graph, "rate_hike", "provision", k=3)
+for i, route in enumerate(k_routes, 1):
+ length = pf.path_length(graph, route)
+ hops = len(route) - 1
+ band = classify_path_distance(hops)
+ print("Route {} [{:10s}] length={:.3f}: {}".format(
+ i, band, length, " → ".join(route)
+ ))
+
+# Full risk exposure map
+exposed = graph.get_neighbor_distances("rate_hike", hops=5, min_confidence=0.65)
+print("\nRisk exposure map from rate hike:")
+for n in exposed:
+ print(" [{:10s}] decay={:.3f} {}".format(
+ n["distance_band"], n["confidence_decay"], n["id"]
+ ))
+
+# Record and trace the stress-test decision
+dec_id = context.record_decision(
+ category = "stress_test",
+ scenario = "+300bps rate shock — portfolio stress test Q3 2025",
+ reasoning = "LTV deterioration on resi book within tolerance; CRE DSCR breach requires provisioning",
+ outcome = "increase_provision_cre_book",
+ confidence = 0.87,
+ decision_maker = "risk_model_v3",
+)
+
+chains = graph.trace_decision_causality(dec_id, max_depth=5)
+for chain in chains:
+ print("\nCausal chain ({} hops, {}, decay={:.3f}):".format(
+ chain["hop_count"], chain["distance_band"], chain["confidence_decay"]
+ ))
+ print(" Interpretation:", chain["interpretation"])
+```
+
+</Tab>
+
+</Tabs>
+
+## Related Guides
+
+- [Context Graphs](context-graphs) — `ContextGraph` node and edge model; `add_edge(weight=...)` feeds confidence decay
+- [Graph Analytics](graph-analytics) — centrality, community detection, Node2Vec embeddings, link prediction
+- [Agent Memory](agent-memory) — proximity-blended retrieval (`proximity_weight`) integrates distance intelligence into memory search
+- [Decision Intelligence](decision-intelligence) — `trace_decision_causality()` for causal chains with distance annotations
+- [Reasoning & Rules](reasoning) — `TemporalReasoningEngine` for Allen interval algebra over time-bounded graph nodes
diff --git a/docs/guides/export.md b/docs/guides/export.md
new file mode 100644
index 00000000..04b25831
--- /dev/null
+++ b/docs/guides/export.md
@@ -0,0 +1,371 @@
+---
+title: "Export & Serialization"
+description: "Export knowledge graphs to RDF (Turtle, JSON-LD, N-Triples), GraphML, Cypher (Neo4j), ArangoDB AQL, CSV, Parquet, OWL, and more."
+---
+
+`export_rdf`, `export_graph`, `export_lpg`, and related functions serialize a `ContextGraph` to any of ten formats in a single call, preserving node types, edge weights, and metadata faithfully. Use them when downstream consumers — triple stores, graph databases, visualization tools, ML pipelines, or spreadsheet auditors — each expect a different format from the same in-memory graph.
+
+<Info>
+ All export functions take `graph.to_dict()` as their first argument — the same dict produced by `ContextGraph.to_dict()`. Build the graph once, export it to as many formats as you need without re-serializing.
+</Info>
+
+## Building the Graph to Export
+
+Before the first export, populate a graph. Every example below starts from this shared setup:
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+ctx = AgentContext(vector_store=vs, knowledge_graph=graph, graph_expansion=True)
+
+ctx.store(
+ [
+ "APT29 exploits CVE-2024-3400 in PAN-OS to target NATO defense contractors.",
+ "CVE-2024-3400 is a critical remote code execution vulnerability in GlobalProtect.",
+ "HAMMERTOSS is APT29's C2 backdoor using Twitter and GitHub as covert channels.",
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+graph_data = graph.to_dict() # single dict, reused across all exports below
+```
+
+## RDF Formats — For Triple Stores and Semantic Reasoners
+
+When your consumers are triple stores (GraphDB, Stardog, Apache Jena) or OWL reasoners (HermiT, Pellet), you want RDF. Semantica exports to all five standard RDF serializations through a single `export_rdf` call.
+
+```python
+from semantica.export import export_rdf
+
+# Turtle — the human-readable default; best for review and Git storage
+export_rdf(graph_data, "threat_graph.ttl", format="turtle")
+
+# N-Triples — one triple per line, no indentation; fastest bulk load into any triple store
+export_rdf(graph_data, "threat_graph.nt", format="ntriples")
+
+# JSON-LD — embeds @context; best when downstream consumers speak JSON natively
+export_rdf(graph_data, "threat_graph.jsonld", format="jsonld")
+
+# RDF/XML — maximum legacy interop; required by some older OWL tools
+export_rdf(graph_data, "threat_graph.rdf", format="rdfxml")
+```
+
+The format to reach for depends on your consumer. Turtle is ideal for human review and committing to Git — it is compact and readable. N-Triples is the fastest choice for bulk-loading into a SPARQL endpoint because parsers can stream it line-by-line without buffering the whole file. JSON-LD is the right choice when downstream systems already speak JSON and you want the semantic context embedded in the same payload. RDF/XML exists for compatibility with older tools that predate the other formats.
+
+## Graph Formats — For Gephi, Maltego, and Network Analysis
+
+GraphML, GEXF, and DOT are the native formats of graph analysis and visualization tools. They preserve node attributes, edge weights, and type labels, so the graph you built in Semantica renders immediately in Gephi or NetworkX with full attribute data.
+
+```python
+from semantica.export import export_graph
+
+# GraphML — widest tool support: Gephi, yEd, NetworkX, Maltego
+export_graph(graph_data, "threat_graph.graphml", format="graphml")
+
+# GEXF — richer attribute support in Gephi; better for large attributed graphs
+export_graph(graph_data, "threat_graph.gexf", format="gexf")
+
+# DOT (Graphviz) — automated layout and rendering for diagrams in reports
+export_graph(graph_data, "threat_graph.dot", format="dot")
+```
+
+The GEXF format is worth knowing about if you use Gephi for analyst briefings — it carries dynamic attributes and temporal data that GraphML cannot express. DOT is the right choice when you need Graphviz to auto-layout a graph for embedding in a PDF report or documentation site.
+
+## Neo4j Cypher — For Graph-Pattern Threat Hunting
+
+When the SOC team wants to run Cypher queries against the graph — finding threat actors that share infrastructure, or tracing multi-hop attack paths — you export to Cypher and load the result into Neo4j Desktop or Memgraph with a single command.
+
+```python
+from semantica.export import export_lpg
+
+export_lpg(graph_data, "threat_graph.cypher", method="cypher")
+```
+
+The output file contains ready-to-run `CREATE` and `MATCH` statements:
+
+```text
+CREATE (:ThreatActor {id: "apt29", name: "APT29", nation_state: "RU"})
+CREATE (:Vulnerability {id: "cve-2024-3400", cvss_score: 10.0})
+MATCH (a {id: "apt29"}), (b {id: "cve-2024-3400"}) CREATE (a)-[:EXPLOITS {confidence: 0.97}]->(b)
+```
+
+Load into Neo4j with `cypher-shell < threat_graph.cypher` or drag the file into Neo4j Desktop's import wizard. From that point, the SOC team can write Cypher queries without touching Python.
+
+## ArangoDB AQL — For Multi-Model Queries
+
+ArangoDB combines graph traversal with document queries and full-text search in a single query language. When your compliance team needs to join the graph against structured regulatory documents, ArangoDB is the right backend.
+
+```python
+from semantica.export import export_arango
+
+export_arango(
+ graph_data,
+ "regulatory.aql",
+ vertex_collection = "regulatory_nodes",
+ edge_collection = "regulatory_edges",
+ include_collection_creation = True, # emits CREATE COLLECTION statements
+ batch_size = 200, # INSERT statements batched to avoid memory spikes
+)
+```
+
+The `include_collection_creation=True` flag means the AQL file is self-contained — it creates the collections before inserting data, so you can run it against a fresh ArangoDB instance without any prior setup.
+
+## CSV — For Spreadsheet Audits and Statistical Analysis
+
+The compliance team lives in Excel. The data science team lives in pandas. Both of them need CSV. `export_csv` writes the graph as flat rows — entities and relationships as separate files when you pass a base path.
+
+```python
+from semantica.export import export_csv
+
+# Single CSV — nodes and edges interleaved with a "record_type" column
+export_csv(graph_data, "threat_graph.csv")
+
+# Split CSV — writes threat_graph_entities.csv and threat_graph_relationships.csv
+export_csv(
+ {"entities": graph_data.get("nodes", []),
+ "relationships": graph_data.get("edges", [])},
+ "threat_graph",
+)
+```
+
+The split form is more useful for downstream tools: the entities CSV feeds a pivot table of entity types; the relationships CSV feeds a network analysis in pandas or R.
+
+## Parquet — For Data Lakes and ML Pipelines
+
+When the data science team runs feature engineering over graph attributes in DuckDB, Spark, or a lakehouse, Parquet is the format they want. It is columnar, compressed, and readable by every major ML framework.
+
+```python
+from semantica.export import export_parquet
+
+export_parquet(graph_data, "threat_graph_entities.parquet")
+```
+
+Once in Parquet, the graph entities become a DataFrame that can be joined against telemetry, enriched with external features, and fed into classification models — without any custom serialization code on the data science side.
+
+## OWL — For Ontology-Based Reasoning
+
+When you have generated an OWL ontology from your graph using `OntologyGenerator`, you can export it for Protégé, HermiT reasoning, or regulatory submission.
+
+```python
+from semantica.export import export_owl
+from semantica.ontology import OntologyGenerator
+
+ontology = OntologyGenerator(base_uri="https://example.org/cti/") \
+ .generate_from_graph(graph_data)
+
+export_owl(ontology, "cti_ontology.owl", format="owl-xml")
+```
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+A CTI team needs the same threat graph in four places simultaneously: a SPARQL endpoint for cross-team queries, Gephi for the analyst briefing, Neo4j for graph-pattern threat hunting, and a JSON-LD feed for the SIEM ingestion pipeline. Four exports, one graph dict.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.ingest import ingest_file
+from semantica.export import export_rdf, export_graph, export_lpg
+import os
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+ctx = AgentContext(vector_store=vs, knowledge_graph=graph, graph_expansion=True)
+
+apt_report = ingest_file("apt29_2024_campaign.pdf", method="file")
+ctx.store(apt_report.text, extract_entities=True, extract_relationships=True)
+
+graph_data = graph.to_dict()
+os.makedirs("./exports/", exist_ok=True)
+
+# 1. Turtle → SPARQL endpoint (Apache Jena, Stardog, GraphDB)
+export_rdf(graph_data, "./exports/threat_graph.ttl", format="turtle")
+
+# 2. JSON-LD → SIEM ingestion (Splunk, Elastic) — JSON-native pipeline
+export_rdf(graph_data, "./exports/threat_graph.jsonld", format="jsonld")
+
+# 3. GraphML → Gephi for analyst briefing visualization
+export_graph(graph_data, "./exports/threat_graph.graphml", format="graphml")
+
+# 4. Cypher → Neo4j for graph-pattern threat hunting
+export_lpg(graph_data, "./exports/threat_graph.cypher", method="cypher")
+
+print("Threat graph exported to 4 formats.")
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+During an active incident the SOC needs the graph in Neo4j for hunting, in GEXF for the Gephi timeline visualization, and in GraphML for import into Maltego. All three from the same in-memory graph.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.export import export_lpg, export_graph
+import os
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+ctx = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ decision_tracking=True,
+)
+
+incidents = [
+ "Host ws-finance-03 (10.10.1.5): scheduled task created via wmiprvse.exe — T1053.005",
+ "User jsmith logged in from anomalous IP 185.220.101.7 (Tor exit node)",
+ "EDR alert on dc01: LSASS memory access by procdump.exe — T1003.001",
+]
+ctx.store(incidents, extract_entities=True, extract_relationships=True)
+
+graph_data = graph.to_dict()
+os.makedirs("./soc_exports/", exist_ok=True)
+
+# Cypher → Neo4j for Cypher-based threat hunting
+export_lpg(graph_data, "./soc_exports/incident_graph.cypher", method="cypher")
+
+# GEXF → Gephi for timeline visualization
+export_graph(graph_data, "./soc_exports/incident_graph.gexf", format="gexf")
+
+# GraphML → Maltego for link analysis
+export_graph(graph_data, "./soc_exports/incident_graph.graphml", format="graphml")
+
+print("SOC graph exported — load incident_graph.cypher into Neo4j Desktop.")
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+Clinical trial data needs to reach a SPARQL endpoint for cross-trial federated queries, a CSV for statistical analysis in R, and a Turtle file for regulatory submission. The graph encodes compound-target-disease relationships extracted from trial protocols.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.ingest import DBIngestor
+from semantica.export import export_rdf, export_csv
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph(advanced_analytics=True)
+ctx = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ retention_days=None,
+)
+
+db = DBIngestor()
+trial_rows = db.execute_query(
+ "postgresql://readonly@clindb:5432/trials",
+ "SELECT compound, target_protein, disease, mechanism FROM trial_protocols",
+)
+trial_texts = [
+ "{} targets {} in {} via {}.".format(
+ r["compound"], r["target_protein"], r["disease"], r["mechanism"]
+ )
+ for r in trial_rows
+]
+ctx.store(trial_texts, extract_entities=True, extract_relationships=True)
+
+graph_data = graph.to_dict()
+
+# N-Triples for fast bulk load into GraphDB or Stardog
+export_rdf(graph_data, "./exports/clinical_graph.nt", format="ntriples")
+
+# Turtle for human review and regulatory dossier attachment
+export_rdf(graph_data, "./exports/clinical_graph.ttl", format="turtle")
+
+# Split CSV for statistical analysis in R / SAS
+export_csv(
+ {"entities": graph_data.get("nodes", []),
+ "relationships": graph_data.get("edges", [])},
+ "./exports/clinical_graph",
+)
+
+print("Clinical graph exported — ready for SPARQL endpoint and statistical review.")
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+A regulatory knowledge graph must reach ArangoDB for multi-model compliance queries, RDF/XML for the long-term regulatory archive, and JSON-LD for the compliance dashboard API. Basel III regulations, risk parameters, and their relationships are all captured as graph nodes.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.ingest import ingest_file
+from semantica.export import export_arango, export_rdf
+import os
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+ctx = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ retention_days=2555, # 7-year regulatory retention
+)
+
+regs = [
+ ingest_file("basel3_cre20.pdf", method="file"),
+ ingest_file("sr_11_7_model_risk.pdf", method="file"),
+ ingest_file("bcbs239.pdf", method="file"),
+]
+ctx.store(
+ [r.text for r in regs],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+graph_data = graph.to_dict()
+os.makedirs("./compliance_exports/", exist_ok=True)
+
+# ArangoDB AQL for multi-model regulatory queries (graph + document joins)
+export_arango(
+ graph_data,
+ "./compliance_exports/regulatory.aql",
+ vertex_collection = "regulatory_nodes",
+ edge_collection = "regulatory_edges",
+ include_collection_creation = True,
+ batch_size = 200,
+)
+
+# RDF/XML for long-term regulatory archive (maximum legacy interop)
+export_rdf(graph_data, "./compliance_exports/regulatory_audit.rdf", format="rdfxml")
+
+# JSON-LD for compliance dashboard REST API
+export_rdf(graph_data, "./compliance_exports/regulatory.jsonld", format="jsonld")
+
+print("Compliance graph exported in 3 formats.")
+```
+
+</Tab>
+
+</Tabs>
+
+## Choosing the Right Format
+
+The format decision usually comes down to who is consuming the output and what tools they already use.
+
+If your consumer speaks SPARQL or uses a triple store, reach for Turtle (human review), N-Triples (bulk load), or JSON-LD (JSON-native pipelines). If they use a property graph database, Cypher goes to Neo4j or Memgraph; AQL goes to ArangoDB when they also need document and search queries in the same system. If they use a graph visualization tool, GraphML is the safest default with the widest tool support, GEXF gives richer attribute handling in Gephi specifically, and DOT is right when you need Graphviz to auto-render a static diagram. If they live in spreadsheets or statistical tools, CSV is the path of least resistance. If they run ML pipelines in DuckDB, Spark, or a lakehouse, Parquet is what they want.
+
+For semantic reasoning and ontology work, OWL/XML is the format — it is the only output that preserves the full class hierarchy for Protégé and HermiT.
+
+## Related Guides
+
+- [Context Graphs](context-graphs) — the `ContextGraph` object whose `to_dict()` feeds all exports
+- [Ontology Management](ontology) — export OWL ontologies generated from your graph
+- [Reasoning & Rules](reasoning) — reasoning results can be exported as RDF triples
+- [Change Management](change-management) — snapshot a graph before exporting to prove the export was made from a verified state
+- [Pipeline](pipeline) — chain ingest, extract, and export in a single `PipelineBuilder`
diff --git a/docs/guides/graph-analytics.md b/docs/guides/graph-analytics.md
new file mode 100644
index 00000000..0c46bfd8
--- /dev/null
+++ b/docs/guides/graph-analytics.md
@@ -0,0 +1,464 @@
+---
+title: "Graph Analytics"
+description: "How to find the most important nodes in your knowledge graph, discover hidden communities, measure structural similarity, and predict missing connections — with real-world examples."
+icon: "chart-network"
+---
+
+`ContextGraph` analytics — centrality, community detection, Node2Vec embeddings, link prediction, and structural similarity — answer what your graph *means*, not just what it contains. Enable them once with `advanced_analytics=True` and use them to rank the most structurally important nodes, surface hidden operational clusters, and flag implied connections before they are formally observed.
+
+<Info>
+ All analytics require `advanced_analytics=True` at construction time. Without it, every method in this guide raises `RuntimeError: advanced_analytics not enabled`. The flag lazy-initializes five sub-components: `CentralityCalculator`, `CommunityDetector`, `NodeEmbedder`, `LinkPredictor`, and `SimilarityCalculator`.
+</Info>
+
+## Setting Up the Analytical Graph
+
+```python
+from semantica.context import ContextGraph
+
+graph = ContextGraph(
+ advanced_analytics = True,
+ community_detection = True,
+ node_embeddings = True,
+)
+```
+
+If you're loading an existing graph from storage, pass the same flags — the sub-components initialize from the loaded graph state, not from a fresh empty graph.
+
+## The One-Call Snapshot
+
+Before diving into individual analyses, get the lay of the land first. `analyze_graph_with_kg()` runs every analytics pass in sequence and returns a single unified report:
+
+```python
+report = graph.analyze_graph_with_kg()
+
+print(f"Nodes: {report['graph_metrics']['node_count']}")
+print(f"Edges: {report['graph_metrics']['edge_count']}")
+print(f"Density: {report['graph_metrics']['density']:.4f}")
+print(f"Communities: {len(report['community_analysis'])}")
+```
+
+For a graph with 2,400 nodes and 8,700 edges, a density of 0.003 is completely normal — knowledge graphs are sparse by nature; most nodes connect to a small neighborhood, not to everything. If you see density above 0.1, you likely have over-connected hub nodes pulling everything together, which can distort centrality scores.
+
+Run this at the end of each ingestion batch. The result gives you a baseline to compare against the next run — if community count drops from 12 to 4 between ingestion cycles, something in the new data is bridging clusters that were previously separate. That's a signal worth investigating before the next analyst briefing.
+
+The full report structure:
+
+```text
+report
+├── "graph_metrics" → node_count, edge_count, density
+├── "centrality_analysis" → all five measures + per-node rankings
+├── "community_analysis" → detected communities + modularity score
+├── "connectivity_analysis" → connected components, diameter, avg path length
+├── "node_embeddings" → node_id → List[float] (Node2Vec vectors)
+└── "timestamp" → ISO datetime of this analysis run
+```
+
+## Finding the Kingpins — Centrality Analysis
+
+Not all nodes are equal. Centrality analysis gives each node five different scores, each measuring a different kind of importance.
+
+The key intuition: a node can have low *degree* (few direct connections) but extreme *betweenness* (everything passes through it). That's a **broker** — the node that, if removed, would fragment the graph into disconnected pieces. In threat intelligence, brokers are often infrastructure nodes: bulletproof hosting providers, shared C2 frameworks, or intermediary loaders that every campaign routes through.
+
+### Scoring a Single Node
+
+When you suspect a particular entity is significant, start with a direct score:
+
+```python
+scores = graph.get_node_centrality("APT29")
+
+# degree → 0.0420 (4.2% of nodes are direct neighbors)
+# betweenness → 0.1837 (APT29 sits on 18% of all shortest paths)
+# closeness → 0.6123 (average 1.6 hops to any other node)
+# eigenvector → 0.8941 (most of APT29's neighbors are themselves well-connected)
+# pagerank → 0.0089 (0.89% of random-walk probability mass lands here)
+
+for measure, score in scores.items():
+ print(f"{measure:12s}: {score:.4f}")
+```
+
+The betweenness score of 0.18 here is striking — it means APT29 acts as a broker for nearly a fifth of all information flows in the graph. If an analyst wants to understand "what connects our observed TTPs to known infrastructure," they have to pass through APT29. That's not just fame; that's structural power.
+
+### Bulk Rankings Across the Full Graph
+
+To rank every node across all five measures at once:
+
+```python
+from semantica.kg import CentralityCalculator
+
+calc = CentralityCalculator()
+graph_dict = graph.to_dict()
+
+all_measures = calc.calculate_all_centrality(graph_dict)
+
+# Pull top 5 by betweenness — these are your brokers
+betweenness_rankings = all_measures["centrality_measures"]["betweenness"]["rankings"]
+print("Top brokers (betweenness):")
+for entry in betweenness_rankings[:5]:
+ print(f" [{entry['score']:.4f}] {entry['node']}")
+```
+
+If you only care about two measures, pass the subset to avoid computing all five:
+
+```python
+focused = calc.calculate_all_centrality(
+ graph_dict,
+ centrality_types = ["degree", "pagerank"],
+)
+```
+
+### Which Measure to Trust?
+
+| If you want to know... | Use |
+| :--- | :--- |
+| Who has the most direct connections? | `degree` |
+| Who would most disrupt the network if removed? | `betweenness` |
+| Who can reach the rest of the network fastest? | `closeness` |
+| Who is influential because their neighbors are influential? | `eigenvector` |
+| Who matters in a random traversal of the graph? | `pagerank` |
+
+For attribution analysis, **eigenvector** centrality often surfaces the most meaningful nodes — high eigenvector means you're connected to other high-eigenvector nodes, which in threat intelligence tracks with "known-to-be-important" entities clustering together.
+
+## Mapping Threat Actor Clusters — Community Detection
+
+Centrality tells you about individual nodes. Community detection tells you about *groups* — which nodes form tightly-knit clusters with more internal connections than external ones.
+
+Imagine your graph has twenty distinct threat actor nodes. Centrality can rank them individually, but it can't tell you that twelve of them actually share infrastructure, tooling patterns, and target sectors in a way that makes them a single operational cluster, while the remaining eight split into two separate groups. Community detection finds that automatically.
+
+```python
+from semantica.kg import CommunityDetector
+
+detector = CommunityDetector()
+result = detector.detect_communities(graph.to_dict(), algorithm="louvain")
+
+communities = result["communities"] # List[List[str]] — node groups
+assignments = result["node_assignments"] # node_id → community index
+modularity = result["modularity"] # 0.0–1.0 — partition quality
+
+print(f"Found {len(communities)} communities (modularity: {modularity:.3f})")
+
+for i, members in enumerate(communities):
+ print(f"\n Community {i} — {len(members)} members")
+ print(f" Sample: {', '.join(members[:4])}")
+```
+
+**Modularity above 0.4** is generally considered meaningful — the communities found are not random. If your graph returns 0.71, that's a strong signal that the clustering is real: your threat actors genuinely form operational clusters, not just random associations.
+
+When you see a community that mixes what you thought were unrelated threat actors, that's a hypothesis worth investigating. Maybe `COZY BEAR`, `VENOMOUS BEAR`, and `FANCY BEAR` all appear in the same community because they share C2 infrastructure — despite being traditionally attributed to different GRU units.
+
+Visualize immediately with:
+
+```python
+from semantica.visualization import KGVisualizer
+
+viz = KGVisualizer()
+viz.visualize_communities(
+ graph = graph,
+ communities = communities,
+ output = "interactive",
+ file_path = "threat_clusters.html",
+)
+```
+
+## Teaching the Graph to Measure Distance — Node2Vec Embeddings
+
+Centrality and community detection are topological — they work with edges as binary connections. Node2Vec embeddings go deeper: they generate a dense vector for each node by simulating thousands of random walks through the graph, learning which nodes tend to appear in similar neighborhoods.
+
+The practical result: nodes that play similar *structural roles* end up near each other in embedding space — even if they have no direct edge between them. Two C2 domains that both sit between threat actors and victim infrastructure will have similar embeddings, even if they're in completely different parts of the graph.
+
+```python
+from semantica.kg import NodeEmbedder
+import numpy as np
+
+embedder = NodeEmbedder() # requires: pip install semantica[embeddings]
+embeddings = embedder.compute_embeddings(
+ graph_store = graph, # ContextGraph instance — not a dict
+ node_labels = None, # None = embed all node types
+ relationship_types = None, # None = traverse all edge types
+)
+# Returns: Dict[str, List[float]] — node_id → embedding vector
+
+for node_id, vec in list(embeddings.items())[:3]:
+ print(f"{node_id}: dim={len(vec)}, norm={np.linalg.norm(vec):.4f}")
+```
+
+These vectors become first-class citizens in Semantica — they're stored on `Decision` nodes as `node2vec_embedding` and used automatically by `find_precedents_by_scenario()` as the structural similarity component.
+
+## What Does This Attack Pattern Remind Me Of?
+
+Once you have embeddings, you can ask: "which nodes in my graph are structurally most similar to APT29?" This isn't about shared edges — it's about shared *role*. Which other nodes play the same position in the graph that APT29 plays?
+
+```python
+from semantica.kg import SimilarityCalculator
+
+calc = SimilarityCalculator()
+
+top5 = calc.find_most_similar(
+ embeddings = embeddings,
+ query_embedding = embeddings["APT29"],
+ top_k = 5,
+)
+
+print("Nodes most similar to APT29 (by structural role):")
+for node_id, score in top5:
+ print(f" [{score:.4f}] {node_id}")
+```
+
+If `LAZARUS` and `APT38` both appear at the top with similarity > 0.85, that's worth noting in your analyst report: these groups are playing structurally identical roles in the graph, which may warrant a unified tracking hypothesis even if traditional attribution keeps them separate.
+
+To compare two nodes directly:
+
+```python
+score = calc.cosine_similarity(embeddings["APT29"], embeddings["LAZARUS"])
+print(f"Structural similarity APT29 ↔ LAZARUS: {score:.4f}")
+```
+
+For a quicker path that doesn't require pre-computing all embeddings:
+
+```python
+similar = graph.find_similar_nodes(
+ "APT29",
+ similarity_type = "structural",
+ top_k = 5,
+)
+for r in similar:
+ print(f" [{r['score']:.4f}] {r['type']:20s} {r['id']}")
+```
+
+## Anticipating the Next Move — Link Prediction
+
+Link prediction answers a different question: not "which nodes are similar" but "which edges are *missing*?" The graph may lack a direct connection between two nodes not because the connection doesn't exist, but because you haven't observed it yet.
+
+In practice: you have `APT29 → uses → SUNBURST` and `SUNBURST → targets → Windows Server 2019`. Link prediction might surface `APT29 → targets → Windows Server 2019` with a high score — the connection is implied by transitivity but hasn't been explicitly drawn.
+
+```python
+from semantica.kg import LinkPredictor
+
+predictor = LinkPredictor()
+predictions = predictor.predict_links(graph.to_dict(), top_k=10)
+
+print("Predicted missing links:")
+for node1, node2, score in predictions:
+ print(f" [{score:.4f}] {node1} → {node2}")
+```
+
+A score above 0.8 is worth analyst review — these aren't random; they're edges the topology of the existing graph strongly implies. Scores below 0.5 are noise. The sweet spot for human review is 0.6–0.8: plausible but not yet confirmed.
+
+<Info>
+ Link prediction is also available on `Decision` nodes through `DecisionQuery.predict_decision_relationships(decision_id, top_k)`. See the [Decision Intelligence guide](decision-intelligence) for how to surface causal relationships between past decisions.
+</Info>
+
+## Understanding Your Decision History
+
+When decisions are stored as nodes in the graph, `get_decision_insights()` gives you an analytical view across all of them:
+
+```python
+insights = graph.get_decision_insights()
+
+print(f"Total decisions: {insights['total_decisions']}")
+print(f"Mean confidence: {insights['confidence_stats']['mean']:.2f}")
+
+print("\nBy category:")
+for category, count in sorted(insights["categories"].items(), key=lambda x: -x[1]):
+ print(f" {category:<30} {count}")
+
+print("\nBy outcome:")
+for outcome, count in sorted(insights["outcomes"].items(), key=lambda x: -x[1]):
+ print(f" {outcome:<20} {count}")
+```
+
+The confidence stats are the tell: if mean confidence is 0.91 but minimum is 0.34, someone is making low-confidence decisions that still got recorded as final. That gap is worth flagging in a governance review.
+
+The `"advanced_analytics"` key inside `insights` contains the full `analyze_graph_with_kg()` result — so calling `get_decision_insights()` gives you the complete analytical picture without an extra call.
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI Threat Network">
+
+Your SOC just merged three threat intel feeds into a single CTI graph. Before this week's analyst briefing, you need to rank the most dangerous actors, identify hidden operational clusters, and flag implied connections that haven't been formally tracked.
+
+```python
+from semantica.context import ContextGraph
+from semantica.kg import CentralityCalculator, CommunityDetector, LinkPredictor
+from semantica.visualization import AnalyticsVisualizer
+
+graph = ContextGraph(
+ advanced_analytics = True,
+ community_detection = True,
+ node_embeddings = True,
+)
+# (Populated from MISP/OTX/OSINT ingest)
+
+# Full snapshot
+report = graph.analyze_graph_with_kg()
+print(f"Graph: {report['graph_metrics']['node_count']} nodes, "
+ f"{report['graph_metrics']['edge_count']} edges")
+
+# Rank brokers — who, if taken down, fragments the network?
+calc = CentralityCalculator()
+measures = calc.calculate_all_centrality(graph.to_dict())
+brokers = measures["centrality_measures"]["betweenness"]["rankings"][:5]
+
+print("\nTop 5 broker nodes (betweenness):")
+for entry in brokers:
+ print(f" [{entry['score']:.4f}] {entry['node']}")
+
+# Find operational clusters
+detector = CommunityDetector()
+result = detector.detect_communities(graph.to_dict(), algorithm="louvain")
+print(f"\n{len(result['communities'])} clusters "
+ f"(modularity {result['modularity']:.3f})")
+
+# Flag implied connections
+predictor = LinkPredictor()
+predictions = predictor.predict_links(graph.to_dict(), top_k=5)
+print("\nHigh-confidence implied connections:")
+for n1, n2, score in predictions:
+ if score > 0.7:
+ print(f" [{score:.3f}] {n1} → {n2}")
+```
+
+</Tab>
+
+<Tab title="Security — Active Incident">
+
+During an active incident, your graph has grown to include alert nodes, affected hosts, lateral movement edges, and identified malware. You need to understand the blast radius: which hosts are structural brokers in the lateral movement chain, and which connections haven't been formally documented yet?
+
+```python
+from semantica.context import ContextGraph
+from semantica.kg import CentralityCalculator, LinkPredictor
+
+graph = ContextGraph(advanced_analytics=True)
+# (Populated from SIEM alert correlation and EDR telemetry)
+
+calc = CentralityCalculator()
+measures = calc.calculate_all_centrality(graph.to_dict())
+
+# Betweenness finds the pivot hosts — the ones lateral movement flows through
+pivot_hosts = measures["centrality_measures"]["betweenness"]["rankings"][:5]
+print("Pivot hosts (lateral movement brokers):")
+for entry in pivot_hosts:
+ print(f" [{entry['score']:.4f}] {entry['node']}")
+
+# Identify the attacker's likely next targets
+predictor = LinkPredictor()
+predictions = predictor.predict_links(graph.to_dict(), top_k=10)
+
+print("\nLikely next lateral moves (predicted):")
+for src, dst, score in predictions:
+ if score > 0.65:
+ print(f" [{score:.3f}] {src} → {dst}")
+
+# Score a specific high-value target
+dc_scores = graph.get_node_centrality("DC-PROD-01")
+print(f"\nDomain Controller centrality:")
+print(f" Betweenness: {dc_scores['betweenness']:.4f}")
+print(f" PageRank: {dc_scores['pagerank']:.4f}")
+# High betweenness + high pagerank on a DC = confirmed pivot point
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical Trial Graph">
+
+Your clinical trial platform maintains a graph of drugs, biomarkers, patient populations, adverse event types, and regulatory decisions. At the end of each trial phase, you need to understand whether the drug cluster for metabolic syndrome is truly isolated from the cardiovascular cluster — that separation matters for co-administration risk assessment.
+
+```python
+from semantica.context import ContextGraph
+from semantica.kg import CommunityDetector, NodeEmbedder, SimilarityCalculator
+
+graph = ContextGraph(
+ advanced_analytics = True,
+ community_detection = True,
+ node_embeddings = True,
+)
+# (Populated from trial records, PubMed, and FDA adverse event database)
+
+# Find drug-disease clusters
+detector = CommunityDetector()
+result = detector.detect_communities(graph.to_dict(), algorithm="louvain")
+print(f"Clinical clusters: {len(result['communities'])} "
+ f"(modularity {result['modularity']:.3f})")
+
+# Inspect the cluster containing dapagliflozin
+drug_cluster_idx = result["node_assignments"].get("dapagliflozin")
+if drug_cluster_idx is not None:
+ cluster_members = result["communities"][drug_cluster_idx]
+ print(f"\nCluster containing dapagliflozin ({len(cluster_members)} members):")
+ for m in cluster_members[:8]:
+ print(f" {m}")
+
+# Find drugs that play the same structural role as dapagliflozin
+embedder = NodeEmbedder()
+embeddings = embedder.compute_embeddings(graph_store=graph)
+calc = SimilarityCalculator()
+
+similar_drugs = calc.find_most_similar(
+ embeddings = embeddings,
+ query_embedding = embeddings["dapagliflozin"],
+ top_k = 5,
+)
+print("\nStructurally similar to dapagliflozin:")
+for drug, score in similar_drugs:
+ print(f" [{score:.4f}] {drug}")
+```
+
+</Tab>
+
+<Tab title="Banking — Counterparty Risk">
+
+Your risk management team models counterparty relationships as a graph: banks, SPVs, exposure instruments, and regulatory entities connected by exposure, guarantees, and ownership edges. Before the quarterly stress test, you need to identify which entities are systemic — whose failure would cascade most broadly.
+
+```python
+from semantica.context import ContextGraph
+from semantica.kg import CentralityCalculator, CommunityDetector
+
+graph = ContextGraph(advanced_analytics=True, community_detection=True)
+# (Populated from regulatory filings, trade repositories, and internal exposure data)
+
+calc = CentralityCalculator()
+measures = calc.calculate_all_centrality(graph.to_dict())
+
+# Eigenvector finds "too connected to fail" — entities connected to other
+# high-centrality entities
+systemic = measures["centrality_measures"]["eigenvector"]["rankings"][:5]
+print("Systemically connected entities:")
+for entry in systemic:
+ print(f" [{entry['score']:.4f}] {entry['node']}")
+
+# Betweenness finds contagion brokers — entities that, if they defaulted,
+# would disconnect otherwise-separate parts of the exposure graph
+brokers = measures["centrality_measures"]["betweenness"]["rankings"][:5]
+print("\nContagion brokers:")
+for entry in brokers:
+ print(f" [{entry['score']:.4f}] {entry['node']}")
+
+# Find exposure clusters — groups with dense mutual exposure
+detector = CommunityDetector()
+result = detector.detect_communities(graph.to_dict(), algorithm="louvain")
+print(f"\n{len(result['communities'])} exposure clusters "
+ f"(modularity {result['modularity']:.3f})")
+```
+
+</Tab>
+
+</Tabs>
+
+## What the Numbers Mean
+
+| Score | What it tells you |
+| :--- | :--- |
+| Betweenness > 0.15 | Critical broker — investigate this node first in any attribution or root-cause analysis |
+| Modularity > 0.4 | Communities are real, not statistical noise — trust the clustering |
+| Modularity < 0.2 | Graph is too dense for meaningful community structure at this level |
+| Embedding cosine similarity > 0.85 | Two nodes are structurally near-identical — strong hypothesis for unified tracking |
+| Link prediction score > 0.7 | This edge almost certainly exists — queue for analyst confirmation |
+| Link prediction score 0.5–0.7 | Plausible but uncertain — treat as a hypothesis, not a fact |
+
+## Related Guides
+
+- [Context Graphs](context-graphs) — building and querying the underlying `ContextGraph`
+- [Visualization](visualization) — render centrality rankings and community clusters as interactive dashboards
+- [Decision Intelligence](decision-intelligence) — link prediction and structural similarity applied to decision nodes
+- [GraphRAG](graphrag) — using analytics results to ground LLM generation in the most contextually relevant subgraph
diff --git a/docs/guides/graphrag.md b/docs/guides/graphrag.md
new file mode 100644
index 00000000..07258a0d
--- /dev/null
+++ b/docs/guides/graphrag.md
@@ -0,0 +1,509 @@
+---
+title: "GraphRAG — Graph-Augmented Retrieval"
+description: "Go beyond vector search: retrieve facts, trace reasoning paths, and ground LLM responses in your knowledge graph."
+---
+
+GraphRAG combines vector similarity with knowledge graph traversal so retrieval finds structurally connected facts, not just text that sounds related. When a `ContextGraph` is attached to `AgentContext`, every retrieval call automatically blends semantic search with multi-hop graph expansion — and `query_with_reasoning()` returns an auditable reasoning path alongside the LLM answer.
+
+<Info>
+GraphRAG activates automatically when you pass `knowledge_graph=` to `AgentContext`. There is no separate mode to switch on. The `hybrid_alpha` parameter and `proximity_weight` argument control how much influence graph structure has relative to vector similarity.
+</Info>
+
+## Building the graph and loading your intelligence
+
+Before you can query the graph, you need to build it. The setup is three objects: a vector store for embedding-based retrieval, a `ContextGraph` for structural traversal, and an `AgentContext` that wires them together.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+# FAISS runs locally with no external dependencies
+vs = VectorStore(backend="faiss", dimension=768, index_path="intel.faiss")
+graph = ContextGraph(advanced_analytics=True)
+
+context = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True, # enable multi-hop traversal from seed nodes
+ max_expansion_hops=3, # APT29 → infrastructure → victim → sector is 3 hops
+ hybrid_alpha=0.6, # 60% graph influence, 40% vector similarity
+ decision_tracking=True, # record analyst queries as auditable decisions
+)
+```
+
+Now ingest your documents. `store()` with `extract_entities=True` runs the full extraction pipeline internally — NER, relation extraction, and entity linking — and populates both the vector index and the graph simultaneously:
+
+```python
+intel_documents = [
+ {
+ "content": "APT29 deployed HAMMERTOSS malware against NATO logistics networks in Jan–Mar 2025. "
+ "C2 infrastructure used Tor exit nodes in AS59796.",
+ "metadata": {"source": "FINTEL_2025_0192", "classification": "SECRET//NOFORN"},
+ },
+ {
+ "content": "HAMMERTOSS was subsequently observed on hosts in the LifeCare hospital network "
+ "(AS64496), suggesting lateral movement beyond the initial NATO targets.",
+ "metadata": {"source": "FINTEL_2025_0211"},
+ },
+ {
+ "content": "LifeCare operates 47 acute-care hospitals and is classified as Tier-1 "
+ "healthcare critical infrastructure under CISA Sector 6.",
+ "metadata": {"source": "CISA_CI_REGISTRY_2025"},
+ },
+ {
+ "content": "Healthcare critical infrastructure has been a high-priority targeting class "
+ "for Russian state-sponsored threat actors since 2022.",
+ "metadata": {"source": "NCSC_ADVISORY_2024_12"},
+ },
+]
+
+stats = context.store(
+ intel_documents,
+ extract_entities=True,
+ extract_relationships=True,
+ link_entities=True, # merge duplicate entity mentions across documents
+)
+
+print("Graph built: {} nodes, {} edges".format(
+ stats["graph_nodes"], stats["graph_edges"]
+))
+# Graph built: 18 nodes, 14 edges
+# Nodes: APT29, HAMMERTOSS, NATO, LifeCare, AS59796, CISA Sector 6, ...
+# Edges: deployed, observed_on, classified_as, targets, operates_in, ...
+```
+
+The graph now contains a connected subgraph linking APT29 to healthcare infrastructure across four document boundaries — something that would be invisible to a pure vector search.
+
+## Retrieving the relevant subgraph
+
+With the graph populated, a plain `retrieve()` call already does more than vector search. When `use_graph=True`, the retriever seeds the graph traversal from the top-k vector matches and expands outward by following edges, collecting connected facts within `max_hops`:
+
+```python
+results = context.retrieve(
+ "APT29 tactics against healthcare",
+ use_graph=True,
+ proximity_weight=0.5, # blend structural proximity into the final score
+ max_results=10,
+ expand_graph=True,
+ max_hops=3,
+)
+
+for r in results:
+ print("[combined={:.3f} vec={:.3f} prox={:.3f}] {}".format(
+ r.get("combined_score", r["score"]),
+ r["score"],
+ r.get("proximity_score", 0.0),
+ r["content"][:90],
+ ))
+
+# [combined=0.921 vec=0.884 prox=0.957] APT29 deployed HAMMERTOSS malware against NATO...
+# [combined=0.887 vec=0.701 prox=0.972] HAMMERTOSS was subsequently observed on hosts in the LifeCare...
+# [combined=0.841 vec=0.623 prox=0.961] LifeCare operates 47 acute-care hospitals...
+# [combined=0.798 vec=0.590 prox=0.907] Healthcare critical infrastructure has been a high-priority...
+```
+
+Notice the third and fourth results: their vector scores are modest (0.623 and 0.590) — neither document mentions APT29 or TTPs. But their proximity scores are high because they are structurally adjacent to the seed nodes in the graph. Pure vector retrieval would have ranked them much lower or excluded them entirely. GraphRAG surfaces them because the graph knows they are connected.
+
+When you know specifically which entity you want to anchor the traversal to, pass `anchor_node`:
+
+```python
+# Anchor on APT29 explicitly — proximity scores are calculated from this node
+apt29_intel = context.retrieve(
+ "C2 infrastructure beaconing patterns",
+ use_graph=True,
+ anchor_node="APT29",
+ proximity_weight=0.7, # strongly favour nodes close to APT29
+ max_hops=3,
+ max_results=8,
+)
+```
+
+## Getting a grounded LLM answer with a reasoning path
+
+`retrieve()` gives you the grounded context. `query_with_reasoning()` goes one step further: it passes that subgraph context to an LLM and returns the answer together with the multi-hop path the retrieval system traced through the graph. That path is your audit trail.
+
+```python
+from semantica.llms import LiteLLM
+
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+
+result = context.query_with_reasoning(
+ "What are APT29's known TTPs against healthcare infrastructure, "
+ "and what is the evidence chain connecting them?",
+ llm_provider=llm,
+ max_results=12,
+ max_hops=3,
+)
+
+# The LLM answer — grounded in graph-retrieved context, not training memory
+print(result["response"])
+
+# The multi-hop trace: APT29 → deployed → HAMMERTOSS → observed_on → LifeCare → ...
+print("\n--- Reasoning Path ---")
+print(result["reasoning_path"])
+
+# Confidence reflects how well the retrieved context supports the answer
+print("\nConfidence: {:.1%}".format(result["confidence"]))
+
+# Inspect every source the LLM was given
+print("\nSources ({} total):".format(result["num_sources"]))
+for src in result["sources"]:
+ print(" [{:.3f}] {}".format(src["score"], src["content"][:80]))
+```
+
+The `reasoning_path` field is what separates GraphRAG from a black-box LLM call. When an analyst asks "how do you know APT29 targeted healthcare?", you can show them the exact traversal the system made across your own documents — not a claim the model generated from training data.
+
+The full return structure from `query_with_reasoning()`:
+
+```python
+{
+ "response": str, # LLM-generated answer, grounded in retrieved subgraph
+ "reasoning_path": str, # multi-hop traversal narrative
+ "sources": list, # list of retrieved context dicts with scores
+ "confidence": float, # 0–1 aggregate confidence
+ "num_sources": int,
+ "num_reasoning_paths": int,
+}
+```
+
+## Domain examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+Multi-INT intelligence fusion: OSINT threat feeds, NVD CVE data, and HUMINT summaries ingested into a single graph, then queried with multi-hop reasoning to trace C2 infrastructure chains and attribute campaigns to specific actors.
+
+In classified environments the graph can be partitioned by data handling caveat — each `AgentContext` operates over the subset of documents cleared for the querying user. The `reasoning_path` output doubles as a sanitisable audit trail for downgraded reporting.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import LiteLLM
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+
+context = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ max_expansion_hops=3, # actor → infra → victim → attribution chain
+ hybrid_alpha=0.6, # graph-heavy: structured intel benefits from topology
+ decision_tracking=True,
+)
+
+# Ingest multi-INT corpus
+humint_summary = """
+HUMINT-2025-Q1-007: Source BRAVO-9 confirms APT29 operating from
+infrastructure in AS59796. C2 beacons use Tor exit nodes in DE/NL.
+Targets: ITAR-controlled defense contractors in aerospace sector.
+"""
+cti_report_text = "APT29 exploited CVE-2025-3400 in PAN-OS GlobalProtect to gain initial access..."
+
+context.store(
+ [
+ {"content": humint_summary, "metadata": {"source": "HUMINT-2025-Q1-007"}},
+ {"content": cti_report_text, "metadata": {"source": "CTI_RPT_APT29_2025"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+ link_entities=True,
+)
+
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+result = context.query_with_reasoning(
+ "Trace the C2 infrastructure chain for APT29 operations targeting "
+ "ITAR-controlled contractors in 2025. Include IP ranges, ASNs, and TTPs.",
+ llm_provider=llm,
+ max_results=15,
+ max_hops=3,
+)
+
+print(result["response"])
+print("\n--- Reasoning Path ---")
+print(result["reasoning_path"])
+print("Confidence: {:.1%}".format(result["confidence"]))
+
+# Anchor retrieval on APT29 for a proximity-weighted follow-up
+proximate = context.retrieve(
+ "C2 beaconing patterns Tor exit nodes",
+ use_graph=True,
+ anchor_node="APT29",
+ proximity_weight=0.7,
+ max_hops=3,
+ max_results=10,
+)
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+Security operations: real-time alert triage against a graph containing hosts, CVEs, user accounts, runbooks, and historical incidents. GraphRAG retrieves the relevant runbook and similar past incidents in a single call, reducing mean-time-to-respond.
+
+The `decision_tracking=True` flag records every triage query as an auditable decision, with the full context that was provided to the LLM — essential for post-incident review and SOC metrics.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import LiteLLM
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+
+soc_context = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ max_expansion_hops=2,
+ hybrid_alpha=0.5,
+ decision_tracking=True,
+ retention_days=365,
+)
+
+runbooks = [
+ "RB-001: Lateral movement — isolate source host, collect memory dump, "
+ "escalate if EDR alert on LSASS access.",
+ "RB-002: Ransomware precursor — block C2 range, snapshot affected volumes, "
+ "engage IR team within 15 minutes.",
+ "RB-003: Scheduled task persistence — review parent process, check Sigma "
+ "T1053.005, quarantine if encoded payload confirmed.",
+]
+soc_context.store(runbooks, extract_entities=True)
+
+alert_text = """
+ALERT-2025-110342 [CRITICAL]
+Host: dc01.corp.internal (10.10.1.5)
+User: svc_backup (DOMAIN\\svc_backup)
+Event: Scheduled task created — cmd.exe /c powershell -enc <base64>
+Parent: wmiprvse.exe
+Sigma match: T1053.005 Scheduled Task/Job
+"""
+
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+triage = soc_context.query_with_reasoning(
+ "Triage this SIEM alert and identify the correct response runbook:\n{}".format(alert_text),
+ llm_provider=llm,
+ max_results=8,
+ max_hops=2,
+)
+
+print("TRIAGE: {}".format(triage["response"]))
+# TRIAGE: Based on the wmiprvse.exe parent spawning an encoded PowerShell scheduled task,
+# this matches the persistence pattern in RB-003. Recommended action: review parent process
+# chain, confirm encoded payload, quarantine dc01.corp.internal if confirmed...
+print("Confidence: {:.1%}".format(triage["confidence"]))
+
+# Also pull similar historical incidents for analyst context
+similar = soc_context.retrieve(
+ "wmiprvse.exe encoded powershell scheduled task persistence",
+ use_graph=True,
+ proximity_weight=0.5,
+ max_results=5,
+)
+for inc in similar:
+ print("[{:.3f}] {}".format(inc.get("combined_score", inc["score"]), inc["content"][:100]))
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+Clinical decision support: FDA drug labels, clinical guidelines, and trial summaries ingested into a graph where drug-enzyme-metabolite-interaction chains become traversable paths. A three-hop query (drug → enzyme → metabolite → contraindication) surfaces interaction risks that no single document would make explicit.
+
+Setting `max_expansion_hops=3` is deliberate: the pharmacokinetic chain from amiodarone to elevated warfarin plasma levels runs drug → CYP2C9 inhibition → warfarin metabolism reduced → bleeding risk, which is exactly three structural hops.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import LiteLLM
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+
+clinical_context = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ max_expansion_hops=3, # drug → enzyme → metabolite → interaction
+ hybrid_alpha=0.55,
+ retention_days=None, # clinical records: no expiry
+)
+
+fda_label_text = (
+ "Warfarin sodium: narrow therapeutic index anticoagulant. CYP2C9 is the "
+ "primary metabolic pathway. Amiodarone is a potent CYP2C9 inhibitor..."
+)
+
+guideline_text = (
+ "ESC 2023 AF Guidelines: bridging therapy with heparin is not recommended "
+ "for most patients with AF undergoing elective procedures..."
+)
+
+clinical_context.store(
+ [
+ {"content": fda_label_text, "metadata": {"source": "FDA_WARFARIN_LABEL_2024"}},
+ {"content": guideline_text, "metadata": {"source": "ESC_AF_GUIDELINE_2023"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+ link_entities=True,
+)
+
+patient_context = """
+Patient: 68F, AF, CKD stage 3b (eGFR 32). On warfarin (INR target 2.0–3.0).
+Presenting for elective hip replacement. Concurrent: amiodarone 200mg, atorvastatin 40mg.
+"""
+
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+answer = clinical_context.query_with_reasoning(
+ "What is the evidence-based warfarin bridging protocol for this patient "
+ "given CKD and amiodarone interaction risk?\n\n{}".format(patient_context),
+ llm_provider=llm,
+ max_results=12,
+ max_hops=3,
+)
+
+print(answer["response"])
+print("Evidence sources: {}".format(answer["num_sources"]))
+print("Reasoning hops: {}".format(answer["num_reasoning_paths"]))
+
+# Pull the contraindication chain explicitly
+contra_chain = clinical_context.retrieve(
+ "CYP2C9 inhibition amiodarone warfarin bleeding risk",
+ use_graph=True,
+ anchor_node="warfarin",
+ proximity_weight=0.65,
+ max_hops=3,
+ max_results=6,
+)
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+Regulatory compliance: Basel III (CRE20), BCBS 239, SR 11-7, and EBA IRRBB guidelines ingested as a graph where regulation articles cross-reference each other as edges. Multi-hop queries traverse those cross-references automatically, so a question about commercial real estate RWA pulls the relevant CRE20 paragraphs and the BCBS 239 data quality requirements that govern their calculation in a single call.
+
+The `reasoning_path` output serves directly as the audit trail required by regulators to demonstrate that a capital calculation was grounded in cited regulatory text.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import LiteLLM
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+
+compliance_context = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ max_expansion_hops=2,
+ hybrid_alpha=0.5,
+ retention_days=2555, # 7-year regulatory retention
+)
+
+# In production these come from ingest_file() — shown as strings here for brevity
+basel_cre20_text = "CRE20.32: For income-producing real estate where repayment depends on "
+ "property cash flows, RWA = exposure × risk weight, where risk weight "
+ "is determined by LTV bucket per Table CRE20.3..."
+bcbs239_text = "Principle 3: Risk data should be accurate and have a single authoritative source. "
+ "Where data is aggregated across systems, reconciliation must be documented..."
+
+compliance_context.store(
+ [
+ {"content": basel_cre20_text, "metadata": {"source": "BCBS_CRE20_2024"}},
+ {"content": bcbs239_text, "metadata": {"source": "BCBS239_2013"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+answer = compliance_context.query_with_reasoning(
+ "Under Basel III CRE20, what are the RWA calculation requirements for "
+ "commercial real estate exposures with LTV > 80%? "
+ "Cross-reference with BCBS 239 data quality requirements.",
+ llm_provider=llm,
+ max_results=12,
+ max_hops=2,
+)
+
+print(answer["response"])
+print("Regulatory sources cited: {}".format(answer["num_sources"]))
+print("Confidence: {:.1%}".format(answer["confidence"]))
+
+# The reasoning path is the audit log — show it to the regulator
+print("\n--- Reasoning Path (audit log) ---")
+print(answer["reasoning_path"])
+```
+
+</Tab>
+
+</Tabs>
+
+## Tuning the vector-graph balance
+
+The `hybrid_alpha` parameter set in the `AgentContext` constructor establishes a default blend between vector similarity and graph influence. `0.0` is pure vector retrieval; `1.0` is pure graph traversal. The recommended starting point is `0.5`.
+
+You can override this per call using `proximity_weight` in `retrieve()` without changing the constructor default:
+
+```python
+# Exploratory query — let semantics lead, graph confirms
+results = context.retrieve(query, use_graph=True, proximity_weight=0.2)
+
+# Known-entity tracing — topology drives the retrieval
+results = context.retrieve(
+ query, use_graph=True, anchor_node="APT29", proximity_weight=0.8
+)
+```
+
+Each additional hop in `max_hops` exponentially increases the subgraph size. Practical defaults by domain:
+
+```text
+General Q&A max_expansion_hops=2 (95% of useful facts within 2 hops)
+Threat intel (APT) max_expansion_hops=3 (actor → infra → victim → attribution)
+Drug interactions max_expansion_hops=3 (drug → enzyme → metabolite → interaction)
+Regulatory cross-ref max_expansion_hops=2 (rule → article → article)
+```
+
+Set globally in the constructor; override per call with the `max_hops` argument to `retrieve()`.
+
+## How GraphRAG works internally
+
+```text
+Query text
+ |
+ v
+Vector embedding ─────────────────────────────────────┐
+ | |
+ v v
+Semantic search Graph traversal (BFS)
+(FAISS / Qdrant) from anchor / top-k seeds
+ | |
+ └──────────┐ ┌──────────────────────┘
+ v v
+ Score fusion (proximity_weight blend)
+ |
+ v
+ Ranked subgraph
+ |
+ v
+ LLM grounding <── query_with_reasoning()
+ |
+ v
+ {response, reasoning_path, sources, confidence}
+```
+
+The vector search and graph traversal run independently, then their scores are fused. The graph traversal uses breadth-first expansion from the seed nodes identified by the vector search, so the graph component is always anchored in semantic relevance rather than exploring the entire graph blindly.
+
+## Related Guides
+
+- [Semantic Extraction](semantic-extraction) — build the graph from raw unstructured text
+- [Agent Memory](agent-memory) — store, retrieve, and persist agent memories
+- [Context Graphs](context-graphs) — build and traverse the knowledge graph directly
+- [Reasoning](reasoning) — derive new facts and run inference rules over the graph
+- [Decision Intelligence](decision-intelligence) — causal chains, policy enforcement, decision tracking
+- [LLM Integrations](llm-integrations) — connect Groq, OpenAI, Anthropic, HuggingFace, and 100+ more
diff --git a/docs/guides/ingest.md b/docs/guides/ingest.md
new file mode 100644
index 00000000..97a4082c
--- /dev/null
+++ b/docs/guides/ingest.md
@@ -0,0 +1,683 @@
+---
+title: "Ingest Anything"
+description: "Load data from files, websites, Git repos, databases, Kafka streams, RSS feeds, and more — unified ingestion API."
+---
+
+Semantica's ingest module provides a single consistent function call for each source type. Every call returns structured objects with a `.text` property ready to pipe into `AgentContext.store()`, so heterogeneous sources compose cleanly into one graph ingestion script.
+
+<Info>
+ All ingest functions live in `semantica.ingest`. Optional dependencies are loaded lazily — you only need `pip install beautifulsoup4` for web/feed ingestion, `pip install gitpython` for repository ingestion, and `pip install pyarrow` for Parquet. Missing a dependency raises a clear `ImportError` message naming the exact package.
+</Info>
+
+## Source 1 — PDF Vendor Reports
+
+Pass a file path or directory to `ingest_file()` to extract plain text from PDFs and other document formats:
+
+```python
+from semantica.ingest import ingest_file
+
+# Single file
+report = ingest_file("apt29_q4_2024.pdf", method="file")
+print(report.text[:500]) # extracted plain text
+print(report.metadata) # {"file_type": "pdf", "size": 1843200, ...}
+print(report.name) # "apt29_q4_2024.pdf"
+print(report.file_type) # "pdf"
+
+# Whole directory at once — recursive by default
+reports = ingest_file("./vendor_reports/", method="directory", recursive=True)
+for r in reports:
+ print(f"{r.name}: {len(r.text)} chars extracted")
+
+# apt29_q4_2024.pdf: 42317 chars extracted
+# lazarus_group_h2.pdf: 38901 chars extracted
+# fin7_campaign.pdf: 51204 chars extracted
+# cozy_bear_ttps.pdf: 29876 chars extracted
+```
+
+`ingest_file()` returns a `FileObject` (single file) or `List[FileObject]` (directory). The `.text` property is always a decoded string — you never handle bytes or encoding manually. For DOCX, XLSX, CSV, TXT, JSON, and XML files the same call works; file type is detected from the extension and MIME type automatically.
+
+If your vendor also drops reports into an S3 bucket, switch to cloud ingestion without changing the rest of your pipeline:
+
+```python
+s3_reports = ingest_file(
+ "s3://intel-vendor-bucket/weekly-reports/",
+ method="cloud",
+ provider="s3",
+ aws_access_key_id="AKIA...",
+ aws_secret_access_key="...",
+)
+# Returns List[FileObject] — same shape as the local directory call
+```
+
+## Source 2 — MISP REST API
+
+`RESTIngestor` handles authentication, retry logic, and pagination:
+
+```python
+from semantica.ingest import RESTIngestor
+
+ingestor = RESTIngestor()
+
+# Single paginated endpoint — returns APIData
+api_data = ingestor.ingest_endpoint(
+ "https://misp.internal/events/restSearch",
+ headers={"Authorization": "YOUR_MISP_API_KEY"},
+ params={"limit": 100, "page": 1, "threat_level_id": "1"},
+)
+
+# api_data.data is List[Dict] — one dict per event
+events = api_data.data
+print(f"Retrieved {len(events)} MISP events")
+print(f"Endpoint: {api_data.endpoint}")
+print(f"Status: {api_data.response_status}")
+
+# Convert to text blobs for the knowledge graph
+event_texts = []
+for event in events:
+ attrs = ", ".join(
+ a.get("value", "") for a in event.get("Event", {}).get("Attribute", [])
+ )
+ text = (
+ f"MISP Event {event['Event']['id']}: "
+ f"{event['Event'].get('info', '')} "
+ f"[TLP: {event['Event'].get('distribution', '')}] "
+ f"Attributes: {attrs[:300]}"
+ )
+ event_texts.append(text)
+```
+
+For endpoints that return thousands of records across many pages, `paginated_fetch()` walks all pages automatically and returns one `APIData` object per page:
+
+```python
+all_events = ingestor.paginated_fetch(
+ "https://misp.internal/events/restSearch",
+ headers={"Authorization": "YOUR_MISP_API_KEY"},
+ page_size=100,
+)
+# all_events is List[APIData] across all pages
+total_events = sum(len(page.data) for page in all_events if isinstance(page.data, list))
+print(f"Pages fetched: {len(all_events)}")
+print(f"Total events fetched: {total_events}")
+```
+
+## Source 3 — PostgreSQL CVE Database
+
+For ad hoc SQL queries, use `DBIngestor.execute_query()`, which returns `List[Dict]`:
+
+```python
+from semantica.ingest import DBIngestor
+
+db = DBIngestor()
+
+# Returns List[Dict] — one dict per row
+cves = db.execute_query(
+ "postgresql://readonly:[email protected]:5432/nvd",
+ """
+ SELECT
+ cve_id,
+ description,
+ cvss_v3_score,
+ affected_products,
+ published_date,
+ last_modified
+ FROM cve_records
+ WHERE cvss_v3_score >= 7.0
+ AND published_date >= NOW() - INTERVAL '30 days'
+ ORDER BY cvss_v3_score DESC
+ """,
+)
+
+print(f"High-severity CVEs (last 30 days): {len(cves)}")
+
+# Convert rows to text for the knowledge graph
+cve_texts = [
+ f"{r['cve_id']} (CVSS {r['cvss_v3_score']}): "
+ f"{r['description']} "
+ f"Affects: {r['affected_products']}"
+ for r in cves
+]
+```
+
+The same `DBIngestor.execute_query()` pattern covers MySQL, SQLite, Oracle, and SQL Server — swap the connection string. For schema discovery before writing your query:
+
+```python
+schema = db.execute_query(
+ "postgresql://readonly:[email protected]:5432/nvd",
+ """
+ SELECT table_name, column_name, data_type
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ ORDER BY table_name, ordinal_position
+ """,
+)
+for col in schema[:10]:
+ print(f"{col['table_name']}.{col['column_name']} ({col['data_type']})")
+```
+
+## Source 4 — GitHub Advisory Feed
+
+`ingest_feed()` pulls RSS and Atom feeds and returns a `FeedData` object with a list of `FeedItem` objects:
+
+```python
+from semantica.ingest import ingest_feed
+
+# RSS feed — returns FeedData; iterate .items for FeedItem objects
+feed = ingest_feed(
+ "https://github.com/advisories.atom",
+ method="atom",
+)
+
+print(f"Feed title: {feed.title}")
+print(f"Total items: {len(feed.items)}")
+
+# Convert feed items to text blobs
+advisory_texts = []
+for item in feed.items:
+ text = f"Advisory: {item.title}\n{item.description}"
+ advisory_texts.append(text)
+ print(f" {item.title[:80]} [{item.published}]")
+
+# For NVD's own RSS feed of new CVEs:
+nvd_feed = ingest_feed(
+ "https://nvd.nist.gov/feeds/xml/cve/misc/nvd-rss.xml",
+ method="rss",
+)
+nvd_texts = [
+ f"{item.title}: {item.description}"
+ for item in nvd_feed.items
+]
+```
+
+If you don't know whether a site uses RSS or Atom, `method="discover"` finds all available feed URLs from the page's HTML link tags:
+
+```python
+feeds = ingest_feed("https://github.com/advisories", method="discover")
+# feeds is a list of validated feed URLs
+for f in feeds:
+ print(f)
+```
+
+## Source 5 — Filesystem STIX Bundles
+
+Use `ingest_file()` on a directory to extract text from every STIX JSON file deposited by an overnight daemon:
+
+```python
+from semantica.ingest import ingest_file
+
+# Ingest all STIX JSON files from the directory
+stix_files = ingest_file("./stix_bundles/", method="directory", recursive=True)
+
+stix_texts = []
+for f in stix_files:
+ if f.file_type == "json":
+ stix_texts.append(f.text)
+ print(f"{f.name}: {f.size:,} bytes")
+
+# apt29_stix_bundle_2024-12-01.json: 184,320 bytes
+# lazarus_stix_bundle_2024-12-01.json: 97,408 bytes
+# fin7_stix_bundle_2024-12-01.json: 211,968 bytes
+```
+
+For large XML-based STIX 1.x bundles, use `ingest_xml()` to get structured parse results instead of raw text:
+
+```python
+from semantica.ingest import ingest_xml
+
+stix_xml_files = ingest_xml("./stix_xml_bundles/", method="directory")
+for bundle in stix_xml_files:
+ print(f"{bundle.source_path}: {len(bundle.elements)} elements parsed")
+```
+
+## Combining All Five Sources
+
+With each source returning text blobs, pass everything into `AgentContext.store()` in one batch:
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.ingest import ingest_file, ingest_feed, RESTIngestor, DBIngestor
+
+# --- Infrastructure ---
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ graph_expansion = True,
+)
+
+# --- Source 1: PDF reports ---
+reports = ingest_file("./vendor_reports/", method="directory")
+report_texts = [r.text for r in reports]
+
+# --- Source 2: MISP API ---
+ingestor = RESTIngestor()
+api_data = ingestor.paginated_fetch(
+ "https://misp.internal/events/restSearch",
+ headers={"Authorization": "YOUR_MISP_API_KEY"},
+ page_size=100,
+)
+misp_texts = [
+ f"MISP {e['Event']['id']}: {e['Event'].get('info', '')} "
+ f"attrs={len(e['Event'].get('Attribute', []))}"
+ for page in api_data
+ for e in page.data
+]
+
+# --- Source 3: PostgreSQL CVEs ---
+db = DBIngestor()
+cves = db.execute_query(
+ "postgresql://readonly:[email protected]:5432/nvd",
+ "SELECT cve_id, description, cvss_v3_score FROM cve_records "
+ "WHERE cvss_v3_score >= 7.0 AND published_date >= NOW() - INTERVAL '30 days'",
+)
+cve_texts = [f"{r['cve_id']} (CVSS {r['cvss_v3_score']}): {r['description']}" for r in cves]
+
+# --- Source 4: GitHub Advisory feed ---
+feed = ingest_feed("https://github.com/advisories.atom", method="atom")
+advisory_texts = [f"{item.title}: {item.description}" for item in feed.items]
+
+# --- Source 5: STIX bundles ---
+stix_files = ingest_file("./stix_bundles/", method="directory")
+stix_texts = [f.text for f in stix_files if f.file_type == "json"]
+
+# --- Combine and store ---
+all_texts = report_texts + misp_texts + cve_texts + advisory_texts + stix_texts
+
+context.store(
+ all_texts,
+ extract_entities = True,
+ extract_relationships = True,
+)
+
+s = graph.stats()
+print(f"Graph: {s['node_count']} nodes, {s['edge_count']} edges")
+print(f"Total documents ingested: {len(all_texts)}")
+```
+
+## Handling Errors Gracefully
+
+Wrap each source in a try/except so the pipeline continues and reports failures at the end rather than crashing on the first bad source:
+
+```python
+from semantica.ingest import ingest_file, ingest_feed, RESTIngestor, DBIngestor
+
+all_texts = []
+errors = []
+
+# Source 1: PDFs
+try:
+ reports = ingest_file("./vendor_reports/", method="directory")
+ all_texts.extend(r.text for r in reports)
+ print(f"PDFs: {len(reports)} files ingested")
+except Exception as e:
+ errors.append(f"PDF ingest failed: {e}")
+
+# Source 2: MISP
+try:
+ ingestor = RESTIngestor()
+ events = ingestor.paginated_fetch(
+ "https://misp.internal/events/restSearch",
+ headers={"Authorization": "YOUR_MISP_API_KEY"},
+ page_size=100,
+ )
+ all_texts.extend(
+ f"MISP {e['Event']['id']}: {e['Event'].get('info', '')}"
+ for page in events
+ for e in page.data
+ )
+ print(f"MISP: {sum(len(page.data) for page in events if isinstance(page.data, list))} events ingested")
+except Exception as e:
+ errors.append(f"MISP API failed: {e}")
+
+# Source 3: PostgreSQL
+try:
+ db = DBIngestor()
+ cves = db.execute_query(
+ "postgresql://readonly:[email protected]:5432/nvd",
+ "SELECT cve_id, description, cvss_v3_score FROM cve_records "
+ "WHERE cvss_v3_score >= 7.0 AND published_date >= NOW() - INTERVAL '30 days'",
+ )
+ all_texts.extend(f"{r['cve_id']}: {r['description']}" for r in cves)
+ print(f"CVEs: {len(cves)} records ingested")
+except Exception as e:
+ errors.append(f"PostgreSQL failed: {e}")
+
+# Source 4: GitHub feed
+try:
+ feed = ingest_feed("https://github.com/advisories.atom", method="atom")
+ all_texts.extend(f"{item.title}: {item.description}" for item in feed.items)
+ print(f"Advisories: {len(feed.items)} items ingested")
+except Exception as e:
+ errors.append(f"GitHub feed failed: {e}")
+
+# Source 5: STIX files
+try:
+ stix_files = ingest_file("./stix_bundles/", method="directory")
+ stix_texts = [f.text for f in stix_files if f.file_type == "json"]
+ all_texts.extend(stix_texts)
+ print(f"STIX: {len(stix_texts)} bundles ingested")
+except Exception as e:
+ errors.append(f"STIX directory failed: {e}")
+
+# Report any failures — don't silently swallow them
+if errors:
+ print(f"\n{len(errors)} source(s) failed:")
+ for err in errors:
+ print(f" - {err}")
+
+print(f"\nTotal documents for graph: {len(all_texts)}")
+```
+
+## Scheduling Recurring Ingestion
+
+Wrap the combined ingestion in a function and call it from your scheduler of choice (cron, Airflow, a cloud scheduler):
+
+```python
+from datetime import datetime, timedelta
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.ingest import ingest_file, ingest_feed, RESTIngestor, DBIngestor
+
+def run_daily_ingest(since: datetime = None):
+ """Run the full five-source ingest pipeline. Returns graph stats dict."""
+ since = since or datetime.now() - timedelta(days=1)
+
+ graph = ContextGraph(advanced_analytics=True)
+ context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768,
+ index_path="cti_index.faiss"),
+ knowledge_graph = graph,
+ graph_expansion = True,
+ )
+
+ all_texts = []
+ errors = []
+
+ # PDFs deposited since last run
+ try:
+ reports = ingest_file("./vendor_reports/", method="directory")
+ # Filter by modification time in production — simplified here
+ all_texts.extend(r.text for r in reports)
+ except Exception as e:
+ errors.append(f"PDF: {e}")
+
+ # MISP events since last run
+ try:
+ ingestor = RESTIngestor()
+ events = ingestor.paginated_fetch(
+ "https://misp.internal/events/restSearch",
+ headers={"Authorization": "YOUR_MISP_API_KEY"},
+ params={"timestamp": int(since.timestamp())},
+ page_size=100,
+ )
+ all_texts.extend(
+ f"MISP {e['Event']['id']}: {e['Event'].get('info', '')}"
+ for page in events
+ for e in page.data
+ )
+ except Exception as e:
+ errors.append(f"MISP: {e}")
+
+ # CVEs published since last run
+ try:
+ db = DBIngestor()
+ cves = db.execute_query(
+ "postgresql://readonly:[email protected]:5432/nvd",
+ f"SELECT cve_id, description, cvss_v3_score FROM cve_records "
+ f"WHERE published_date >= '{since.isoformat()}' AND cvss_v3_score >= 7.0",
+ )
+ all_texts.extend(f"{r['cve_id']}: {r['description']}" for r in cves)
+ except Exception as e:
+ errors.append(f"PostgreSQL: {e}")
+
+ # GitHub advisory feed (always latest)
+ try:
+ feed = ingest_feed("https://github.com/advisories.atom", method="atom")
+ all_texts.extend(f"{item.title}: {item.description}" for item in feed.items)
+ except Exception as e:
+ errors.append(f"GitHub feed: {e}")
+
+ # STIX bundles deposited since last run
+ try:
+ stix_files = ingest_file("./stix_bundles/", method="directory")
+ all_texts.extend(f.text for f in stix_files if f.file_type == "json")
+ except Exception as e:
+ errors.append(f"STIX: {e}")
+
+ if all_texts:
+ context.store(all_texts, extract_entities=True, extract_relationships=True)
+ context.save("./cti_state/")
+
+ return {
+ "run_at": datetime.now().isoformat(),
+ "documents": len(all_texts),
+ "errors": errors,
+ "graph": graph.stats(),
+ }
+
+if __name__ == "__main__":
+ result = run_daily_ingest()
+ print(f"Ingested {result['documents']} documents")
+ print(f"Graph: {result['graph']['node_count']} nodes, {result['graph']['edge_count']} edges")
+ if result["errors"]:
+ print("Errors:", result["errors"])
+```
+
+## Domain Examples
+
+<Tabs>
+ <Tab title="Defense — CTI/Threat">
+ A joint intelligence cell fuses three live sources every six hours: NVD CVE RSS, classified PDF drops from a partner agency, and an internal MISP instance.
+
+```python
+from semantica.ingest import ingest_file, ingest_feed, RESTIngestor
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+graph = ContextGraph(advanced_analytics=True, community_detection=True)
+context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ graph_expansion = True,
+)
+
+# NVD CVE feed — new CVEs in last 6 hours
+nvd_feed = ingest_feed(
+ "https://nvd.nist.gov/feeds/xml/cve/misc/nvd-rss.xml",
+ method="rss",
+)
+nvd_texts = [f"{item.title}: {item.description}" for item in nvd_feed.items]
+
+# Classified PDF drop from partner agency
+partner_docs = ingest_file("//partner-share/intel-drops/", method="directory")
+partner_texts = [doc.text for doc in partner_docs]
+
+# MISP events tagged TLP:AMBER or higher
+ingestor = RESTIngestor()
+misp_data = ingestor.paginated_fetch(
+ "https://misp.internal/events/restSearch",
+ headers={"Authorization": "YOUR_MISP_API_KEY"},
+ params={"tags": "tlp:amber||tlp:red", "threat_level_id": "1"},
+ page_size=100,
+)
+misp_texts = [
+ f"MISP {e['Event']['id']}: {e['Event'].get('info', '')}"
+ for page in misp_data
+ for e in page.data
+]
+
+# Fuse all three into the graph
+context.store(
+ nvd_texts + partner_texts + misp_texts,
+ extract_entities=True, extract_relationships=True,
+)
+print(f"Fused graph: {graph.stats()['node_count']} nodes")
+```
+
+ </Tab>
+
+ <Tab title="Security — SOC/Incident">
+ During an active incident the SOC enriches the timeline on a 15-minute cycle from three sources: SIEM alert CSV exports, an EDR REST API, and the internal CVE database.
+
+```python
+from semantica.ingest import ingest_file, RESTIngestor, DBIngestor
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+)
+
+# SIEM alert CSV exports (written by SIEM every 15 minutes)
+alert_files = ingest_file("./siem_exports/", method="directory")
+alert_texts = [
+ f.text for f in alert_files if f.file_type == "csv"
+]
+
+# EDR platform REST API — host telemetry for the affected segment
+ingestor = RESTIngestor()
+edr_data = ingestor.ingest_endpoint(
+ "https://edr.internal/api/v1/telemetry",
+ headers={"X-API-Key": "EDR_KEY"},
+ params={"segment": "finance", "severity": "high", "limit": 500},
+)
+edr_texts = [
+ f"Host {e.get('hostname')}: {e.get('event_type')} — {e.get('description')}"
+ for e in edr_data.data
+]
+
+# CVE cross-reference for any CVE IDs observed in alerts
+db = DBIngestor()
+exploited_cves = db.execute_query(
+ "postgresql://readonly:[email protected]:5432/nvd",
+ "SELECT cve_id, description, cvss_v3_score FROM cve_records "
+ "WHERE cve_id = ANY(ARRAY['CVE-2024-3400', 'CVE-2024-21762'])",
+)
+cve_texts = [f"{r['cve_id']} (CVSS {r['cvss_v3_score']}): {r['description']}"
+ for r in exploited_cves]
+
+context.store(
+ alert_texts + edr_texts + cve_texts,
+ extract_entities=True, extract_relationships=True,
+)
+print(f"Incident graph: {graph.stats()['node_count']} nodes enriched")
+```
+
+ </Tab>
+
+ <Tab title="Life Science — Clinical/Pharma">
+ A pharmacovigilance platform ingests three data sources after each trial phase closes: FDA submission PDFs, a PostgreSQL clinical trials database, and PubMed literature via web scraping.
+
+```python
+from semantica.ingest import ingest_file, ingest_web, DBIngestor
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ retention_days = None, # regulatory data — unlimited retention
+)
+
+# FDA submissions for Phase III oncology trials
+submissions = ingest_file("./fda_submissions/phase3_oncology/", method="directory")
+sub_texts = [s.text for s in submissions]
+
+# Clinical trials database — protocol and AE records
+db = DBIngestor()
+trial_records = db.execute_query(
+ "postgresql://readonly:[email protected]:5432/trials",
+ """
+ SELECT t.protocol_id, t.title, t.primary_endpoint,
+ ae.event_type, ae.severity, ae.frequency_pct
+ FROM clinical_trials t
+ JOIN adverse_events ae ON t.protocol_id = ae.protocol_id
+ WHERE t.phase = 'III' AND t.therapeutic_area = 'oncology'
+ ORDER BY ae.severity DESC
+ """,
+)
+trial_texts = [
+ f"Protocol {r['protocol_id']}: {r['title']} "
+ f"AE: {r['event_type']} (severity={r['severity']}, freq={r['frequency_pct']}%)"
+ for r in trial_records
+]
+
+# PubMed literature for the drug compound
+pubmed_pages = ingest_web(
+ "https://pubmed.ncbi.nlm.nih.gov/?term=dapagliflozin+cardiovascular",
+ method="url",
+)
+pub_texts = [pubmed_pages.text]
+
+context.store(
+ sub_texts + trial_texts + pub_texts,
+ extract_entities=True, extract_relationships=True,
+)
+print(f"Pharmacovigilance graph: {graph.stats()['node_count']} nodes")
+```
+
+ </Tab>
+
+ <Tab title="Banking — Risk/Compliance">
+ A compliance team pulls from three sources each quarter: BIS and Basel publications (web sitemap crawl), internal policy PDFs, and a regulatory rules database.
+
+```python
+from semantica.ingest import ingest_file, ingest_web, DBIngestor
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ retention_days = 2555, # 7-year regulatory retention requirement
+)
+
+# BIS/Basel publications via sitemap crawl — filter to capital/liquidity pages
+bis_pages = ingest_web("https://www.bis.org/sitemap.xml", method="sitemap")
+basel_pages = [p for p in bis_pages if any(
+ kw in p.url.lower() for kw in ["bcbs", "capital", "liquidity", "leverage"]
+)]
+bis_texts = [p.text for p in basel_pages]
+print(f"BIS pages matched: {len(bis_texts)}")
+
+# Internal policy library
+policies = ingest_file("./regulatory_library/", method="directory", recursive=True)
+policy_texts = [p.text for p in policies]
+
+# Regulatory rules database — active rules only
+db = DBIngestor()
+rules = db.execute_query(
+ "postgresql://compliance_ro:[email protected]:5432/compliance",
+ """
+ SELECT rule_id, title, requirement_text, effective_date, jurisdiction
+ FROM regulations
+ WHERE active = true AND jurisdiction IN ('EU', 'US', 'UK')
+ ORDER BY effective_date DESC
+ """,
+)
+rule_texts = [
+ f"{r['rule_id']} [{r['jurisdiction']}] {r['title']}: {r['requirement_text']}"
+ for r in rules
+]
+
+context.store(
+ bis_texts + policy_texts + rule_texts,
+ extract_entities=True, extract_relationships=True,
+)
+print(f"Compliance graph: {graph.stats()['node_count']} nodes, "
+ f"{graph.stats()['edge_count']} edges")
+```
+
+ </Tab>
+</Tabs>
+
+## Related Guides
+
+- [Pipeline](pipeline) — chain ingest steps with `PipelineBuilder` for automated, retryable, parallelised workflows
+- [Context Graphs](context-graphs) — storing and querying the entities you ingest as a typed property graph
+- [Semantic Extraction](semantic-extraction) — NER, relation extraction, and triplet extraction from ingested text
+- [Provenance](provenance) — tracking the origin document, confidence score, and ingestion timestamp for every extracted entity
diff --git a/docs/guides/llm-integrations.md b/docs/guides/llm-integrations.md
new file mode 100644
index 00000000..b49d21ec
--- /dev/null
+++ b/docs/guides/llm-integrations.md
@@ -0,0 +1,526 @@
+---
+title: "LLM Integrations"
+description: "Connect Semantica to Groq, OpenAI, Anthropic, HuggingFace, Novita AI, and 100+ LLM providers through a unified interface."
+---
+
+Semantica exposes a unified provider interface — a single `.generate()` method — across Groq, OpenAI, Anthropic Claude, HuggingFace, Novita AI, and 100+ providers via LiteLLM. Use it when you need to swap providers for latency, accuracy, cost, or data-residency reasons without touching application code.
+
+<Info>
+ The providers in `semantica.llms` (`Groq`, `OpenAI`, `LiteLLM`, `HuggingFaceLLM`) are for text generation and `query_with_reasoning()`. For structured entity and relation extraction, `semantica.semantic_extract` accepts provider names as strings. Both patterns are covered here.
+</Info>
+
+## Choosing a Provider
+
+Four factors drive provider selection. **Latency** matters most in real-time SOC triage loops where an analyst is waiting on a triage verdict — Groq's inference server typically returns 8B model responses in under 300ms. **Accuracy** matters most in high-stakes decisions: clinical contraindication checks, credit committee reasoning, and legal document analysis reward the frontier models available via `LiteLLM`. **Data residency** constraints eliminate cloud providers for classified or HIPAA-regulated workloads — `HuggingFaceLLM` with a local model path covers those cases. **Cost at scale** favors high-throughput open-model providers like Novita AI for bulk extraction pipelines where you are processing thousands of documents per hour.
+
+The good news: because Semantica's interface is identical across providers, you can prototype with Groq for speed, validate accuracy with Claude, and deploy to Azure OpenAI for compliance — without changing a single line of your application code. Only the provider constructor changes.
+
+## The Shared Interface
+
+Every provider exposes the same two methods:
+
+```python
+provider.generate(prompt: str, **kwargs) -> str
+provider.generate_structured(prompt: str, **kwargs) -> dict
+provider.is_available() -> bool
+```
+
+`generate()` returns a plain string. `generate_structured()` instructs the model to respond in JSON and returns a parsed `dict`. `is_available()` lets you health-check the provider before committing to a call — useful in retry logic and warm-up checks.
+
+This means every place in Semantica that accepts an LLM — `query_with_reasoning()`, semantic extraction, custom reasoning loops — accepts any of these providers interchangeably.
+
+## Groq — Fast Inference for Real-Time Agents
+
+Groq Cloud runs open models on purpose-built Language Processing Units that deliver sub-300ms latency for 8B parameter models. This makes Groq the right default for any agent loop where the LLM is in the hot path — SOC triage, real-time alert classification, conversational agents.
+
+```python
+from semantica.llms import Groq
+
+# api_key falls back to the GROQ_API_KEY environment variable
+groq = Groq(model="llama-3.1-8b-instant", api_key="YOUR_GROQ_KEY")
+
+# Always health-check before the first call in a long-running process
+if not groq.is_available():
+ raise RuntimeError("Groq provider unreachable — check GROQ_API_KEY")
+
+# Plain generation
+verdict = groq.generate(
+ "Alert: 4200 LDAP objects enumerated in 8s from ws-finance-03. "
+ "True positive or false positive? One sentence.",
+ temperature=0.1, # low temperature for deterministic triage verdicts
+)
+print(verdict)
+# "True positive — volume and speed are consistent with T1087.002 domain enumeration."
+
+# Structured extraction — returns a parsed dict
+entities = groq.generate_structured(
+ "Extract threat actors and CVEs from: "
+ "APT29 exploited CVE-2024-3400 in PAN-OS GlobalProtect."
+)
+# {"threat_actors": ["APT29"], "cves": ["CVE-2024-3400"], "products": ["PAN-OS GlobalProtect"]}
+```
+
+Groq model selection comes down to the speed-vs-capability tradeoff: `llama-3.1-8b-instant` for anything in the hot path, `llama-3.3-70b-versatile` when you need stronger reasoning but can afford slightly higher latency, `mixtral-8x7b-32768` for long-context summarisation tasks.
+
+## OpenAI — Function Calling and Vision
+
+The `OpenAI` provider wraps the OpenAI API. Use it when you need GPT-4o's function-calling precision, vision capabilities for document screenshots, or when your team already has an OpenAI contract and wants to stay there.
+
+```python
+from semantica.llms import OpenAI
+
+oai = OpenAI(model="gpt-4o", api_key="YOUR_OAI_KEY")
+# api_key falls back to OPENAI_API_KEY environment variable
+
+response = oai.generate(
+ "Under CRR2 Article 92, what is the minimum total capital ratio "
+ "for a G-SIB subject to a 2% GSIB buffer surcharge?"
+)
+print(response)
+
+# Structured output — useful for deterministic data extraction
+risk_data = oai.generate_structured(
+ "Extract all counterparty names and exposure amounts from: "
+ "Counterparty A: 45M EUR notional, Counterparty B: 12M EUR notional, "
+ "Counterparty C: 89M EUR notional."
+)
+# {"counterparties": [{"name": "Counterparty A", "exposure_eur": 45000000}, ...]}
+```
+
+The default model `gpt-3.5-turbo` is fine for classification and light extraction. Switch to `gpt-4o` for complex multi-step regulatory reasoning or document understanding.
+
+## LiteLLM — One Interface, 100+ Providers
+
+`LiteLLM` is the Swiss Army knife. It wraps the `litellm` library, which speaks to every major provider using a unified completion API. The model string encodes both provider and model name: `"anthropic/claude-sonnet-4-20250514"`, `"azure/gpt-4o"`, `"bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0"`, `"ollama/llama3.2"`. Change the string, change the provider — no other code changes needed.
+
+```python
+from semantica.llms import LiteLLM
+
+# Anthropic Claude — highest accuracy for complex reasoning
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+# Reads ANTHROPIC_API_KEY from environment
+
+# Azure OpenAI — compliance and data-residency requirements
+llm = LiteLLM(model="azure/gpt-4o", api_key="YOUR_AZURE_KEY")
+
+# AWS Bedrock — existing cloud agreement, no new vendor
+llm = LiteLLM(model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0")
+
+# Google Vertex AI
+llm = LiteLLM(model="vertex_ai/gemini-1.5-pro")
+
+# Ollama — fully local, no network calls
+llm = LiteLLM(model="ollama/llama3.2")
+
+# All of them: same call
+response = llm.generate("Summarise the ICH E6(R2) GCP guideline key requirements.")
+```
+
+The environment-variable convention for each provider: `ANTHROPIC_API_KEY`, `AZURE_API_KEY`, `OPENAI_API_KEY`, `GOOGLE_APPLICATION_CREDENTIALS`, etc. LiteLLM picks them up automatically. For a provider switch driven by deployment environment, you can keep provider selection in a config dict and inject it at startup — no `if/else` branches in application code:
+
+```python
+import os
+
+PROVIDER_MAP = {
+ "prod": "anthropic/claude-sonnet-4-20250514",
+ "staging": "openai/gpt-4o-mini",
+ "local": "ollama/llama3.2",
+ "azure": "azure/gpt-4o",
+}
+
+env = os.getenv("DEPLOY_ENV", "local")
+llm = LiteLLM(model=PROVIDER_MAP[env])
+# The rest of the application never touches provider names
+```
+
+## HuggingFaceLLM — Air-Gapped and On-Premise
+
+`HuggingFaceLLM` loads a model from the HuggingFace Hub or from a local directory path. No network calls during inference. This is the only option for classified environments, HIPAA-constrained clinical deployments, and any network segment without outbound internet access.
+
+```python
+from semantica.llms import HuggingFaceLLM
+
+# HuggingFace Hub — authentication via HF_TOKEN environment variable
+hf = HuggingFaceLLM(model="mistralai/Mistral-7B-Instruct-v0.3")
+
+# Biomedical fine-tuned model for clinical entity extraction
+bio_llm = HuggingFaceLLM(model="aaditya/Llama3-OpenBioLLM-70B")
+
+# Air-gapped deployment — model on local NFS share or mounted volume
+# Both `model` and `model_name` are accepted as constructor parameters
+air_gapped_llm = HuggingFaceLLM(model="/opt/models/llama-3.1-70b-instruct")
+
+response = air_gapped_llm.generate(
+ "Summarise SIGINT collection window 2024-Q3 for APT29 C2 infrastructure.",
+ max_length=512,
+)
+```
+
+Set `HF_TOKEN` in your environment for Hub access to gated or private models. For local paths, no token is needed — the model directory must contain the standard HuggingFace checkpoint files.
+
+## Swapping Providers Without Changing Application Code
+
+The real payoff of the unified interface is in `query_with_reasoning()`. This is the call that drives graph-grounded reasoning in every `AgentContext`. Because it accepts any provider object, you can slot in a different LLM at any tier of your pipeline with zero changes to the surrounding code.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import Groq, LiteLLM
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(vector_store=vs, knowledge_graph=graph, graph_expansion=True)
+
+# Load your knowledge base once
+context.store(
+ [
+ {"content": "APT29 exploits CVE-2024-3400 in PAN-OS GlobalProtect — CVSS 10.0",
+ "metadata": {"source": "nvd", "actor": "APT29"}},
+ {"content": "NOBELIUM (APT29) leverages OAuth token theft against Azure AD tenants",
+ "metadata": {"source": "msft_blog_2023", "actor": "APT29", "technique": "T1528"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+query = "What is APT29's current exploitation methodology and what cloud services are targeted?"
+
+# Tier 1: fast answer with Groq (< 300ms)
+fast_llm = Groq(model="llama-3.1-8b-instant", api_key="YOUR_GROQ_KEY")
+fast_result = context.query_with_reasoning(query, llm_provider=fast_llm, max_results=5)
+print("FAST: {} (conf={:.0%})".format(fast_result["response"], fast_result["confidence"]))
+
+# Tier 2: deep answer with Claude if confidence is below threshold
+if fast_result["confidence"] < 0.85:
+ deep_llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+ deep_result = context.query_with_reasoning(
+ query, llm_provider=deep_llm, max_results=15, max_hops=3
+ )
+ print("DEEP: {} (conf={:.0%})".format(deep_result["response"], deep_result["confidence"]))
+```
+
+The `context`, the graph, the retrieval logic — none of it changes. Only the `llm_provider` argument differs between the two tiers.
+
+## Using Providers for Semantic Extraction
+
+For NER, relation extraction, and triplet extraction, Semantica's `semantica.semantic_extract` module accepts provider names as strings rather than class instances. The module handles provider instantiation internally.
+
+```python
+from semantica.semantic_extract import NamedEntityRecognizer, EventDetector
+from semantica.semantic_extract.methods import (
+ extract_entities_llm,
+ extract_relations_llm,
+ extract_triplets_llm,
+)
+
+# NER with Groq — provider name as a string
+ner = NamedEntityRecognizer(
+ methods=["llm"],
+ provider="groq",
+ llm_model="llama-3.1-8b-instant",
+)
+entities = ner.extract_entities(
+ "APT29 exploited CVE-2024-3400 in PAN-OS GlobalProtect to compromise NATO member networks."
+)
+for e in entities:
+ # Entity fields: .text, .label, .confidence
+ print("{} ({}) — conf={:.2f}".format(e.text, e.label, e.confidence))
+# APT29 (THREAT_ACTOR) — conf=0.96
+# CVE-2024-3400 (CVE) — conf=0.99
+# PAN-OS GlobalProtect (PRODUCT) — conf=0.94
+# NATO (ORGANIZATION) — conf=0.91
+
+# Event detection with the same provider pattern
+detector = EventDetector(method="llm", provider="groq")
+events = detector.detect_events(
+ "ENISA published the Threat Landscape 2024 report on October 22nd, "
+ "covering 11 primary threat categories including ransomware and supply-chain attacks."
+)
+
+# Triplet extraction — returns (subject, predicate, object) triples
+text = "Warfarin inhibits VKORC1 enzyme activity, reducing vitamin K-dependent clotting factor synthesis."
+triplets = extract_triplets_llm(text, provider="groq", model="llama-3.1-8b-instant")
+for t in triplets:
+ print("{} -> {} -> {}".format(t.subject, t.predicate, t.object))
+# warfarin -> inhibits -> VKORC1 enzyme activity
+# warfarin -> reduces -> vitamin K-dependent clotting factor synthesis
+```
+
+## Novita AI — Cost-Efficient Bulk Extraction
+
+Novita AI exposes an OpenAI-compatible API and is available as a built-in provider for the extraction layer. It is accessed differently from the `semantica.llms` classes — through `create_provider` from `semantica.semantic_extract.providers` — making it the right choice for high-volume NER pipelines where per-call cost matters.
+
+```python
+from semantica.semantic_extract.providers import create_provider
+from semantica.semantic_extract import NamedEntityRecognizer
+
+# create_provider pools instances — same key reuses the same object
+provider = create_provider(
+ "novita",
+ api_key="YOUR_NOVITA_KEY", # or set NOVITA_API_KEY env var
+ model="deepseek/deepseek-v3.2", # default model
+)
+
+if provider.is_available():
+ # Plain generation
+ response = provider.generate("Summarise the Basel III leverage ratio requirement.")
+
+ # Structured extraction — returns parsed dict
+ data = provider.generate_structured(
+ "Extract drug names and dosages from: "
+ "Patient received warfarin 5mg daily, aspirin 75mg daily, metformin 500mg twice daily."
+ )
+
+# Use Novita through the NER interface — provider name as string
+ner = NamedEntityRecognizer(
+ methods=["llm"],
+ provider="novita",
+ llm_model="deepseek/deepseek-v3.2",
+)
+entities = ner.extract_entities(
+ "CVE-2024-3400 is exploited by UNC3886 targeting PAN-OS GlobalProtect."
+)
+for e in entities:
+ print("{} ({}) — conf={:.2f}".format(e.text, e.label, e.confidence))
+```
+
+Novita requires the `openai` Python client under the hood — install with `pip install "semantica[llm-openai]"` or `pip install openai`.
+
+## Domain Examples
+
+<Tabs>
+<Tab title="Defense — CTI/Threat">
+A classified threat-intelligence analysis unit needs to run entirely air-gapped — no outbound network traffic of any kind. The extraction model and the reasoning model both load from a local NFS share. The knowledge graph accumulates over the analysis session; all inference happens on-premise.
+
+```python
+from semantica.llms import HuggingFaceLLM
+from semantica.semantic_extract import NamedEntityRecognizer
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+# Both models load from the air-gapped NFS share — no Hub calls
+extraction_llm = HuggingFaceLLM(model="/opt/models/mistral-7b-instruct")
+reasoning_llm = HuggingFaceLLM(model="/opt/models/llama-3.1-70b-instruct")
+
+# NER with local model — provider pattern still works for local paths
+# (use extract_entities_llm directly with the provider instance)
+from semantica.semantic_extract.methods import extract_entities_llm
+
+sigint_text = (
+ "[S//NF] APT29 operator observed deploying WARPWIRE credential harvester "
+ "via CVE-2024-3400 on perimeter VPN gateways of target BRAVO-7."
+)
+
+# For fully local models, call the provider's generate method directly
+raw_entities = extraction_llm.generate(
+ "Extract all threat actors, CVEs, malware names, and target identifiers "
+ "from the following text as a JSON list:\n\n" + sigint_text
+)
+
+# Build the graph and run reasoning
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ decision_tracking=True,
+)
+
+context.store(
+ sigint_text,
+ metadata={"source": "SIGINT_Q4_2024", "classification": "SECRET//NOFORN"},
+ conversation_id="op-analysis-q4",
+)
+
+result = context.query_with_reasoning(
+ "What credential-harvesting capabilities has APT29 deployed against "
+ "perimeter VPN gateways and what CVEs enable initial access?",
+ llm_provider=reasoning_llm, # fully local — no network calls
+ max_results=10,
+ max_hops=3,
+)
+print(result["response"])
+print("Confidence: {:.0%}".format(result["confidence"]))
+
+context.save("./classified_output/q4_analysis/")
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+A SOC pipeline uses two providers at different tiers: Groq for sub-500ms initial triage that keeps the analyst in flow, and Anthropic Claude for deep ATT&CK analysis when Tier 1 confidence falls below the escalation threshold. The provider switch is determined programmatically — no manual handoff required.
+
+```python
+from semantica.llms import Groq, LiteLLM
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+context = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ decision_tracking=True,
+)
+
+# Preload MITRE ATT&CK runbook knowledge
+context.store([
+ "T1087.002 (Domain Account Discovery): anomalous LDAP enumeration — isolate source host, reset service account passwords",
+ "T1053.005 (Scheduled Task/Job): encoded PowerShell via wmiprvse.exe — collect task XML, check persistence keys, notify IR",
+ "T1021.002 (SMB/Windows Admin Shares): PsExec lateral movement to DC — immediate host isolation, reset service accounts",
+])
+
+alert = (
+ "SIEM Alert: host ws-finance-03, user jsmith — scheduled task with base64-encoded PowerShell. "
+ "Parent process: wmiprvse.exe. Sigma: T1053.005. Time: 2025-06-21T09:14:32Z."
+)
+context.store(alert, metadata={"type": "alert", "severity": "high"})
+
+# Tier 1: fast triage with Groq — target < 500ms end-to-end
+fast_llm = Groq(model="llama-3.1-8b-instant", api_key="YOUR_GROQ_KEY")
+triage = context.query_with_reasoning(
+ "Is this alert a true positive? One sentence verdict and confidence.",
+ llm_provider=fast_llm,
+ max_results=5,
+)
+print("TRIAGE: {} (conf={:.0%})".format(triage["response"], triage["confidence"]))
+
+# Tier 2: escalate to Claude for deep analysis if Tier 1 is uncertain
+if triage["confidence"] < 0.88:
+ deep_llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+ deep = context.query_with_reasoning(
+ "Full MITRE ATT&CK analysis of this alert: identify the attack chain, "
+ "blast radius, affected systems, and recommended containment steps.",
+ llm_provider=deep_llm,
+ max_results=15,
+ max_hops=3,
+ )
+ print("DEEP ANALYSIS: {}".format(deep["response"]))
+
+ context.record_decision(
+ category="escalation",
+ scenario="Scheduled task T1053.005 on ws-finance-03 — Tier 1 conf {:.0%}".format(triage["confidence"]),
+ reasoning=deep["reasoning_path"],
+ outcome="escalated_tier2",
+ confidence=deep["confidence"],
+ entities=["ws-finance-03", "jsmith", "T1053.005"],
+ decision_maker="soc_pipeline_v3",
+ )
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+A clinical NLP pipeline uses a domain-specific biomedical NER model from HuggingFace for entity extraction, then switches to Anthropic Claude for structured oncology report synthesis. The same `LiteLLM` wrapper handles the Claude call — switching to Azure OpenAI for HIPAA compliance is a one-line change.
+
+```python
+from semantica.llms import LiteLLM
+from semantica.semantic_extract import NamedEntityRecognizer
+
+# Biomedical NER — HuggingFace extractor for clinical entities
+# (Note: HuggingFace NER uses method="huggingface", not the LLM generation interface)
+ner = NamedEntityRecognizer(
+ methods=["huggingface"],
+ huggingface_model="d4data/biomedical-ner-all",
+ confidence_threshold=0.75,
+)
+
+clinical_note = (
+ "Patient presents with HER2+ breast cancer (T2N1M0, Stage IIB). "
+ "Recommended: trastuzumab 8mg/kg loading then 6mg/kg q3w + pertuzumab 840mg loading "
+ "then 420mg q3w + docetaxel 75mg/m2 q3w (THP regimen) for 6 cycles. "
+ "eGFR 78 mL/min/1.73m2, LVEF 62%. Monitor for cardiotoxicity."
+)
+
+entities = ner.extract_entities(clinical_note)
+# Entity fields: .text, .label (not .type), .confidence
+drugs = [e for e in entities if e.label == "DRUG"]
+diagnoses = [e for e in entities if e.label in ("DISEASE", "CANCER")]
+
+print("Drugs identified:")
+for d in drugs:
+ print(" {} (conf={:.2f})".format(d.text, d.confidence))
+# trastuzumab (conf=0.98), pertuzumab (conf=0.97), docetaxel (conf=0.96)
+
+# Report synthesis with Claude — switch to azure/gpt-4o for HIPAA by changing one string
+report_llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+# For HIPAA-constrained Azure deployment:
+# report_llm = LiteLLM(model="azure/gpt-4o", api_key="YOUR_AZURE_KEY")
+
+oncology_summary = report_llm.generate(
+ "Write a structured oncology treatment summary for the following note. "
+ "Include: diagnosis, staging, treatment regimen, monitoring parameters, "
+ "and key safety considerations.\n\n" + clinical_note
+)
+print(oncology_summary)
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+A regulatory Q&A system runs the same Basel III question through two providers and picks the answer with higher confidence — a simple consensus pattern for high-stakes regulatory interpretation where a wrong answer carries legal risk.
+
+```python
+from semantica.llms import OpenAI, LiteLLM
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph(advanced_analytics=True)
+context = AgentContext(
+ vector_store=vs,
+ knowledge_graph=graph,
+ graph_expansion=True,
+ retention_days=2555,
+)
+
+# Load Basel III / CRR2 regulatory corpus
+context.store(
+ [
+ {"content": "CRR2 Art. 92: minimum total capital ratio 8% + 2.5% conservation buffer + GSIB surcharge",
+ "metadata": {"source": "CRR2_Art92", "category": "capital_requirement"}},
+ {"content": "Basel III leverage ratio: Tier 1 capital / total exposure >= 3% (Art. 429 CRR2)",
+ "metadata": {"source": "CRR2_Art429", "category": "leverage"}},
+ {"content": "GSIB buffer surcharges: bucket 1=1%, bucket 2=1.5%, bucket 3=2%, bucket 4=2.5%, bucket 5=3.5%",
+ "metadata": {"source": "BCBS_GSIB_2022", "category": "gsib_buffer"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+question = (
+ "Under CRR2 Article 92 and the BCBS GSIB framework, what is the minimum "
+ "total capital ratio for a bucket-2 G-SIB? Show the component breakdown."
+)
+
+# Two-provider consensus — same query, same graph, different LLMs
+gpt4o = OpenAI(model="gpt-4o", api_key="YOUR_OAI_KEY")
+claude = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+
+answer_a = context.query_with_reasoning(question, llm_provider=gpt4o, max_results=10)
+answer_b = context.query_with_reasoning(question, llm_provider=claude, max_results=10)
+
+# Pick higher-confidence answer for the audit trail
+best = answer_a if answer_a["confidence"] >= answer_b["confidence"] else answer_b
+winner = "GPT-4o" if best is answer_a else "Claude"
+
+print("Selected: {} (conf={:.0%})".format(winner, best["confidence"]))
+print(best["response"])
+# Expected: 8% (minimum) + 2.5% (conservation) + 1.5% (bucket-2 GSIB) = 12.0% total
+
+# Sources the answer is grounded in
+for src in best["sources"]:
+ print(" - [{}] {}".format(src.get("metadata", {}).get("source", "?"), src["content"][:60]))
+```
+
+</Tab>
+</Tabs>
+
+## Related Guides
+
+- [Agent Memory](agent-memory) — using `query_with_reasoning()` with any LLM provider for graph-grounded retrieval
+- [Multi-Agent Systems](multi-agent) — wiring different LLM providers to different agent tiers in a shared-graph pipeline
+- [Semantic Extraction](semantic-extraction) — LLM-powered NER, relation extraction, event detection, and triplet extraction
+- [GraphRAG](graphrag) — multi-hop graph reasoning with `query_with_reasoning()`
diff --git a/docs/guides/mcp-server.md b/docs/guides/mcp-server.md
new file mode 100644
index 00000000..e72ddb24
--- /dev/null
+++ b/docs/guides/mcp-server.md
@@ -0,0 +1,273 @@
+---
+title: "MCP Server"
+description: "Connect Semantica's knowledge graph, decision intelligence, and reasoning to Claude Desktop, Windsurf, VS Code, Cline, and any MCP-compatible AI client."
+icon: "plug"
+---
+
+The Semantica MCP server exposes your knowledge graph as 12 callable tools so any compatible AI client — Claude Desktop, Windsurf, VS Code extensions — can traverse the graph live, record decisions, run analytics, and export results during a conversation. Use it to give LLM agents direct, real-time access to graph data without writing custom tool wrappers.
+
+<Info>
+ The Semantica MCP server exposes 12 tools and 3 read-only resources. All tools accept and return JSON. No configuration beyond an optional environment variable for graph persistence is required.
+</Info>
+
+## Starting the Server
+
+Install Semantica, then launch the MCP server. It starts in stdio mode by default — the protocol used by Claude Desktop, Windsurf, VS Code extensions, and most MCP clients.
+
+```bash
+pip install semantica
+```
+
+```bash
+# Via the CLI entry-point (recommended)
+semantica-mcp
+
+# Or via the Python module directly
+python -m semantica.mcp_server
+```
+
+Startup info prints to stderr. Without `SEMANTICA_KG_PATH` the server initialises an empty in-memory graph — sufficient for testing. For a persistent graph that survives restarts, set the path:
+
+```bash
+SEMANTICA_KG_PATH=/data/threat_graph.json semantica-mcp
+```
+
+<Info>
+ Without `SEMANTICA_KG_PATH`, the graph resets when the server process exits. Always set this path for any session whose data should survive a restart.
+</Info>
+
+## Connecting to Claude Desktop
+
+Edit the Claude Desktop config file — on macOS at `~/Library/Application Support/Claude/claude_desktop_config.json`, on Windows at `%APPDATA%\Claude\claude_desktop_config.json`:
+
+```json
+{
+ "mcpServers": {
+ "semantica": {
+ "command": "semantica-mcp",
+ "env": {
+ "SEMANTICA_KG_PATH": "/path/to/knowledge_graph.json",
+ "SEMANTICA_LOG_LEVEL": "INFO"
+ }
+ }
+ }
+}
+```
+
+Restart Claude Desktop after saving. The Semantica tools appear in the tool palette automatically — Claude can now call them during any conversation.
+
+If `semantica-mcp` is not on your system PATH (for example, if it is installed in a virtualenv), use the full binary path in `"command"`: `"/path/to/venv/bin/semantica-mcp"`.
+
+## Connecting to Other Clients
+
+**Windsurf** — in Settings → MCP Servers → Add Server, or edit `~/.windsurf/mcp_servers.json`:
+
+```json
+{
+ "semantica": {
+ "command": "semantica-mcp",
+ "env": { "SEMANTICA_KG_PATH": "/path/to/knowledge_graph.json" }
+ }
+}
+```
+
+**VS Code (Cline / Roo Code / Continue)** — add to `.mcp.json` in your project root:
+
+```json
+{
+ "servers": {
+ "semantica": {
+ "type": "stdio",
+ "command": "semantica-mcp",
+ "env": {
+ "SEMANTICA_KG_PATH": "${workspaceFolder}/knowledge_graph.json",
+ "SEMANTICA_LOG_LEVEL": "DEBUG"
+ }
+ }
+ }
+}
+```
+
+**Docker**:
+
+```bash
+docker run --rm -i \
+ -e SEMANTICA_KG_PATH=/data/kg.json \
+ -v /local/path:/data \
+ ghcr.io/semantica-agi/semantica-mcp:latest
+```
+
+## What the Agent Can Do: The 12 Tools
+
+Once connected, the LLM can call any of these tools during a conversation. The agent chains them automatically — you do not orchestrate the sequence, you just describe what you want.
+
+**Entity and relation extraction** — `extract_entities` pulls named entities from free text; `extract_relations` extracts semantic relationships and RDF triplets. These two tools turn a raw OSINT report into structured graph inputs without any preprocessing.
+
+**Knowledge graph manipulation** — `add_entity` adds a node, `add_relationship` adds a directed edge. After extraction, the agent calls these to persist what it found into the live graph.
+
+**Decision intelligence** — `record_decision` writes a decision as a provenance node with confidence score, reasoning, and decision maker identity. `query_decisions` retrieves past decisions by query or category. `find_precedents` finds the most similar past decisions by semantic similarity. `get_causal_chain` traces decision causality upstream or downstream.
+
+**Reasoning** — `run_reasoning` applies forward-chaining IF/THEN rules over a set of facts and returns derived conclusions.
+
+**Analytics and export** — `get_graph_analytics` computes PageRank centrality and community detection. `get_graph_summary` returns node count, decision count, and server status. `export_graph` serializes the current graph to Turtle, JSON-LD, N-Triples, or plain JSON.
+
+## Watching a Real Agent Session
+
+Here is what happens when an analyst types a prompt into Claude Desktop and the graph is live. The prompt is:
+
+> "Extract entities and relationships from this OSINT report, add them to the knowledge graph, then record an attribution decision for APT29 with confidence 0.88 and export the full graph as Turtle."
+
+Claude chains five tool calls automatically:
+
+```text
+1. extract_entities(text="<report text>")
+ → { "entities": [{"label": "APT29", "type": "ThreatActor"}, ...] }
+
+2. extract_relations(text="<report text>")
+ → { "relations": [{"source": "APT29", "type": "EXPLOITS", "target": "CVE-2024-3400"}] }
+
+3. add_entity(id="apt29", label="APT29", type="ThreatActor", metadata={"alias": "NOBELIUM"})
+ → { "status": "added", "id": "apt29" }
+ (repeated for each extracted entity)
+
+4. add_relationship(source="apt29", target="cve-2024-3400", type="EXPLOITS",
+ metadata={"confidence": 0.97})
+ → { "status": "added" }
+ (repeated for each extracted relation)
+
+5. record_decision(
+ category="threat_attribution",
+ scenario="C2 beacon from 185.220.101.47, TTP T1566.001 observed",
+ reasoning="IP overlaps APT29 infrastructure cluster; TTPs match NOBELIUM phishing playbook",
+ outcome="attributed_to_apt29",
+ confidence=0.88,
+ decision_maker="analyst_zhang"
+ )
+ → { "decision_id": "dec_a3f2b1", "status": "recorded" }
+
+6. export_graph(format="turtle")
+ → { "format": "turtle", "data": "@prefix ... <apt29> a :ThreatActor ..." }
+```
+
+The analyst asked one question in natural language. Six structured tool calls happened against live graph data. The result is a populated graph, a recorded attribution decision with full provenance, and a Turtle export ready for the SPARQL endpoint — all in a single conversation turn.
+
+## The Three Read-Only Resources
+
+Resources expose graph state without a tool call — the client can read them at any point:
+
+| URI | Description |
+| :-- | :---------- |
+| `semantica://graph/summary` | Node count, edge count, server status |
+| `semantica://decisions/list` | Up to 50 most recent recorded decisions |
+| `semantica://schema/info` | Server version, capabilities, available tool list |
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+The CTI team uses Claude Desktop to correlate new OSINT reports against the existing threat graph, record attribution decisions, and query causal chains — all through natural language, with the graph updated live.
+
+**Analyst prompt:**
+> "Extract entities from this Mandiant report on APT40, add them to the knowledge graph, find any past decisions about APT40 attribution, and record a new attribution decision with confidence 0.84."
+
+Claude chains automatically:
+
+1. `extract_entities` + `extract_relations` on the report text
+2. `add_entity` for each extracted entity (APT40, CVEs, infrastructure nodes)
+3. `add_relationship` for each extracted relation
+4. `query_decisions(query="APT40 attribution", category="threat_attribution")`
+5. `find_precedents(scenario="APT40 targeting maritime sector", max_results=3)`
+6. `record_decision(category="threat_attribution", outcome="attributed_to_apt40", confidence=0.84, decision_maker="analyst_zhang")`
+
+The attribution is now a graph node linked to the OSINT evidence, searchable by future agents.
+
+```json
+{
+ "category": "threat_attribution",
+ "scenario": "C2 infrastructure overlaps APT40 cluster; TEMP.Periscope TTPs confirmed",
+ "reasoning": "Three C2 IPs match known APT40 hosting ASN; T1190 exploit chain identical to 2023 campaign",
+ "outcome": "attributed_to_apt40",
+ "confidence": 0.84,
+ "decision_maker": "analyst_zhang"
+}
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+During a live incident, the SOC uses Claude to reason over the graph, apply zero-trust policy rules, and record containment decisions with their causal chain — creating a real-time audit trail.
+
+**SOC analyst prompt:**
+> "Add WKSTN-047 and DC01 as hosts, add the lateral movement relationship between them, run reasoning to classify the severity, and record a containment decision."
+
+Claude chains:
+
+1. `add_entity(id="wkstn-047", type="Host", label="WKSTN-047")`
+2. `add_entity(id="dc01", type="Host", label="DC01")`
+3. `add_relationship(source="wkstn-047", target="dc01", type="lateral_movement")`
+4. `run_reasoning(facts=["Host(WKSTN-047)", "LateralMove(WKSTN-047, DC01)", "DC(DC01)"], rules=["IF LateralMove(X, Y) AND DC(Y) THEN CriticalIncident(X)"])`
+5. `record_decision(category="containment", scenario="Lateral movement to DC detected", outcome="isolate_wkstn047", confidence=0.95)`
+6. `get_causal_chain(decision_id="...", direction="downstream", max_depth=3)`
+
+The containment decision and its downstream effects are captured in the graph for the post-mortem.
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+Clinical AI assistants use the MCP server to record treatment decisions with provenance, retrieve guideline precedents, and export decision graphs for regulatory submission and MDT review.
+
+**Clinical prompt:**
+> "The patient has eGFR 28 and is on metformin. Find precedents for metformin dose modification with severely reduced kidney function, then record a treatment modification decision."
+
+Claude calls:
+
+1. `find_precedents(scenario="metformin with eGFR below 30", max_results=5)`
+2. `record_decision(category="treatment_modification", scenario="eGFR 28, current metformin 1000mg BD", reasoning="eGFR 28 is below the 30 mL/min/1.73m2 absolute contraindication threshold per BNF and NICE NG28", outcome="discontinue_metformin_switch_to_gliclazide", confidence=0.97, decision_maker="clinical_ai_v2")`
+3. `get_causal_chain(direction="upstream")` — surfaces the guideline node that drove the decision
+4. `export_graph(format="json-ld")` — produces the decision graph for MDT review
+
+The graph captures the decision, its guideline basis, and the causal chain — all retrievable for regulatory audit.
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+Credit risk teams use the MCP server to record every lending decision with its reasoning chain, surface regulatory precedents, and export compliance graphs for Basel III model governance review.
+
+**Credit analyst prompt:**
+> "Record a conditional mortgage approval for APP-2025-994421 (LTV 78%, DSTI 38%, credit score 714), find the three most similar past approvals, and return the causal chain for this decision."
+
+Claude calls:
+
+1. `record_decision(category="mortgage_origination", scenario="LTV 78%, DSTI 38%, credit score 714, first-time buyer", reasoning="LTV within 80% cap; DSTI 38% under stressed rate scenario breaches 35% guideline — conditional approval with LMI requirement", outcome="approved_conditional_lmi", confidence=0.89, decision_maker="credit_model_v3")`
+2. `find_precedents(scenario="mortgage approval borderline DSTI stress test", max_results=3)`
+3. `get_causal_chain(decision_id="...", direction="upstream", max_depth=5)`
+4. `export_graph(format="turtle")` — produces the decision provenance graph for model governance committee
+
+The result is a fully auditable credit decision trail with precedent links, ready for SR 11-7 model risk governance review.
+
+</Tab>
+
+</Tabs>
+
+## Troubleshooting
+
+**Server does not appear in Claude Desktop** — fully quit and reopen Claude Desktop after editing the config (close the window is not enough). Verify the binary is on PATH: `which semantica-mcp` on Unix, `where semantica-mcp` on Windows. If using a virtualenv, use the absolute binary path in `"command"`. Set `SEMANTICA_LOG_LEVEL=DEBUG` and check stderr for startup errors.
+
+**Graph data not persisting between sessions** — set `SEMANTICA_KG_PATH` to an absolute file path. Without it the graph is in-memory only and resets on every server restart.
+
+**Tool calls returning empty results** — `get_graph_summary` returning `"node_count": 0` means the graph is empty. Populate it via `add_entity` and `add_relationship`, or run `extract_entities` on text first and then `add_entity` for each result.
+
+**Permission errors on `SEMANTICA_KG_PATH`** — the server process needs read/write access to the file and its parent directory. If running inside Docker, verify the volume mount and file ownership.
+
+## Related Guides
+
+- [Reasoning & Rules](reasoning) — the engine behind the `run_reasoning` tool
+- [Decision Intelligence](decision-intelligence) — how decisions are stored as causal graph nodes
+- [Context Graphs](context-graphs) — the graph that `add_entity` and `add_relationship` write to
+- [Export & Serialization](export) — all export formats available via `export_graph`
+- [Ontology Management](ontology) — generate OWL ontologies from the graph built via MCP
diff --git a/docs/guides/multi-agent.md b/docs/guides/multi-agent.md
new file mode 100644
index 00000000..a471d125
--- /dev/null
+++ b/docs/guides/multi-agent.md
@@ -0,0 +1,613 @@
+---
+title: "Multi-Agent Systems"
+description: "Coordinate multiple AI agents through shared memory, knowledge graphs, and decision history — without a message broker."
+---
+
+Semantica coordinates multiple agents through a shared `ContextGraph` — agents read and write to the same graph, or hand off serialized state via `save()` and `load()`, with no message broker required. Use this pattern when splitting work across ingestion, enrichment, reasoning, and reporting roles that must share a single evidence base.
+
+<Info>
+ This guide covers multi-agent coordination. For the memory layer each agent uses internally, see [Agent Memory](agent-memory). For graph traversal and entity linking, see [Context Graphs](context-graphs). For decision recording and precedent matching, see [Decision Intelligence](decision-intelligence).
+</Info>
+
+## The Three Coordination Patterns
+
+Before writing any code, choose the right coordination pattern for your pipeline.
+
+**Shared graph** works when all agents run in the same process. They hold references to the same `ContextGraph` object — thread-safe by default — so every `store()` from one agent is immediately visible to every `retrieve()` from another. This is the lowest-latency option and the right default for in-process pipelines.
+
+**Save / load handoff** works when agents run in different processes, on different machines, or at different times. Agent A finishes its work, calls `context.save(path)`, and Agent B calls `context.load(path)` to pick up exactly where A left off — full memory, full graph, full vector index. This is how you implement shift handoffs, async pipelines, and cross-service orchestration.
+
+**Namespaced memories** works when you have a single `AgentContext` instance serving multiple logical agents, each scoping its reads and writes with a `conversation_id`. Agents are isolated by tag, not by instance — useful for lightweight role separation without the overhead of multiple contexts.
+
+The pipeline in this guide uses all three.
+
+## Pattern 1 — Shared Graph for Concurrent Ingestion
+
+The OSINT collector and the enrichment agent run concurrently. They share a single `ContextGraph` and a single `VectorStore` — the graph's internal `RLock` makes concurrent writes safe.
+
+```python
+import threading
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+# One graph, one vector store — both agents write to these
+shared_graph = ContextGraph(advanced_analytics=True)
+shared_vs = VectorStore(backend="faiss", dimension=768)
+
+def make_agent() -> AgentContext:
+ """Factory: each agent gets its own AgentContext wrapping the shared backing stores."""
+ return AgentContext(
+ vector_store=shared_vs, # same VectorStore instance
+ knowledge_graph=shared_graph, # same ContextGraph instance
+ graph_expansion=True,
+ max_expansion_hops=2,
+ decision_tracking=True,
+ )
+
+osint_agent = make_agent()
+enrichment_agent = make_agent()
+reasoning_agent = make_agent()
+```
+
+The OSINT collector's job is to ingest raw feeds and extract entities. It does not reason — it just ingests and lets the graph accumulate structure.
+
+```python
+def osint_collection():
+ """Agent 1: ingest raw threat feeds and CVE data."""
+ osint_agent.store(
+ [
+ {
+ "content": "APT29 exploits CVE-2024-3400 in PAN-OS GlobalProtect — unauthenticated RCE, CVSS 10.0",
+ "metadata": {"source": "nvd_feed", "cve": "CVE-2024-3400", "actor": "APT29"},
+ },
+ {
+ "content": "Volexity confirms active exploitation of CVE-2024-3400 against NATO member networks",
+ "metadata": {"source": "volexity_blog", "actor": "APT29", "target": "NATO"},
+ },
+ {
+ "content": "PAN-OS GlobalProtect affected versions: < 10.2.9-h1, < 11.0.4-h1, < 11.1.2-h3",
+ "metadata": {"source": "paloalto_advisory", "cve": "CVE-2024-3400", "product": "GlobalProtect"},
+ },
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+ conversation_id="osint-pipeline",
+ )
+```
+
+While the OSINT collector is running, the enrichment agent is independently pulling actor-profile data and linking it into the same graph.
+
+```python
+def enrichment():
+ """Agent 2: enrich the graph with actor profile and TTP context."""
+ enrichment_agent.store(
+ [
+ {
+ "content": "APT29 TTP profile: T1190 (Exploit Public-Facing Application), T1071.001 (Web Protocols C2), T1078 (Valid Accounts)",
+ "metadata": {"source": "mitre_attck", "actor": "APT29", "type": "ttp_profile"},
+ },
+ {
+ "content": "APT29 infrastructure fingerprint: use of Cloudflare Workers for C2 relay, certificate reuse across campaigns",
+ "metadata": {"source": "recorded_future", "actor": "APT29", "type": "infrastructure"},
+ },
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+ conversation_id="enrichment-pipeline",
+ )
+```
+
+Run both concurrently — the graph handles the locking.
+
+```python
+t1 = threading.Thread(target=osint_collection)
+t2 = threading.Thread(target=enrichment)
+t1.start(); t2.start()
+t1.join(); t2.join()
+
+# The shared graph now contains entities and relationships from both agents.
+# The reasoning agent can query across everything both agents stored.
+```
+
+## Pattern 2 — Save / Load Handoff to a Reasoning Agent
+
+The reasoning agent runs after ingestion completes. In a production pipeline this might be a separate process, a different container, or a scheduled job. The ingestion agents save their shared state; the reasoning agent loads it.
+
+```python
+# After ingestion: save the combined graph and vector index
+osint_agent.save("./pipeline/enriched_intel/")
+# Writes:
+# pipeline/enriched_intel/agent_memory.json — all MemoryItems
+# pipeline/enriched_intel/vector_store/ — FAISS index
+# pipeline/enriched_intel/knowledge_graph.json — all nodes and edges
+
+print("Ingestion complete. State saved for reasoning agent.")
+```
+
+The reasoning agent starts fresh, loads the state, and has full access to everything the ingestion agents built.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import LiteLLM
+
+# Create a fresh context before loading — load() merges into the existing context
+reasoning_vs = VectorStore(backend="faiss", dimension=768)
+reasoning_graph = ContextGraph(advanced_analytics=True)
+reasoning_agent = AgentContext(
+ vector_store=reasoning_vs,
+ knowledge_graph=reasoning_graph,
+ graph_expansion=True,
+ max_expansion_hops=3,
+ decision_tracking=True,
+)
+
+reasoning_agent.load("./pipeline/enriched_intel/")
+# All memories, graph nodes, and vector embeddings from both ingestion agents are now available.
+
+# Use a high-capability model for the synthesis step
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+
+synthesis = reasoning_agent.query_with_reasoning(
+ "Summarize the APT29 exploitation of CVE-2024-3400: affected products, "
+ "observed TTPs, targeted sectors, and recommended mitigations.",
+ llm_provider=llm,
+ max_results=15,
+ max_hops=3,
+)
+
+print(synthesis["response"])
+print("Confidence: {:.0%}".format(synthesis["confidence"]))
+
+# Store the synthesis back into the graph — the reporting agent will retrieve it
+reasoning_agent.store(
+ "SYNTHESIS: " + synthesis["response"],
+ metadata={"type": "synthesis", "agent": "reasoning", "confidence": synthesis["confidence"]},
+ conversation_id="synthesis-output",
+)
+
+# Record the analytical judgment as a traceable decision
+reasoning_agent.record_decision(
+ category="threat_assessment",
+ scenario="APT29 active exploitation of CVE-2024-3400 in PAN-OS",
+ reasoning=synthesis["reasoning_path"],
+ outcome="high_priority_patch_advisory",
+ confidence=synthesis["confidence"],
+ entities=["APT29", "CVE-2024-3400", "GlobalProtect", "NATO"],
+ decision_maker="reasoning_agent_v2",
+)
+
+# Hand off to the reporting agent
+reasoning_agent.save("./pipeline/synthesis_output/")
+```
+
+<Info>
+ `load()` merges into the existing context — it does not wipe it first. Always create a fresh `AgentContext` before calling `load()` if you want a clean restore from a handoff checkpoint.
+</Info>
+
+## Pattern 3 — Namespaced Memories for Role Separation
+
+The reporting agent does not need its own graph instance. It shares the reasoning agent's context but scopes its writes to its own namespace — the `conversation_id` acts as an agent identifier.
+
+```python
+# The reporting agent loads the synthesis output
+reporting_vs = VectorStore(backend="faiss", dimension=768)
+reporting_graph = ContextGraph()
+reporting_agent = AgentContext(
+ vector_store=reporting_vs,
+ knowledge_graph=reporting_graph,
+ graph_expansion=True,
+)
+reporting_agent.load("./pipeline/synthesis_output/")
+
+# Retrieve everything the reasoning agent produced
+synthesis_items = reporting_agent.retrieve(
+ "APT29 CVE-2024-3400 threat assessment synthesis",
+ max_results=10,
+ conversation_id="synthesis-output", # scoped to reasoning agent's output
+)
+
+# Build the finished brief
+brief_sections = []
+for item in synthesis_items:
+ brief_sections.append(item["content"])
+
+# Store the final report under the reporting agent's own namespace
+reporting_agent.store(
+ "\n\n".join(brief_sections),
+ metadata={"type": "finished_report", "classification": "TLP:GREEN"},
+ conversation_id="reporting-output", # reporting agent's namespace
+ user_id="reporting_agent",
+)
+
+# The full pipeline audit trail: retrieve across all namespaces
+full_trail = reporting_agent.retrieve("APT29 CVE-2024-3400", max_results=25)
+print("Pipeline produced {} traceable context items".format(len(full_trail)))
+```
+
+Each agent's contributions are retrievable individually by filtering on `conversation_id`, or collectively by querying without a filter.
+
+## Domain Examples
+
+<Tabs>
+<Tab title="Defense — CTI/Threat">
+A three-agent intelligence fusion cell: an OSINT collector ingests public feeds, a HUMINT analyst loads classified summaries, and a fusion officer synthesizes both streams into a Priority Intelligence Requirement answer. The OSINT and HUMINT agents run concurrently on a shared graph; the fusion officer loads the combined state in a separate process on an air-gapped network segment.
+
+```python
+import threading
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import HuggingFaceLLM
+
+# Shared graph for concurrent multi-INT collection
+shared_graph = ContextGraph(advanced_analytics=True)
+shared_vs = VectorStore(backend="faiss", dimension=768)
+
+osint_agent = AgentContext(vector_store=shared_vs, knowledge_graph=shared_graph, graph_expansion=True)
+humint_agent = AgentContext(vector_store=shared_vs, knowledge_graph=shared_graph, graph_expansion=True)
+
+def osint_collection():
+ osint_agent.store(
+ [
+ {"content": "CVE-2024-3400 confirmed exploited by APT29 against NATO member VPN gateways",
+ "metadata": {"source": "NVD", "classification": "UNCLASSIFIED", "actor": "APT29"}},
+ {"content": "Palo Alto PSIRT: GlobalProtect OS command injection via crafted SESSID cookie",
+ "metadata": {"source": "PAN-SA-2024-0006", "classification": "UNCLASSIFIED"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+ conversation_id="osint-collector",
+ )
+
+def humint_analysis():
+ # In a cleared environment, HUMINT docs come from a local classified store
+ humint_agent.store(
+ [
+ {"content": "[S//NF] APT29 operator tradecraft: deploy WARPWIRE credential harvester post-exploitation of perimeter VPNs",
+ "metadata": {"source": "HUMINT_Q4_2024", "classification": "SECRET//NOFORN", "actor": "APT29"}},
+ {"content": "[S//NF] Target selection pattern: APT29 prioritizes Foreign Ministry and Defense Attache networks within NATO",
+ "metadata": {"source": "HUMINT_Q4_2024", "classification": "SECRET//NOFORN", "actor": "APT29"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+ conversation_id="humint-analyst",
+ )
+
+# Concurrent multi-INT collection — graph handles thread safety
+t1 = threading.Thread(target=osint_collection)
+t2 = threading.Thread(target=humint_analysis)
+t1.start(); t2.start()
+t1.join(); t2.join()
+
+# Save combined intelligence base for the air-gapped fusion officer
+osint_agent.save("./fusion/combined_intel/")
+
+# --- Fusion Officer (air-gapped segment, separate process) ---
+fusion_vs = VectorStore(backend="faiss", dimension=768)
+fusion_graph = ContextGraph(advanced_analytics=True)
+fusion_officer = AgentContext(
+ vector_store=fusion_vs,
+ knowledge_graph=fusion_graph,
+ graph_expansion=True,
+ decision_tracking=True,
+)
+fusion_officer.load("./fusion/combined_intel/")
+
+# Air-gapped inference: local model on NFS share
+llm = HuggingFaceLLM(model="/opt/models/llama-3.1-70b-instruct")
+
+pir_answer = fusion_officer.query_with_reasoning(
+ "PIR: What is APT29's current exploitation methodology against NATO perimeter VPNs "
+ "and what post-exploitation capabilities have they deployed in Q4 2024?",
+ llm_provider=llm,
+ max_results=20,
+ max_hops=3,
+)
+print(pir_answer["response"])
+fusion_officer.save("./fusion/pir_report/")
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+A three-tier SOC pipeline: Tier 1 triages the alert with a fast Groq model, Tier 2 escalates with a deep Claude analysis if Tier 1 confidence is low, and a manager agent reads the full incident thread across all tiers. All three tiers share one `ContextGraph` — each tier namespaces its findings with a tier-scoped `conversation_id`.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import Groq, LiteLLM
+
+shared_graph = ContextGraph()
+shared_vs = VectorStore(backend="faiss", dimension=768)
+
+def make_soc_agent() -> AgentContext:
+ return AgentContext(
+ vector_store=shared_vs,
+ knowledge_graph=shared_graph,
+ graph_expansion=True,
+ decision_tracking=True,
+ )
+
+tier1 = make_soc_agent()
+tier2 = make_soc_agent()
+manager = make_soc_agent()
+
+incident_id = "INC-2025-110342"
+
+# --- Tier 1: fast triage with Groq (target < 500ms) ---
+fast_llm = Groq(model="llama-3.1-8b-instant", api_key="YOUR_GROQ_KEY")
+
+alert = (
+ "Host: ws-finance-03 User: jsmith Event: Scheduled task — base64-encoded PowerShell\n"
+ "Sigma: T1053.005 Parent: wmiprvse.exe Time: 2025-06-21T09:14:32Z"
+)
+tier1.store(alert, metadata={"tier": 1, "incident": incident_id})
+
+triage = tier1.query_with_reasoning(
+ "Is this a true positive? One-line verdict.",
+ llm_provider=fast_llm,
+ max_results=5,
+)
+tier1.store(
+ "TIER1 VERDICT: " + triage["response"],
+ metadata={"tier": 1, "incident": incident_id, "confidence": triage["confidence"]},
+ conversation_id="{}-tier1".format(incident_id),
+)
+
+# --- Tier 2: deep investigation when Tier 1 confidence is low ---
+if triage["confidence"] < 0.90:
+ deep_llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+
+ investigation = tier2.query_with_reasoning(
+ "Full MITRE ATT&CK analysis of incident {}. "
+ "Identify attack chain, affected systems, blast radius, and recommended containment.".format(incident_id),
+ llm_provider=deep_llm,
+ max_results=15,
+ max_hops=3,
+ )
+ tier2.store(
+ "TIER2 ANALYSIS: " + investigation["response"],
+ metadata={"tier": 2, "incident": incident_id},
+ conversation_id="{}-tier2".format(incident_id),
+ )
+ tier2.record_decision(
+ category="escalation",
+ scenario="Escalate {} — Tier 1 confidence {:.0%}".format(incident_id, triage["confidence"]),
+ reasoning=investigation["reasoning_path"],
+ outcome="escalated_to_tier3",
+ confidence=investigation["confidence"],
+ entities=["ws-finance-03", "jsmith", "wmiprvse.exe"],
+ decision_maker="tier2_analyst",
+ )
+
+# --- Manager: read the full incident thread across all tiers ---
+full_thread = manager.retrieve(
+ "incident {}".format(incident_id),
+ use_graph=True,
+ max_results=25,
+)
+print("Full incident thread ({} items):".format(len(full_thread)))
+for item in full_thread:
+ tier = item.get("metadata", {}).get("tier", "?")
+ print(" [Tier {}] {}".format(tier, item["content"][:100]))
+
+# Per-tier history for post-incident review
+t1_history = manager.conversation("{}-tier1".format(incident_id))
+t2_history = manager.conversation("{}-tier2".format(incident_id))
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+A three-agent drug discovery pipeline: a literature agent ingests PubMed papers, an experimental agent loads validated assay results, and a chief agent synthesizes both to identify lead compounds. The literature and experimental agents run in parallel on a shared graph; the chief agent queries across both after ingestion completes.
+
+```python
+import threading
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import LiteLLM
+
+shared_graph = ContextGraph(advanced_analytics=True)
+shared_vs = VectorStore(backend="faiss", dimension=768)
+
+def make_agent() -> AgentContext:
+ return AgentContext(
+ vector_store=shared_vs,
+ knowledge_graph=shared_graph,
+ graph_expansion=True,
+ max_expansion_hops=3,
+ retention_days=None, # unlimited retention for research data
+ )
+
+lit_agent = make_agent()
+exp_agent = make_agent()
+chief = make_agent()
+
+def literature_review():
+ # Ingest PubMed abstracts for KRAS G12C inhibitors
+ lit_agent.store(
+ [
+ {"content": "Sotorasib (AMG-510) achieves 37.1% ORR in KRAS G12C NSCLC (CodeBreaK 100, NEJM 2021)",
+ "metadata": {"source": "CodeBreaK100", "target": "KRAS_G12C", "compound": "sotorasib"}},
+ {"content": "Adagrasib (MRTX849) ORR 42.9% in KRAS G12C NSCLC with CNS activity (KRYSTAL-1, NEJM 2022)",
+ "metadata": {"source": "KRYSTAL-1", "target": "KRAS_G12C", "compound": "adagrasib"}},
+ {"content": "Resistance to KRAS G12C inhibitors frequently driven by Y96D mutation in switch-II pocket",
+ "metadata": {"source": "Tanaka_CancerCell_2021", "target": "KRAS_G12C", "mechanism": "resistance"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+ conversation_id="literature-agent",
+ )
+
+def experimental_results():
+ # Load validated in-vitro and in-vivo assay data
+ exp_agent.store(
+ [
+ {"content": "Compound RMC-6291: IC50=0.6nM KRAS G12C, selectivity index 480, in-vivo efficacy 82%, toxicity grade 1",
+ "metadata": {"source": "internal_assay", "compound": "RMC-6291", "source_type": "experimental"}},
+ {"content": "Compound BI-7273: IC50=1.4nM KRAS G12C, selectivity index 310, in-vivo efficacy 71%, toxicity grade 2",
+ "metadata": {"source": "internal_assay", "compound": "BI-7273", "source_type": "experimental"}},
+ {"content": "Compound GDC-6036: IC50=0.9nM KRAS G12C, active against Y96D resistance mutation, toxicity grade 1",
+ "metadata": {"source": "internal_assay", "compound": "GDC-6036", "source_type": "experimental"}},
+ ],
+ extract_entities=True,
+ conversation_id="experimental-agent",
+ )
+
+# Parallel ingestion — graph handles concurrency
+t1 = threading.Thread(target=literature_review)
+t2 = threading.Thread(target=experimental_results)
+t1.start(); t2.start()
+t1.join(); t2.join()
+
+# Chief agent synthesizes across literature and experimental data
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+
+synthesis = chief.query_with_reasoning(
+ "Identify the top two candidate compounds for KRAS G12C NSCLC that show "
+ "both strong experimental IC50 selectivity and clinical/literature support "
+ "for the target pathway, including any coverage of resistance mechanisms.",
+ llm_provider=llm,
+ max_results=20,
+ max_hops=3,
+)
+print(synthesis["response"])
+chief.save("./drug_discovery/kras_g12c_checkpoint/")
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+A four-agent credit committee: a risk desk agent computes PD/LGD, a compliance desk agent checks Basel III and EBA requirements, a credit officer agent applies policy, and a committee chair agent reads across all three desks to produce the final decision with a complete audit trail. Each desk namespaces its findings; the chair reads across all namespaces.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import LiteLLM
+
+shared_graph = ContextGraph(advanced_analytics=True)
+shared_vs = VectorStore(backend="faiss", dimension=768)
+
+def make_desk_agent() -> AgentContext:
+ return AgentContext(
+ vector_store=shared_vs,
+ knowledge_graph=shared_graph,
+ graph_expansion=True,
+ decision_tracking=True,
+ retention_days=2555, # 7-year Basel III retention
+ kg_algorithms=True,
+ )
+
+risk_desk = make_desk_agent()
+compliance_desk = make_desk_agent()
+credit_officer = make_desk_agent()
+committee_chair = make_desk_agent()
+
+app_id = "LOAN-2025-88421"
+llm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
+
+# --- Risk Desk: PD/LGD/EL analysis ---
+risk_desk.store(
+ "Risk analysis {}: PD=2.3%, LGD=45%, EL=89k GBP, DSCR=1.12, LTV=78%. "
+ "Stress test +300bps: DSCR falls to 0.98 — marginal but within policy floor of 0.95.".format(app_id),
+ metadata={"desk": "risk", "application": app_id},
+ conversation_id="{}-risk".format(app_id),
+)
+risk_desk.record_decision(
+ category="credit_risk",
+ scenario="Risk assessment {}".format(app_id),
+ reasoning="PD 2.3% within 3% internal threshold; LTV 78% marginal — LMI required; stress test passes",
+ outcome="conditional_approval_lmi_required",
+ confidence=0.78,
+ entities=[app_id, "LTV_78pct", "PD_2pct"],
+ decision_maker="risk_model_v6",
+)
+
+# --- Compliance Desk: Basel III / EBA GL 2020/06 check ---
+compliance_desk.store(
+ [
+ {"content": "Basel III CRR2 Art. 92: total capital ratio minimum 8% + 2.5% conservation buffer",
+ "metadata": {"source": "CRR2_Art92", "category": "capital_requirement"}},
+ {"content": "EBA GL 2020/06: DSTI > 40% requires enhanced creditworthiness assessment and senior credit officer sign-off",
+ "metadata": {"source": "EBA_GL_2020_06", "category": "affordability"}},
+ {"content": "CRE20: LTV > 80% for residential mortgages requires LMI or equivalent credit enhancement",
+ "metadata": {"source": "Basel_CRE20", "category": "collateral"}},
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+compliance_check = compliance_desk.query_with_reasoning(
+ "Does application {} (residential mortgage, LTV 78%, DSTI 35%) satisfy "
+ "Basel III CRE20, EBA GL 2020/06 affordability requirements, and CRR2 Art. 92?".format(app_id),
+ llm_provider=llm,
+ max_results=10,
+)
+compliance_desk.store(
+ "COMPLIANCE FINDING: " + compliance_check["response"],
+ metadata={"desk": "compliance", "application": app_id, "confidence": compliance_check["confidence"]},
+ conversation_id="{}-compliance".format(app_id),
+)
+
+# --- Committee Chair: cross-desk synthesis and final decision ---
+committee_decision = committee_chair.query_with_reasoning(
+ "Summarize all desk findings for application {} and produce the final "
+ "credit committee decision with all conditions stated explicitly.".format(app_id),
+ llm_provider=llm,
+ max_results=25,
+ max_hops=3,
+)
+print(committee_decision["response"])
+
+# Record the final decision — this is what the regulator sees
+committee_chair.record_decision(
+ category="credit_committee",
+ scenario="Final committee decision {}".format(app_id),
+ reasoning=committee_decision["reasoning_path"],
+ outcome="approved_with_conditions_lmi",
+ confidence=committee_decision["confidence"],
+ entities=[app_id, "LTV_78pct", "DSTI_35pct"],
+ decision_maker="credit_committee_2025",
+)
+
+# Per-desk audit retrieval
+risk_thread = committee_chair.conversation("{}-risk".format(app_id))
+compliance_thread = committee_chair.conversation("{}-compliance".format(app_id))
+
+committee_chair.save("./credit_files/{}/context/".format(app_id))
+```
+
+</Tab>
+</Tabs>
+
+## Memory Isolation Reference
+
+When multiple agents write to a shared context, use `conversation_id` to isolate their streams and retrieve them individually.
+
+```python
+# Tag a memory to an agent's namespace
+context.store("Finding: lateral movement confirmed", conversation_id="tier2-ir")
+
+# Retrieve only that agent's memories
+tier2_history = context.retrieve("lateral movement", conversation_id="tier2-ir")
+
+# Get the full ordered history for a namespace
+full_history = context.conversation("tier2-ir", max_items=100)
+
+# Delete an agent's entire namespace
+context.forget(conversation_id="tier2-ir")
+```
+
+The same pattern works for user-scoped isolation — replace `conversation_id` with `user_id`:
+
+```python
+context.store("...", user_id="analyst-jsmith")
+context.retrieve("...", user_id="analyst-jsmith")
+```
+
+## Related Guides
+
+- [Agent Memory](agent-memory) — memory storage, retrieval, persistence, and the working memory window each agent uses internally
+- [Context Graphs](context-graphs) — build and traverse the shared `ContextGraph` directly; temporal interval reasoning; entity deduplication before node insertion
+- [Decision Intelligence](decision-intelligence) — record and trace decisions across agent handoffs with causal chain analysis
+- [LLM Integrations](llm-integrations) — configure the LLM provider passed to `query_with_reasoning()` in each agent
diff --git a/docs/guides/ontology.md b/docs/guides/ontology.md
new file mode 100644
index 00000000..c7aa8035
--- /dev/null
+++ b/docs/guides/ontology.md
@@ -0,0 +1,400 @@
+---
+title: "Ontology Management"
+description: "Generate OWL ontologies from your knowledge graph, validate class hierarchies, infer properties, and export to Turtle, RDF/XML, or JSON-LD."
+---
+
+`OntologyGenerator` derives a formal OWL ontology directly from the entities and relationships already in your knowledge graph — no schema design upfront. Use it to produce a machine-readable contract for your graph's classes and properties, then export to Turtle, OWL/XML, or JSON-LD for SHACL validation, reasoning engines, and STIX/TAXII toolchains.
+
+<Info>
+Semantica's ontology module derives formal OWL ontologies directly from entities and relationships already in your knowledge graph — no schema design upfront. A 6-stage pipeline infers classes, builds hierarchies, maps OWL types, and serialises to Turtle. The pipeline runs in memory; you do not need a running triple store.
+</Info>
+
+---
+
+## The graph that has no schema
+
+Populate a knowledge graph with CTI data to make the pipeline mechanics visible.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+ctx = AgentContext(vector_store=vs, knowledge_graph=graph, graph_expansion=True)
+
+ctx.store(
+ [
+ "CVE-2024-3400 is a critical vulnerability in PAN-OS exploited by APT29.",
+ "APT29 is a Russian state-sponsored threat actor targeting NATO governments.",
+ "PAN-OS is a network operating system developed by Palo Alto Networks.",
+ "HAMMERTOSS is a backdoor malware used by APT29 for command-and-control.",
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+# At this point we have ~8 nodes and several edges, but no formal schema.
+# "APT29" and a hypothetical "Lazarus Group" are both ThreatActors —
+# but nothing enforces that both must have an attribution_confidence property.
+print(f"Graph nodes: {len(graph.to_dict().get('nodes', []))}")
+```
+
+---
+
+## Generating the ontology
+
+`OntologyGenerator` reads your graph dict and runs the 6-stage pipeline.
+
+```python
+from semantica.ontology import OntologyGenerator
+
+generator = OntologyGenerator(
+ base_uri="https://cti.example.org/ontology/",
+ min_occurrences=1, # every entity type that appears at least once becomes a class
+)
+
+ontology = generator.generate_from_graph(
+ graph.to_dict(),
+ name="CyberThreatOntology",
+ build_hierarchy=True, # infer parent-child class relationships
+)
+
+# What the pipeline produced:
+print(f"Classes : {len(ontology.get('classes', []))}")
+# Classes : 4 → ThreatActor, Vulnerability, Software, Malware
+
+print(f"Properties: {len(ontology.get('properties', []))}")
+# Properties: 3 → exploits (object), targets (object), name (datatype)
+
+# Inspect a class:
+for cls in ontology.get("classes", []):
+ print(f" {cls['name']} parent={cls.get('parent')}")
+# ThreatActor parent=None
+# Vulnerability parent=None
+# Software parent=None
+# Malware parent=Software ← hierarchy inferred because HAMMERTOSS was linked to PAN-OS (Software)
+```
+
+The hierarchy entry for `Malware` shows the pipeline detected that malware is a sub-type of software based on co-occurrence patterns in the relationship graph. You can override these inferences manually before exporting.
+
+---
+
+## Validating the schema
+
+Run structural validation before exporting.
+
+```python
+from semantica.ontology import validate_ontology
+
+result = validate_ontology(ontology)
+
+print(f"Valid: {result.get('valid', False)}")
+# Valid: True
+
+for w in result.get("warnings", []):
+ print(f" WARN : {w}")
+# WARN : Class 'Malware' has no declared datatype properties
+
+for e in result.get("errors", []):
+ print(f" ERROR: {e}")
+# (none — the ontology is structurally sound)
+```
+
+A warning about missing datatype properties is common at this stage. It means the inference pipeline found the class in your graph but none of the nodes carried explicit attribute values. You can add properties manually using `ClassInferrer` and `PropertyGenerator` before the next export cycle.
+
+---
+
+## Growing the ontology as new node types emerge
+
+Use `ClassInferrer` to add new entity types incrementally without regenerating the full ontology.
+
+```python
+from semantica.ontology import ClassInferrer, PropertyGenerator
+
+# Fine-grained control: infer classes from the new batch of entities
+new_entities = [
+ {"id": "kev-001", "name": "KEV-CVE-2024-3400", "type": "KEVEntry",
+ "due_date": "2024-04-19", "ransomware_use": "Known"},
+ {"id": "kev-002", "name": "KEV-CVE-2023-4966", "type": "KEVEntry",
+ "due_date": "2023-11-14", "ransomware_use": "Unknown"},
+]
+
+inferrer = ClassInferrer()
+new_classes = inferrer.infer_classes(new_entities)
+# [{"id": "KEVEntry", "name": "KEVEntry", "parent": None, ...}]
+
+# Manually set the parent to Vulnerability before merging
+for cls in new_classes:
+ if cls["name"] == "KEVEntry":
+ cls["parent"] = "https://cti.example.org/ontology/Vulnerability"
+
+# Inspect the hierarchy
+hierarchy = inferrer.build_class_hierarchy(new_classes)
+print(hierarchy)
+# {"KEVEntry": {"parent": "...Vulnerability", "children": []}}
+
+# Merge into the existing ontology
+ontology["classes"].extend(new_classes)
+
+# Infer properties from the new nodes
+prop_gen = PropertyGenerator()
+# PropertyGenerator reads entity attributes and relationship patterns
+# to produce datatype properties (due_date: xsd:date) and object properties
+```
+
+The pattern here is incremental: you run `infer_classes` on each new batch, review the results, adjust parent assignments where the pipeline guessed wrong, and merge. The ontology grows with the graph rather than falling behind it.
+
+---
+
+## Generating an ontology from unstructured text
+
+`LLMOntologyGenerator` extracts classes and properties from prose using an LLM — useful for bootstrapping when no structured graph exists yet.
+
+```python
+from semantica.ontology import LLMOntologyGenerator
+
+llm_gen = LLMOntologyGenerator(provider="groq", model="llama-3.1-8b-instant")
+
+ontology_from_text = llm_gen.generate_ontology_from_text(
+ """
+ APT29 (also known as Cozy Bear) is a Russian state-sponsored threat actor.
+ They use spear-phishing emails to deliver HAMMERTOSS malware.
+ HAMMERTOSS communicates over Twitter and GitHub to evade detection.
+ The group has been observed exploiting CVE-2024-3400 in PAN-OS appliances.
+ """
+)
+
+# The LLM identified: ThreatActor, Malware, Vulnerability, Platform, CommunicationChannel
+print(f"Classes extracted: {len(ontology_from_text.get('classes', []))}")
+
+# Supported providers: "groq", "openai", "anthropic", "novita"
+```
+
+<Info>
+`LLMOntologyGenerator` is best for bootstrapping a new domain where no structured graph exists yet. Once you have a graph, prefer `OntologyGenerator.generate_from_graph()` — it is deterministic, reproducible, and does not consume LLM tokens on every run.
+</Info>
+
+---
+
+## Exporting for downstream systems
+
+Export in the format your downstream tools expect.
+
+```python
+from semantica.export import export_owl, export_rdf
+
+# OWL/XML — for Protégé, OWL API, HermiT, Pellet
+export_owl(ontology, "cyber_threat.owl", format="owl-xml")
+
+# Turtle — compact, human-readable; preferred for SHACL toolchains
+export_rdf(ontology, "cyber_threat.ttl", format="turtle")
+
+# JSON-LD — for web APIs and linked-data applications
+export_rdf(ontology, "cyber_threat.jsonld", format="jsonld")
+
+# N-Triples — for bulk load into triple stores (GraphDB, Stardog, Oxigraph)
+export_rdf(ontology, "cyber_threat.nt", format="ntriples")
+```
+
+The exported Turtle file is the input to Semantica's SHACL validation pipeline. See the [SHACL Validation](shacl-validation) guide for how to generate constraint shapes from this ontology and run them against live graph data.
+
+---
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+A defense CTI team ingests raw OSINT reports each morning. The ontology must stay interoperable with STIX 2.1 and the NATO MISP taxonomy, so IRIs follow the DoD namespace and the ontology is exported to OWL/XML for the org's SIEM reasoning plugin.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.ingest import ingest_file, ingest_web
+from semantica.ontology import OntologyGenerator, validate_ontology
+from semantica.export import export_owl, export_rdf
+
+vs = VectorStore(backend="faiss", dimension=768)
+graph = ContextGraph()
+ctx = AgentContext(vector_store=vs, knowledge_graph=graph, graph_expansion=True)
+
+# Ingest a campaign PDF and NVD advisory page
+cti_report = ingest_file("apt29_cozycar_2024.pdf", method="file")
+nvd_entry = ingest_web("https://nvd.nist.gov/vuln/detail/CVE-2024-3400", method="url")
+
+ctx.store(
+ [cti_report.text, nvd_entry.text],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+generator = OntologyGenerator(
+ base_uri="https://ontology.dod.mil/cyber/",
+ min_occurrences=1,
+)
+ontology = generator.generate_from_graph(
+ graph.to_dict(),
+ name="CyberThreatOntology",
+ build_hierarchy=True,
+)
+
+result = validate_ontology(ontology)
+print(f"Ontology valid: {result.get('valid')}")
+# Ontology valid: True
+
+# OWL/XML for the SIEM reasoning plugin; Turtle for the SHACL pipeline
+export_owl(ontology, "./ontologies/cyber_threat.owl", format="owl-xml")
+export_rdf(ontology, "./ontologies/cyber_threat.ttl", format="turtle")
+
+print(f"Classes : {len(ontology.get('classes', []))}")
+print(f"Properties : {len(ontology.get('properties', []))}")
+# Classes : 7 (ThreatActor, Vulnerability, Malware, Platform, Campaign, ...)
+# Properties : 9 (exploits, targets, uses, name, cvss_score, ...)
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+A SOC team models zero-trust identity entities — users, service accounts, resources, and policies — as an OWL ontology so their policy evaluation engine can use a shared formal vocabulary instead of hard-coded strings.
+
+```python
+from semantica.ontology import OntologyGenerator, ClassInferrer
+from semantica.export import export_owl
+
+# Hand-specify the identity graph — in production this comes from your IAM export
+data = {
+ "entities": [
+ {"id": "u-1", "name": "alice", "type": "User"},
+ {"id": "u-2", "name": "svc-scanner","type": "ServiceAccount"},
+ {"id": "r-1", "name": "kube-api", "type": "Resource"},
+ {"id": "r-2", "name": "s3-prod", "type": "Resource"},
+ {"id": "p-1", "name": "ReadOnly", "type": "Policy"},
+ {"id": "p-2", "name": "AdminAccess","type": "Policy"},
+ ],
+ "relationships": [
+ {"source_id": "u-1", "target_id": "p-1", "type": "BOUND_TO"},
+ {"source_id": "u-2", "target_id": "p-2", "type": "BOUND_TO"},
+ {"source_id": "p-1", "target_id": "r-1", "type": "ALLOWS_ACCESS"},
+ {"source_id": "p-2", "target_id": "r-2", "type": "ALLOWS_ACCESS"},
+ ],
+}
+
+generator = OntologyGenerator(
+ base_uri="https://zerotrust.corp/ontology/",
+ min_occurrences=1,
+)
+ontology = generator.generate_ontology(data, name="ZeroTrustOntology")
+
+# Inspect what the pipeline inferred
+inferrer = ClassInferrer()
+classes = inferrer.infer_classes(data["entities"])
+for cls in classes:
+ print(f" Class: {cls.get('name')}")
+# Class: User
+# Class: ServiceAccount
+# Class: Resource
+# Class: Policy
+
+export_owl(ontology, "./ontologies/zero_trust.owl", format="owl-xml")
+print("Ontology exported for policy evaluation engine")
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+A pharma team needs an ontology aligned to OBO Foundry conventions (GO, CHEBI, HP) to describe Phase II/III oncology trial protocols. Because the source data lives in a PostgreSQL trials database — not a knowledge graph — they use `LLMOntologyGenerator` to bootstrap from prose descriptions.
+
+```python
+from semantica.ontology import LLMOntologyGenerator, OntologyGenerator, validate_ontology
+from semantica.export import export_owl, export_rdf
+from semantica.ingest import DBIngestor
+
+# Load trial records from the clinical database
+db = DBIngestor()
+trial_rows = db.execute_query(
+ "postgresql://readonly@clindb:5432/trials",
+ """
+ SELECT compound, target_protein, disease_indication,
+ mechanism_of_action, primary_endpoint
+ FROM trial_protocols WHERE phase IN ('II','III')
+ """,
+)
+
+# Construct a natural-language summary for the LLM
+protocol_text = "\n".join(
+ f"Compound {r['compound']} targets {r['target_protein']} "
+ f"in {r['disease_indication']} via {r['mechanism_of_action']}. "
+ f"Primary endpoint: {r['primary_endpoint']}."
+ for r in trial_rows
+)
+
+# LLM extracts classes: Compound, TargetProtein, DiseaseIndication,
+# MechanismOfAction, ClinicalEndpoint, ClinicalTrial
+llm_gen = LLMOntologyGenerator(provider="openai", model="gpt-4o")
+ontology = llm_gen.generate_ontology_from_text(protocol_text)
+
+result = validate_ontology(ontology)
+print(f"Valid: {result.get('valid')}")
+for w in result.get("warnings", []):
+ print(f" WARN: {w}")
+
+# Export aligned to OBO Foundry URI convention
+export_owl(ontology, "./ontologies/clinical_trial.owl", format="owl-xml")
+export_rdf(ontology, "./ontologies/clinical_trial.ttl", format="turtle")
+print("Ontology ready for Protégé review and OBO alignment check")
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+A risk team formalises Basel III / BCBS 239 concepts as an OWL ontology so automated compliance rules can reason over credit risk entities with a shared vocabulary — replacing hard-coded field-name checks in Python scripts.
+
+```python
+from semantica.ontology import LLMOntologyGenerator, validate_ontology
+from semantica.export import export_owl, export_rdf
+from semantica.ingest import ingest_file
+
+# Ingest regulatory source documents
+regs = [
+ ingest_file("basel3_cre20.pdf", method="file"),
+ ingest_file("sr_11_7.pdf", method="file"),
+ ingest_file("bcbs239.pdf", method="file"),
+]
+
+# Use an LLM to extract the conceptual model from regulatory prose
+llm_gen = LLMOntologyGenerator(provider="anthropic", model="claude-sonnet-4-20250514")
+ontology = llm_gen.generate_ontology_from_text(
+ "\n\n".join(r.text[:8000] for r in regs) # token-safe excerpt per document
+)
+
+result = validate_ontology(ontology)
+if not result.get("valid"):
+ for err in result.get("errors", []):
+ print(f"ERROR: {err}")
+ # Fix errors before publishing to the compliance rule engine
+else:
+ print("Ontology valid — publishing to compliance registry")
+ # Turtle for SHACL shapes; OWL/XML for HermiT reasoning; JSON-LD for the API
+ export_owl(ontology, "./ontologies/regulatory.owl", format="owl-xml")
+ export_rdf(ontology, "./ontologies/regulatory.ttl", format="turtle")
+ export_rdf(ontology, "./ontologies/regulatory.jsonld", format="jsonld")
+```
+
+</Tab>
+
+</Tabs>
+
+---
+
+## Related Guides
+
+- [SHACL Validation](shacl-validation) — generate W3C SHACL constraint shapes from your ontology and validate live graph data against them
+- [Reasoning & Rules](reasoning) — apply forward/backward-chaining rules over your ontology to derive new facts
+- [Export & Serialization](export) — export graphs to RDF, GraphML, CSV, and Neo4j Cypher
+- [Semantic Extraction](semantic-extraction) — extract entities and relationships that feed ontology generation
+- [Context Graphs](context-graphs) — the knowledge graph that ontology generation reads from
diff --git a/docs/guides/pipeline.md b/docs/guides/pipeline.md
new file mode 100644
index 00000000..cb9e2464
--- /dev/null
+++ b/docs/guides/pipeline.md
@@ -0,0 +1,601 @@
+---
+title: "Pipeline Builder"
+description: "Build end-to-end data processing workflows with the PipelineBuilder DSL — ingest, extract, normalize, embed, and store in a single declarative pipeline."
+---
+
+`PipelineBuilder` solves the glue problem between processing steps. Declare your steps, register handler functions, wire the connections, and hand control to `ExecutionEngine` — it handles topological ordering, passes output between steps, retries on failure with configurable backoff, and returns a structured `ExecutionResult` you can log or alert on.
+
+<Info>
+ `PipelineBuilder` and `ExecutionEngine` are in `semantica.pipeline`. Failure handling, retry policies, and parallelism management are separate classes you can import individually for fine-grained control. Custom step handlers are plain Python functions — no subclassing required.
+</Info>
+
+## Your First Pipeline
+
+The minimum viable pipeline has three steps: ingest, extract, store. Define them, connect them, build, execute:
+
+```python
+from semantica.pipeline import PipelineBuilder, ExecutionEngine
+from semantica.ingest import ingest_file
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+# --- Define handler functions ---
+# The engine calls handler(data, **step_config), so the first positional
+# argument is always the upstream data; step config arrives as kwargs.
+
+def ingest_stix_bundles(data, **config):
+ files = ingest_file(config["path"], method="directory")
+ return [f.text for f in files if f.file_type == "json"]
+
+def extract_entities(data, **config):
+ # data is the output from the previous step
+ threshold = config.get("confidence_threshold", 0.7)
+ results = []
+ for text in data:
+ # Your NER logic here — simplified for illustration
+ results.append({"text": text, "entities": [], "threshold": threshold})
+ return results
+
+def build_graph(data, **config):
+ graph = ContextGraph(advanced_analytics=True)
+ context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ )
+ texts = [d["text"] for d in data]
+ context.store(texts, extract_entities=True, extract_relationships=True)
+ context.save(config["output_path"])
+ return {"node_count": graph.stats()["node_count"],
+ "edge_count": graph.stats()["edge_count"]}
+
+# --- Build the pipeline ---
+# Pass handler= directly in add_step() so each PipelineStep carries its callable.
+
+builder = PipelineBuilder()
+
+builder.add_step("ingest", "stix_ingest", handler=ingest_stix_bundles, path="./stix_bundles/")
+builder.add_step("extract", "ner_extract", handler=extract_entities, confidence_threshold=0.75)
+builder.add_step("store", "kg_build", handler=build_graph, output_path="./cti_output/")
+
+builder.connect_steps("ingest", "extract")
+builder.connect_steps("extract", "store")
+
+pipeline = builder.build("cti_pipeline")
+
+# --- Execute ---
+
+engine = ExecutionEngine(max_workers=4, retry_on_failure=True)
+result = engine.execute_pipeline(pipeline)
+
+print(f"Success: {result.success}")
+print(f"Output: {result.output}") # {"node_count": 312, "edge_count": 847}
+print(f"Duration: {result.metrics['execution_time']:.2f}s")
+print(f"Steps completed: {result.metrics['steps_executed']}")
+```
+
+`ExecutionEngine` performs a topological sort of the step graph before executing, so even if you declare steps in the wrong order the execution sequence is always correct. Each step receives the previous step's return value as its `data` argument.
+
+## Reading the ExecutionResult
+
+Every `engine.execute_pipeline()` call returns an `ExecutionResult` dataclass. Check it before assuming success:
+
+```python
+result = engine.execute_pipeline(pipeline)
+
+if not result.success:
+ print("Pipeline failed. Errors:")
+ for err in result.errors:
+ print(f" {err}")
+else:
+ print(f"Pipeline completed in {result.metrics['execution_time']:.1f}s")
+ print(f"Steps run: {result.metrics['steps_executed']}")
+ print(f"Steps failed: {result.metrics['steps_failed']}")
+ # result.output — the return value of the final step
+ # result.metadata — {"pipeline_id": "...", "execution_time": float}
+```
+
+`result.errors` is a `List[str]` — one entry per failed step, each containing the exception message. A pipeline with `retry_on_failure=True` attempts each failed step up to `max_retries` times (default: 3) before recording it as a failure and moving on.
+
+## Handling Failures and Configuring Retry Policy
+
+By default, `ExecutionEngine(retry_on_failure=True)` uses an exponential backoff policy: three retries, starting at 1 second, doubling each time, capped at 60 seconds. For steps that call external APIs or databases — where transient failures are expected — you can set per-step-type policies via `FailureHandler`:
+
+```python
+from semantica.pipeline import ExecutionEngine, FailureHandler, RetryPolicy, RetryStrategy
+
+# Build a custom failure handler
+handler = FailureHandler()
+
+# Web/API steps: retry up to 5 times with exponential backoff
+handler.set_retry_policy(
+ "misp_fetch",
+ RetryPolicy(
+ max_retries = 5,
+ strategy = RetryStrategy.EXPONENTIAL,
+ backoff_factor = 2.0,
+ initial_delay = 2.0,
+ max_delay = 120.0,
+ ),
+)
+
+# Database steps: fixed delay, fewer retries (connection pool usually recovers fast)
+handler.set_retry_policy(
+ "db_ingest",
+ RetryPolicy(
+ max_retries = 3,
+ strategy = RetryStrategy.FIXED,
+ initial_delay = 5.0,
+ ),
+)
+
+# NER steps: don't retry — if the model crashes it needs human intervention
+handler.set_retry_policy(
+ "ner_extract",
+ RetryPolicy(max_retries=0),
+)
+
+engine = ExecutionEngine(
+ max_workers = 4,
+ retry_on_failure = True,
+)
+# The engine uses handler.get_retry_policy(step.step_type) when a step fails
+```
+
+`handler.classify_error()` distinguishes `ValidationError` (low severity, usually don't retry), `ProcessingError` (high severity), and timeout/connection errors (medium severity, always retry). You can inspect the classification:
+
+```python
+try:
+ result = engine.execute_pipeline(pipeline)
+except Exception as e:
+ classification = handler.classify_error(e)
+ print(f"Severity: {classification['severity'].value}") # "high" / "medium" / "low"
+ print(f"Message: {classification['message']}")
+```
+
+## Running Steps in Parallel
+
+When two steps don't depend on each other — for example, NER extraction and triplet extraction both reading from the same ingest output — declare them as parallel branches by connecting both to the same upstream step:
+
+```python
+builder = PipelineBuilder()
+builder.register_step_handler("file_ingest", ingest_stix_bundles)
+builder.register_step_handler("ner_extract", run_ner)
+builder.register_step_handler("triplet_extract", run_triplets)
+builder.register_step_handler("kg_merge", merge_into_graph)
+
+builder.add_step("ingest", "file_ingest", handler=ingest_stix_bundles, path="./stix_bundles/")
+builder.add_step("ner", "ner_extract", handler=run_ner, confidence_threshold=0.75)
+builder.add_step("triplets", "triplet_extract", handler=run_triplets, include_temporal=True)
+builder.add_step("store", "kg_merge", handler=merge_into_graph, output_path="./cti_output/")
+
+# ingest feeds both ner and triplets in parallel
+builder.connect_steps("ingest", "ner")
+builder.connect_steps("ingest", "triplets")
+# both converge into store
+builder.connect_steps("ner", "store")
+builder.connect_steps("triplets", "store")
+
+builder.set_parallelism(2) # run ner and triplets concurrently
+
+pipeline = builder.build("parallel_extraction")
+engine = ExecutionEngine(max_workers=2, retry_on_failure=True)
+result = engine.execute_pipeline(pipeline)
+```
+
+`set_parallelism(n)` tells the engine how many steps it may run simultaneously. The topological sort guarantees that only steps whose dependencies are all completed are eligible for concurrent execution — you cannot accidentally run a step before its inputs are ready.
+
+## Delta / Incremental Processing
+
+Your STIX bundle directory grows by 20–30 new files each night. Re-processing all 4,000 historical files every morning wastes time and compute. `delta_mode=True` on the ingest step tells the pipeline to process only files that have changed since the last version snapshot:
+
+```python
+builder = PipelineBuilder()
+builder.register_step_handler("stix_ingest", ingest_stix_bundles)
+builder.register_step_handler("ner_extract", run_ner)
+builder.register_step_handler("kg_append", append_to_graph)
+
+builder.add_step(
+ "ingest", "stix_ingest",
+ handler = ingest_stix_bundles,
+ path = "./stix_bundles/",
+ delta_mode = True,
+ base_version_id = "2024-11-30", # last successful run
+ target_version_id = "2024-12-01", # today's snapshot
+)
+builder.add_step("extract", "ner_extract", handler=run_ner)
+builder.add_step("store", "kg_append", handler=append_to_graph, output_path="./cti_output/")
+
+builder.connect_steps("ingest", "extract")
+builder.connect_steps("extract", "store")
+
+pipeline = builder.build("delta_pipeline")
+result = ExecutionEngine(max_workers=4, retry_on_failure=True).execute_pipeline(pipeline)
+
+print(f"Delta run: {result.output}")
+```
+
+The `base_version_id` and `target_version_id` are stored on the `PipelineStep` dataclass and passed through to your handler via `config` — your handler is responsible for using them to filter its input. A typical pattern is to check file modification timestamps against the base version date.
+
+## Building from a Config Dict
+
+For pipelines defined in config files — useful when different environments (dev, staging, prod) run the same pipeline with different paths and thresholds — pass a dict to `build_pipeline()` instead of calling `add_step()` manually:
+
+```python
+from semantica.pipeline import PipelineBuilder, ExecutionEngine
+
+pipeline_config = {
+ "name": "cti_pipeline",
+ "parallelism": 4,
+ "steps": [
+ {
+ "name": "ingest",
+ "type": "stix_ingest",
+ "config": {"path": "./stix_bundles/"},
+ },
+ {
+ "name": "extract",
+ "type": "ner_extract",
+ "config": {"confidence_threshold": 0.8},
+ },
+ {
+ "name": "store",
+ "type": "kg_build",
+ "config": {"output_path": "./cti_output/"},
+ },
+ ],
+}
+
+builder = PipelineBuilder()
+# Register handlers as before, then:
+pipeline = builder.build_pipeline(pipeline_config)
+
+engine = ExecutionEngine(max_workers=4, retry_on_failure=True)
+result = engine.execute_pipeline(pipeline)
+```
+
+Note that `build_pipeline()` reads step connections from the `"dependencies"` key inside each step's config dict (not from `connect_steps()` calls). Add dependencies explicitly if you use this path:
+
+```python
+{
+ "name": "extract",
+ "type": "ner_extract",
+ "config": {"confidence_threshold": 0.8, "dependencies": ["ingest"]},
+},
+```
+
+## Monitoring Progress
+
+`ExecutionEngine` integrates with Semantica's progress tracker automatically — every step start, update, and completion is recorded. To observe progress during a long-running pipeline, inspect step status on the `Pipeline` object after execution:
+
+```python
+from semantica.pipeline import StepStatus
+
+result = engine.execute_pipeline(pipeline)
+for step in pipeline.steps:
+ status_str = step.status.value # "completed" / "failed" / "skipped"
+ print(f" {step.name:20s} {status_str}")
+ if step.status == StepStatus.FAILED and step.error:
+ print(f" Error: {step.error}")
+```
+
+`result.metrics` gives the aggregate view:
+
+```python
+print(f"Total time: {result.metrics['execution_time']:.2f}s")
+print(f"Steps completed: {result.metrics['steps_executed']}")
+print(f"Steps failed: {result.metrics['steps_failed']}")
+```
+
+## Domain Examples
+
+<Tabs>
+ <Tab title="Defense — CTI/Threat">
+ A SOC threat intelligence team needs an end-to-end pipeline that ingests STIX bundles from a classified directory, runs entity extraction with custom threat-actor labels, and builds a `ContextGraph` ready for analyst queries. The pipeline runs every six hours; failed steps retry automatically so a transient filesystem error doesn't drop an ingestion cycle.
+
+```python
+from semantica.pipeline import PipelineBuilder, ExecutionEngine, RetryPolicy, RetryStrategy
+from semantica.ingest import ingest_file
+from semantica.semantic_extract import NamedEntityRecognizer
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+def ingest_classified_stix(data, **config):
+ files = ingest_file(config["path"], method="directory")
+ return [
+ {"text": f.text, "source": f.name, "classification": config["classification"]}
+ for f in files if f.file_type == "json"
+ ]
+
+def extract_cti_entities(data, **config):
+ ner = NamedEntityRecognizer(
+ methods=["pattern", "ml"],
+ custom_labels=["THREAT_ACTOR", "MALWARE", "CVE", "C2_DOMAIN", "CAMPAIGN"],
+ confidence_threshold=config.get("confidence_threshold", 0.80),
+ )
+ results = []
+ for doc in data:
+ entities = ner.extract_entities(doc["text"])
+ results.append({**doc, "entities": [e.__dict__ for e in entities]})
+ return results
+
+def build_cti_graph(data, **config):
+ graph = ContextGraph(advanced_analytics=True, community_detection=True)
+ context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ graph_expansion = True,
+ )
+ texts = [d["text"] for d in data]
+ context.store(texts, extract_entities=True, extract_relationships=True)
+ context.save(config["output_path"])
+ return graph.stats()
+
+builder = PipelineBuilder()
+builder.register_step_handler("classified_ingest", ingest_classified_stix)
+builder.register_step_handler("cti_ner", extract_cti_entities)
+builder.register_step_handler("cti_graph", build_cti_graph)
+
+builder.add_step("ingest", "classified_ingest",
+ handler=ingest_classified_stix,
+ path="./classified/stix/",
+ classification="SECRET//REL TO USA FVEY")
+builder.add_step("extract", "cti_ner", handler=extract_cti_entities, confidence_threshold=0.85)
+builder.add_step("store", "cti_graph", handler=build_cti_graph, output_path="./cti_state/")
+
+builder.connect_steps("ingest", "extract")
+builder.connect_steps("extract", "store")
+builder.set_parallelism(2)
+
+pipeline = builder.build("cti_pipeline")
+engine = ExecutionEngine(max_workers=2, retry_on_failure=True)
+result = engine.execute_pipeline(pipeline)
+
+print(f"CTI pipeline: success={result.success}, "
+ f"nodes={result.output.get('node_count')}, "
+ f"time={result.metrics['execution_time']:.1f}s")
+```
+
+ </Tab>
+
+ <Tab title="Security — SOC/Incident">
+ During an active P1 incident, the SOC needs a 15-minute pipeline that pulls fresh SIEM alert CSVs, cross-references CVEs from the internal database, and updates the incident knowledge graph. The pipeline runs on a tight cycle — NER failures must not block the graph update, so steps are configured to not retry on NER errors but to retry aggressively on database timeouts.
+
+```python
+from semantica.pipeline import (
+ PipelineBuilder, ExecutionEngine, FailureHandler,
+ RetryPolicy, RetryStrategy,
+)
+from semantica.ingest import ingest_file, DBIngestor
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+def ingest_siem_alerts(data, **config):
+ files = ingest_file(config["path"], method="directory")
+ return [{"text": f.text, "source": f.name}
+ for f in files if f.file_type == "csv"]
+
+def enrich_with_cves(data, **config):
+ db = DBIngestor()
+ cve_rows = db.execute_query(config["db_url"], config["query"])
+ cve_lookup = {r["cve_id"]: r for r in cve_rows}
+ for doc in data:
+ doc["cve_enrichment"] = cve_lookup
+ return data
+
+def update_incident_graph(data, **config):
+ graph = ContextGraph(advanced_analytics=True)
+ context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ )
+ texts = [d["text"] for d in data]
+ context.store(texts, extract_entities=True, extract_relationships=True)
+ context.save(config["output_path"])
+ return graph.stats()
+
+handler = FailureHandler()
+handler.set_retry_policy("db_enrich",
+ RetryPolicy(max_retries=5, strategy=RetryStrategy.EXPONENTIAL,
+ initial_delay=2.0, max_delay=30.0))
+handler.set_retry_policy("cti_ner", RetryPolicy(max_retries=0))
+
+builder = PipelineBuilder()
+builder.register_step_handler("siem_ingest", ingest_siem_alerts)
+builder.register_step_handler("db_enrich", enrich_with_cves)
+builder.register_step_handler("graph_update", update_incident_graph)
+
+builder.add_step("ingest", "siem_ingest", handler=ingest_siem_alerts, path="./siem_exports/")
+builder.add_step("enrich", "db_enrich",
+ handler=enrich_with_cves,
+ db_url="postgresql://ro:pass@cvedb:5432/nvd",
+ query="SELECT cve_id, description, cvss_v3_score FROM cve_records "
+ "WHERE cve_id = ANY(ARRAY['CVE-2024-3400','CVE-2024-21762'])")
+builder.add_step("store", "graph_update", handler=update_incident_graph, output_path="./incident_state/")
+
+builder.connect_steps("ingest", "enrich")
+builder.connect_steps("enrich", "store")
+
+pipeline = builder.build("incident_pipeline")
+engine = ExecutionEngine(max_workers=4, retry_on_failure=True)
+result = engine.execute_pipeline(pipeline)
+
+print(f"Incident update: {result.success}, "
+ f"nodes={result.output.get('node_count')}, "
+ f"errors={result.errors}")
+```
+
+ </Tab>
+
+ <Tab title="Life Science — Clinical/Pharma">
+ A clinical NLP pipeline processes EHR exports after each trial month closes: ingest patient notes from a shared directory, run biomedical NER using a HuggingFace model to extract drug/disease/dosage entities, record ICH E6(R2)-compliant provenance, and append to the trial graph. The pipeline uses delta mode so only notes added since the last run are processed.
+
+```python
+from semantica.pipeline import PipelineBuilder, ExecutionEngine
+from semantica.ingest import ingest_file
+from semantica.semantic_extract import NamedEntityRecognizer
+from semantica.provenance import ProvenanceManager, SourceReference
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+def ingest_ehr_notes(data, **config):
+ files = ingest_file(config["path"], method="directory")
+ return [
+ {"text": f.text, "patient_id": f.name.split("_")[0], "source": f.name}
+ for f in files
+ ]
+
+def run_biomedical_ner(data, **config):
+ ner = NamedEntityRecognizer(
+ methods=["huggingface"],
+ huggingface_model="d4data/biomedical-ner-all",
+ confidence_threshold=config.get("confidence_threshold", 0.80),
+ custom_labels=["DRUG", "DISEASE", "DOSAGE", "GENE", "BIOMARKER"],
+ )
+ results = []
+ for doc in data:
+ entities = ner.extract_entities(doc["text"])
+ results.append({**doc, "entities": entities})
+ return results
+
+def track_provenance_and_store(data, **config):
+ manager = ProvenanceManager(storage_path=config["provenance_db"])
+ graph = ContextGraph(advanced_analytics=True)
+ context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ retention_days = None,
+ )
+ for doc in data:
+ for entity in doc.get("entities", []):
+ source = SourceReference(
+ document=doc["patient_id"],
+ section="clinical_note",
+ confidence=getattr(entity, "confidence", 1.0),
+ )
+ manager.track_entity(
+ entity_id=f"{doc['patient_id']}_{getattr(entity, 'text', '')}",
+ source=source.document,
+ metadata={"entity_type": getattr(entity, "label", ""),
+ "confidence": getattr(entity, "confidence", 1.0)},
+ )
+ context.store([d["text"] for d in data], extract_entities=True)
+ context.save(config["output_path"])
+ return graph.stats()
+
+builder = PipelineBuilder()
+builder.register_step_handler("ehr_ingest", ingest_ehr_notes)
+builder.register_step_handler("bio_ner", run_biomedical_ner)
+builder.register_step_handler("prov_store", track_provenance_and_store)
+
+builder.add_step("ingest", "ehr_ingest",
+ handler=ingest_ehr_notes,
+ path="./ehr_exports/month_12/",
+ delta_mode=True,
+ base_version_id="2024-11",
+ target_version_id="2024-12")
+builder.add_step("extract", "bio_ner", handler=run_biomedical_ner, confidence_threshold=0.82)
+builder.add_step("store", "prov_store",
+ handler=track_provenance_and_store,
+ provenance_db="./provenance/trial_Q4.db",
+ output_path="./trial_state/")
+
+builder.connect_steps("ingest", "extract")
+builder.connect_steps("extract", "store")
+builder.set_parallelism(4)
+
+pipeline = builder.build("clinical_nlp_pipeline")
+engine = ExecutionEngine(max_workers=4, retry_on_failure=True)
+result = engine.execute_pipeline(pipeline)
+
+print(f"Clinical pipeline: {result.success}, "
+ f"nodes={result.output.get('node_count')}")
+```
+
+ </Tab>
+
+ <Tab title="Banking — Risk/Compliance">
+ A compliance team runs a monthly incremental pipeline: ingest new BIS publications from the sitemap, extract capital-ratio and threshold entities, and append them to the existing compliance knowledge graph that already holds three years of regulatory history. Delta mode ensures only pages published since the last run are processed.
+
+```python
+from semantica.pipeline import PipelineBuilder, ExecutionEngine
+from semantica.ingest import ingest_web
+from semantica.semantic_extract import NamedEntityRecognizer, TripletExtractor
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+def ingest_bis_pages(data, **config):
+ pages = ingest_web(config["sitemap"], method="sitemap")
+ return [
+ {"text": p.text, "url": p.url}
+ for p in pages
+ if p.text.strip() and any(
+ kw in p.url.lower() for kw in ["bcbs", "capital", "liquidity"]
+ )
+ ]
+
+def extract_regulatory_entities(data, **config):
+ ner = NamedEntityRecognizer(
+ methods=["pattern", "ml"],
+ custom_labels=["REGULATION", "CAPITAL_RATIO", "RISK_WEIGHT", "THRESHOLD"],
+ confidence_threshold=config.get("confidence_threshold", 0.75),
+ )
+ extractor = TripletExtractor(
+ method="pattern", include_temporal=True, include_provenance=True,
+ )
+ results = []
+ for doc in data:
+ entities = ner.extract_entities(doc["text"])
+ triplets = extractor.extract_triplets(doc["text"], entities=entities)
+ results.append({**doc, "entities": entities, "triplets": triplets})
+ return results
+
+def append_to_compliance_graph(data, **config):
+ graph = ContextGraph(advanced_analytics=True)
+ graph.load_from_file(config["existing_graph"])
+ context = AgentContext(
+ vector_store = VectorStore(backend="faiss", dimension=768),
+ knowledge_graph = graph,
+ retention_days = 2555, # 7-year regulatory requirement
+ )
+ context.store([d["text"] for d in data],
+ extract_entities=True, extract_relationships=True)
+ context.save(config["output_path"])
+ return {"added_docs": len(data), "graph": graph.stats()}
+
+builder = PipelineBuilder()
+builder.register_step_handler("bis_ingest", ingest_bis_pages)
+builder.register_step_handler("rule_extract", extract_regulatory_entities)
+builder.register_step_handler("graph_append", append_to_compliance_graph)
+
+builder.add_step("ingest", "bis_ingest",
+ handler=ingest_bis_pages,
+ sitemap="https://www.bis.org/sitemap.xml",
+ delta_mode=True,
+ base_version_id="2024-11",
+ target_version_id="2024-12")
+builder.add_step("extract", "rule_extract", handler=extract_regulatory_entities, confidence_threshold=0.75)
+builder.add_step("store", "graph_append",
+ handler=append_to_compliance_graph,
+ existing_graph="./compliance_graph/knowledge_graph.json",
+ output_path="./compliance_graph/")
+
+builder.connect_steps("ingest", "extract")
+builder.connect_steps("extract", "store")
+builder.set_parallelism(4)
+
+pipeline = builder.build("regulatory_pipeline")
+engine = ExecutionEngine(max_workers=4, retry_on_failure=True)
+result = engine.execute_pipeline(pipeline)
+
+print(f"Compliance delta update: {result.output}")
+```
+
+ </Tab>
+</Tabs>
+
+## Related Guides
+
+- [Ingest](ingest) — all source types for the ingest step: PDFs, APIs, databases, RSS feeds, STIX directories, and streams
+- [Semantic Extraction](semantic-extraction) — NER, relation extraction, triplet extraction, and event detection for the extract step
+- [Context Graphs](context-graphs) — building and querying the `ContextGraph` that the store step populates
+- [Provenance](provenance) — tracking the origin document, confidence score, and pipeline run ID for every extracted entity
diff --git a/docs/guides/policy-engine.md b/docs/guides/policy-engine.md
new file mode 100644
index 00000000..35582da2
--- /dev/null
+++ b/docs/guides/policy-engine.md
@@ -0,0 +1,544 @@
+---
+title: "Policy Engine"
+description: "Define, version, and enforce governance policies over knowledge graph decisions — with compliance checking, violation tracking, impact analysis, and multi-level approval workflows."
+icon: "scale-balanced"
+---
+
+`PolicyEngine` enforces named policies against recorded decisions, returning `True` if the decision satisfies all policy rules. Use it to gate AI decisions at runtime — attributions requiring dual-source confirmation, escalations requiring senior approval, or any decision category where compliance must be verified before the outcome is recorded. Policies are versioned graph nodes, so every check, exception, and approval chain is part of the permanent audit trail.
+
+<Info>
+The Policy Engine sits above `AgentContext` and `ContextGraph`. Policies are stored as nodes in the same graph as decisions, giving them the same causal tracing, provenance, and temporal validity as any other knowledge graph entity. `PolicyEngine` and `Policy` import from `semantica.context`. `Decision` imports from `semantica.context` (it is a dataclass defined in `semantica.context.decision_models`). `DecisionRecorder` imports from `semantica.context.decision_recorder`.
+</Info>
+
+---
+
+## Defining the policy
+
+A `Policy` is a dataclass with a free-form `rules` dict — encode whatever your domain requires.
+
+```python
+from semantica.context import ContextGraph, PolicyEngine, Policy
+from datetime import datetime
+
+graph = ContextGraph()
+engine = PolicyEngine(graph_store=graph)
+
+attribution_policy = Policy(
+ policy_id = "pol-attr-001",
+ name = "Nation-State Attribution — Dual Source + Senior Approval",
+ description = (
+ "Attributions to nation-state actors require corroboration from two independent "
+ "intelligence sources and explicit senior analyst approval before being recorded "
+ "in the authoritative graph."
+ ),
+ rules = {
+ "min_independent_sources": 2,
+ "required_approver_role": "senior_analyst",
+ "disallowed_outcomes": ["nation_state_attributed_single_source"],
+ "min_confidence": 0.85,
+ "mandatory_fields": ["source_a", "source_b", "approver"],
+ },
+ category = "threat_attribution",
+ version = "1.0.0",
+ created_at = datetime.utcnow(),
+ updated_at = datetime.utcnow(),
+)
+
+policy_id = engine.add_policy(attribution_policy)
+print(f"Policy registered: {policy_id}")
+# Policy registered: pol-attr-001
+```
+
+The policy is now a node in the graph. It has a version string, a creation timestamp, and a `rules` dict that the compliance checker will read when evaluating decisions against it.
+
+---
+
+## Checking a decision for compliance
+
+`check_compliance` takes a `Decision` object and the policy ID and returns a boolean.
+
+```python
+from semantica.context import Decision
+
+# The AI analyst's APT29 attribution — only one source cited, no senior approval yet
+decision = Decision(
+ decision_id = "", # auto-generated if left empty
+ category = "threat_attribution",
+ scenario = "APT29 activity cluster in NATO network telemetry Q2 2025",
+ reasoning = (
+ "Observed TTPs match APT29 historical patterns: HAMMERTOSS C2, "
+ "spear-phishing via OneDrive lure, targeting foreign ministry staff. "
+ "Single source: internal SIEM telemetry."
+ ),
+ outcome = "nation_state_attributed_single_source",
+ confidence = 0.91,
+ timestamp = datetime.utcnow(),
+ decision_maker= "ai_threat_analyst_v3",
+)
+
+is_compliant = engine.check_compliance(decision, policy_id)
+print(f"Compliant: {is_compliant}")
+# Compliant: False
+#
+# The outcome "nation_state_attributed_single_source" is in disallowed_outcomes.
+# The policy requires min_independent_sources=2 — the decision only cited one.
+```
+
+The engine returns `False`. The decision has not been rejected — it has been flagged. What happens next depends on your workflow. In some organisations, a non-compliant result simply blocks the write to the authoritative graph. In others, it triggers an exception process where a human approver reviews the evidence and signs off.
+
+---
+
+## Recording a policy exception
+
+`record_exception` permanently links a decision, the policy it violated, the approver identity, and the justification.
+
+```python
+exception_id = engine.record_exception(
+ decision_id = decision.decision_id,
+ policy_id = policy_id,
+ reason = "Time-sensitive attribution — protective action required before second source available",
+ approver = "sr_analyst_chen",
+ justification= (
+ "Senior analyst reviewed SIEM telemetry and concurs with TTP matching. "
+ "Exception approved under Emergency Attribution Procedure §3.2. "
+ "Second source corroboration to be completed within 72 hours."
+ ),
+)
+
+print(f"Exception recorded: {exception_id}")
+# Exception recorded: exc-pol-attr-001-20250621-001
+#
+# The exception node is linked to both the decision and the policy in the graph,
+# creating a permanent three-way provenance link: decision → exception → policy.
+```
+
+---
+
+## Building a multi-level approval chain
+
+For the highest-stakes decisions — formal attribution reports that will be shared with government partners — a single approver is not enough. Three people need to sign off: the team lead, the department head, and the CISO. `DecisionRecorder.record_approval_chain` captures all three in a single call, linking each approver to the communication method and context of their sign-off.
+
+```python
+from semantica.context.decision_recorder import DecisionRecorder
+
+recorder = DecisionRecorder(graph_store=graph)
+
+# approvers, methods, and contexts must be equal-length parallel lists
+recorder.record_approval_chain(
+ decision_id = decision.decision_id,
+ approvers = ["team_lead_okonkwo", "dept_head_zhang", "ciso_miller"],
+ methods = ["slack_dm", "zoom_call", "email"],
+ contexts = [
+ "Team lead reviewed TTPs and SIEM evidence",
+ "Dept head approved sharing with Five Eyes partners",
+ "CISO authorised formal nation-state attribution report",
+ ],
+)
+
+print("Three-level approval chain recorded")
+# The graph now carries a directed approval chain:
+# decision → team_lead_okonkwo → dept_head_zhang → ciso_miller
+# Each link is stamped with method and context for Inspector General review.
+```
+
+---
+
+## What-if impact analysis before changing a policy
+
+Six months on, your threat intelligence lead wants to tighten the policy: raise the minimum confidence threshold from 0.85 to 0.92 to reduce false-positive attributions. Before she updates the policy, she wants to know how many past decisions would have been blocked under the stricter rule.
+
+`analyze_policy_impact` runs a what-if simulation over the historical decision record — no permanent changes are made.
+
+```python
+current_policy = engine.get_policy(policy_id)
+
+impact = engine.analyze_policy_impact(
+ policy_id = policy_id,
+ proposed_rules = {**current_policy.rules, "min_confidence": 0.92},
+)
+
+print(f"Decisions affected by raising confidence floor to 0.92: {impact.get('affected_decisions', 0)}")
+# Decisions affected by raising confidence floor to 0.92: 4
+#
+# Four past attributions had confidence between 0.85 and 0.92.
+# Under the new rule, all four would have required exceptions.
+# The lead can now make an evidence-based choice: is that trade-off acceptable?
+```
+
+The impact dict contains per-decision detail, not just the count. You can inspect which specific attribution decisions would have been affected, review their reasoning, and decide whether tightening the threshold is worth it.
+
+---
+
+## Updating the policy and finding affected decisions
+
+The lead decides to proceed with the threshold increase. She updates the policy to version 1.1.0, recording her reason. The old version is preserved in the history.
+
+```python
+updated_policy_id = engine.update_policy(
+ policy_id = policy_id,
+ rules = {**current_policy.rules, "min_confidence": 0.92},
+ change_reason = "Q3 attribution quality review — raise confidence floor from 0.85 to 0.92 "
+ "to reduce false-positive nation-state attributions",
+ new_version = "1.1.0",
+)
+
+print(f"Policy updated: {updated_policy_id} -> version 1.1.0")
+# Policy updated: pol-attr-001 -> version 1.1.0
+
+# Find all decisions that were evaluated under v1.0.0 —
+# these need to be re-reviewed to confirm they still meet the new standard.
+affected = engine.get_affected_decisions(
+ policy_id = policy_id,
+ from_version = "1.0.0",
+ to_version = "1.1.0",
+)
+
+print(f"Decisions to re-audit: {len(affected)}")
+for dec in affected:
+ print(f" {dec.get('decision_id')} confidence={dec.get('confidence')} outcome={dec.get('outcome')}")
+# decision-a3f1 confidence=0.87 outcome=nation_state_attributed
+# decision-b22c confidence=0.89 outcome=nation_state_attributed
+# ...
+```
+
+This is the re-audit workflow: every decision made under the old policy is surfaced, reviewed against the new standard, and either re-confirmed or flagged for correction. The graph preserves the full history of which policy version governed each decision.
+
+---
+
+## Reviewing the full audit trail
+
+At any point — for an Inspector General review, a board report, or an incident investigation — you can retrieve the complete version history of a policy.
+
+```python
+history = engine.get_policy_history(policy_id)
+
+print(f"Policy versions on record: {len(history)}")
+for version in history:
+ print(f" v{version.version} updated={version.updated_at.date()} rules_keys={list(version.rules.keys())}")
+# v1.0.0 updated=2025-06-21 rules_keys=[min_independent_sources, required_approver_role, ...]
+# v1.1.0 updated=2025-09-14 rules_keys=[min_independent_sources, required_approver_role, ...]
+#
+# The full rules dict for each version is preserved — you can replay exactly
+# what the compliance check would have returned for any past decision against
+# any past version of the policy.
+```
+
+---
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+TLP:RED intelligence must never be shared outside the originating organisation without commander-level approval. The policy is enforced on every information-sharing decision that touches classified threat reporting. Violations are routed to the J2 officer for exception review rather than silently logged.
+
+```python
+from semantica.context import ContextGraph, PolicyEngine, Policy, Decision
+from semantica.context.decision_recorder import DecisionRecorder
+from datetime import datetime
+
+graph = ContextGraph()
+engine = PolicyEngine(graph_store=graph)
+recorder = DecisionRecorder(graph_store=graph)
+
+opsec_policy = Policy(
+ policy_id = "pol-opsec-001",
+ name = "TLP:RED — Restricted Dissemination",
+ description = "TLP:RED intelligence must not be shared outside the originating organisation",
+ rules = {
+ "classification": "TLP:RED",
+ "disallowed_outcomes": ["shared_with_partner", "published"],
+ "min_confidence": 0.95,
+ "mandatory_fields": ["tlp", "classification", "authorised_recipients"],
+ },
+ category = "information_sharing",
+ version = "2.1.0",
+ created_at = datetime.utcnow(),
+ updated_at = datetime.utcnow(),
+)
+engine.add_policy(opsec_policy)
+
+decision = Decision(
+ decision_id = "",
+ category = "information_sharing",
+ scenario = "APT29 SIGINT report TLP:RED — share with Five Eyes partners?",
+ reasoning = "Tactical intelligence — partner request via UKIC liaison",
+ outcome = "shared_with_partner", # violates TLP:RED policy
+ confidence = 0.88,
+ timestamp = datetime.utcnow(),
+ decision_maker= "analyst_rodriguez",
+)
+
+is_compliant = engine.check_compliance(decision, "pol-opsec-001")
+print(f"Compliant: {is_compliant}")
+# Compliant: False — outcome 'shared_with_partner' is disallowed; confidence below 0.95
+
+if not is_compliant:
+ # Route to J2 for exception review — dual commander approval required
+ exception_id = engine.record_exception(
+ decision_id = decision.decision_id,
+ policy_id = "pol-opsec-001",
+ reason = "Five Eyes partner urgent request — time-critical tactical intelligence",
+ approver = "j2_officer_hayes",
+ justification= "Commander approved limited dissemination under UKUSA Article 4 emergency clause",
+ )
+ recorder.record_approval_chain(
+ decision_id = decision.decision_id,
+ approvers = ["j2_officer_hayes", "unit_commander_brooks"],
+ methods = ["secure_phone", "in_person"],
+ contexts = ["J2 tactical review", "Commander emergency approval"],
+ )
+ print(f"Exception recorded with dual-commander approval: {exception_id}")
+
+# Version history for Inspector General review
+history = engine.get_policy_history("pol-opsec-001")
+print(f"Policy versions on record: {len(history)}")
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+Zero-trust access policies enforce MFA for Tier-1 systems and PAM session checkout for privileged accounts. Every automated access decision is checked against both policies. When the PAM portal is unavailable during an emergency patch window, the SOC lead records a time-bounded exception with her sign-off before the work begins — not after.
+
+```python
+from semantica.context import ContextGraph, PolicyEngine, Policy, Decision
+from datetime import datetime
+
+graph = ContextGraph()
+engine = PolicyEngine(graph_store=graph)
+
+for pol in [
+ Policy(
+ policy_id = "pol-zt-mfa",
+ name = "MFA Required — All Tier-1",
+ description = "Every Tier-1 access decision must verify MFA",
+ rules = {
+ "requires_mfa": True,
+ "disallowed_outcomes": ["access_granted_without_mfa"],
+ "min_confidence": 0.90,
+ },
+ category = "access_control",
+ version = "1.0.0",
+ created_at = datetime.utcnow(),
+ updated_at = datetime.utcnow(),
+ ),
+ Policy(
+ policy_id = "pol-zt-pam",
+ name = "PAM Checkout — Privileged Accounts",
+ description = "Privileged account use requires PAM session checkout",
+ rules = {
+ "requires_pam": True,
+ "session_recording": True,
+ "max_session_hours": 4,
+ "disallowed_outcomes": ["privileged_access_granted_no_pam"],
+ },
+ category = "privileged_access",
+ version = "1.0.0",
+ created_at = datetime.utcnow(),
+ updated_at = datetime.utcnow(),
+ ),
+]:
+ engine.add_policy(pol)
+
+# Emergency patch window — PAM portal down
+decision = Decision(
+ decision_id = "",
+ category = "privileged_access",
+ scenario = "sysadmin_kim patching DC-04 — PAM portal unreachable",
+ reasoning = "Critical patch CVE-2025-1234 — 4-hour RTO — PAM portal offline",
+ outcome = "privileged_access_granted_no_pam",
+ confidence = 0.78,
+ timestamp = datetime.utcnow(),
+ decision_maker= "soc_automation",
+)
+
+pam_compliant = engine.check_compliance(decision, "pol-zt-pam")
+print(f"PAM policy compliant: {pam_compliant}")
+# PAM policy compliant: False
+
+# SOC lead records the exception before work begins
+exception_id = engine.record_exception(
+ decision_id = decision.decision_id,
+ policy_id = "pol-zt-pam",
+ reason = "PAM portal offline during critical patch window",
+ approver = "soc_lead_okafor",
+ justification= "Emergency patch approved under BCP §7.3 — manual session logging in place",
+)
+
+# What-if: impact of cutting max session hours from 4 to 2 for board risk review
+pam_policy = engine.get_policy("pol-zt-pam")
+impact = engine.analyze_policy_impact(
+ policy_id = "pol-zt-pam",
+ proposed_rules = {**pam_policy.rules, "max_session_hours": 2},
+)
+print(f"Decisions affected by tighter session cap: {impact.get('affected_decisions', 0)}")
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+An absolute drug contraindication policy prevents metformin from being prescribed when eGFR is below 30. The AI clinical decision-support system checks every prescribing decision against this policy before it reaches the EHR. When a borderline case requires a clinical exception, a three-person MDT approval chain is recorded — consultant, renal specialist, and pharmacist — before the prescription is issued.
+
+```python
+from semantica.context import ContextGraph, PolicyEngine, Policy, Decision
+from semantica.context.decision_recorder import DecisionRecorder
+from datetime import datetime
+
+graph = ContextGraph()
+engine = PolicyEngine(graph_store=graph)
+recorder = DecisionRecorder(graph_store=graph)
+
+safety_policy = Policy(
+ policy_id = "pol-clin-001",
+ name = "Metformin Absolute Contraindication — eGFR < 30",
+ description = "Metformin must not be prescribed when eGFR is below 30 ml/min/1.73m²",
+ rules = {
+ "contraindicated_drug": "metformin",
+ "contraindication_condition": {"egfr": {"operator": "<", "threshold": 30}},
+ "disallowed_outcomes": ["metformin_prescribed", "metformin_continued"],
+ "requires_clinician_sign_off": True,
+ "mandatory_checks": ["egfr_measured_within_90_days"],
+ },
+ category = "clinical_safety",
+ version = "3.0.0", # aligned to BNF 2024
+ created_at = datetime.utcnow(),
+ updated_at = datetime.utcnow(),
+ metadata = {"source": "BNF_2024", "strength": "absolute"},
+)
+engine.add_policy(safety_policy)
+
+# AI decision-support recommendation
+decision = Decision(
+ decision_id = "",
+ category = "treatment_modification",
+ scenario = "PT-00841: T2DM, eGFR 28 — metformin review",
+ reasoning = "eGFR 28 is below the 30 threshold; discontinue metformin and initiate SGLT2i",
+ outcome = "metformin_discontinued_dapagliflozin_initiated",
+ confidence = 0.97,
+ timestamp = datetime.utcnow(),
+ decision_maker= "cdss_v4",
+)
+
+is_compliant = engine.check_compliance(decision, "pol-clin-001")
+print(f"Compliant: {is_compliant}")
+# Compliant: True — outcome is metformin_discontinued, which is allowed
+
+# MDT approval chain for the prescribing record
+recorder.record_approval_chain(
+ decision_id = decision.decision_id,
+ approvers = ["dr_okonkwo", "consultant_renal_patel", "pharmacist_kwon"],
+ methods = ["zoom_call", "zoom_call", "email"],
+ contexts = [
+ "Prescribing physician MDT review",
+ "Renal consultant confirmed eGFR 28 — supports discontinuation",
+ "Clinical pharmacist approved SGLT2i initiation protocol",
+ ],
+)
+print("MDT approval chain recorded — prescription safe to issue")
+
+# Policy version history for CQC inspection
+history = engine.get_policy_history("pol-clin-001")
+print(f"Policy versions on record: {len(history)}")
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+A Basel III mortgage underwriting policy caps LTV at 85% and DSTI at 40%. The credit model checks every origination decision against this policy before booking. When the credit committee wants to raise the minimum credit score floor before the next quarter, the impact analysis shows how many approved loans in the current book would not have passed the new rule — and the audit trail for the policy change goes to the board risk committee.
+
+```python
+from semantica.context import ContextGraph, PolicyEngine, Policy, Decision
+from datetime import datetime
+
+graph = ContextGraph()
+engine = PolicyEngine(graph_store=graph)
+
+mortgage_policy = Policy(
+ policy_id = "pol-credit-001",
+ name = "Retail Mortgage Underwriting — Basel III CRE20",
+ description = "Standard residential mortgage policy aligned to Basel III CRE20",
+ rules = {
+ "max_ltv": 0.85,
+ "max_dsti": 0.40,
+ "min_credit_score": 680,
+ "required_stress_test_bps": 300,
+ "required_fields": ["ltv", "pd", "lgd", "dsti", "credit_score"],
+ "disallowed_outcomes": ["approved_ltv_over_85", "approved_dsti_over_40"],
+ "required_approvers_if_exception": ["senior_underwriter", "credit_committee"],
+ },
+ category = "credit_risk",
+ version = "2.3.0",
+ created_at = datetime.utcnow(),
+ updated_at = datetime.utcnow(),
+ metadata = {"regulatory_basis": "Basel_III_CRE20", "effective_date": "2025-01-01"},
+)
+engine.add_policy(mortgage_policy)
+
+# Borderline decision — LTV 86%, one point over the cap
+decision = Decision(
+ decision_id = "",
+ category = "mortgage_origination",
+ scenario = "APP-2025-9921: £320k mortgage, LTV 86%, DSTI 38%, credit score 710",
+ reasoning = (
+ "LTV 86% exceeds 85% cap. Stress test at +300bps passes. "
+ "Credit score 710 above 680 floor. DSTI 38% within 40% limit."
+ ),
+ outcome = "approved_ltv_over_85", # disallowed outcome — flags non-compliance
+ confidence = 0.72,
+ timestamp = datetime.utcnow(),
+ decision_maker= "underwriting_model_v4",
+)
+
+is_compliant = engine.check_compliance(decision, "pol-credit-001")
+print(f"Compliant: {is_compliant}")
+# Compliant: False — 'approved_ltv_over_85' is in disallowed_outcomes
+
+if not is_compliant:
+ exception_id = engine.record_exception(
+ decision_id = decision.decision_id,
+ policy_id = "pol-credit-001",
+ reason = "LTV 86% — one point over cap; stress test and all other metrics pass",
+ approver = "sr_underwriter_walsh",
+ justification= "Credit committee approved exception under high-quality borrower criteria §4.1",
+ )
+ print(f"Exception recorded: {exception_id}")
+
+# What-if before raising the credit score floor — present to board risk committee
+impact = engine.analyze_policy_impact(
+ policy_id = "pol-credit-001",
+ proposed_rules = {**mortgage_policy.rules, "min_credit_score": 700},
+)
+print(f"Decisions affected by raising credit score floor to 700: {impact.get('affected_decisions', 0)}")
+
+# Find all decisions made under v2.3.0 — re-audit after policy update
+affected = engine.get_affected_decisions("pol-credit-001", "2.3.0", "2.4.0")
+print(f"Decisions to re-audit: {len(affected)}")
+
+# Commit the update — version bump with full change attribution
+engine.update_policy(
+ policy_id = "pol-credit-001",
+ rules = {**mortgage_policy.rules, "min_credit_score": 700},
+ change_reason = "Credit committee Q3 review — raise score floor from 680 to 700",
+ new_version = "2.4.0",
+)
+print("Policy updated to v2.4.0")
+```
+
+</Tab>
+
+</Tabs>
+
+---
+
+## Related Guides
+
+- [Decision Intelligence](decision-intelligence) — `record_decision()`, causal chains, and precedent search — the decisions that `check_compliance()` evaluates
+- [Reasoning & Rules](reasoning) — complement policy rules with formal inference for logical conflict detection
+- [SHACL Validation](shacl-validation) — enforce structural constraints on policy nodes themselves
+- [Change Management](change-management) — version-snapshot the policy graph alongside the knowledge graph
+- [Provenance](provenance) — W3C PROV-O lineage for every policy decision and exception
+- [MCP Server](mcp-server) — expose `record_decision` and `find_precedents` as MCP tools for AI agents
diff --git a/docs/guides/provenance.md b/docs/guides/provenance.md
new file mode 100644
index 00000000..d5cf464d
--- /dev/null
+++ b/docs/guides/provenance.md
@@ -0,0 +1,577 @@
+---
+title: "Provenance & Audit Trails"
+description: "How Semantica tracks the origin and lineage of every entity, relationship, chunk, and property with W3C PROV-O compliant records — with SHA-256 integrity checksums, SQLite persistence, and cross-module audit trails for defense, pharma, banking, and security compliance."
+icon: "file-certificate"
+---
+
+`ProvenanceManager` records a W3C PROV-O compliant entry for every entity, relationship, document chunk, and property value — with a SHA-256 checksum for tamper detection and automatic version chaining on every `track_entity()` call. Use it when you need to answer regulatory questions about where a value came from, who wrote it, and whether it has changed since first ingestion.
+
+<Info>
+The KG pipeline auto-calls `track_entity()` and `track_relationship()` on everything it extracts, so entities that enter through the standard pipeline are already tracked. Use the manual API covered here when you need custom audit integrations, cross-module lineage chains, or fine-grained property-level attribution across multiple sources.
+</Info>
+
+## Setting up the provenance store
+
+`ProvenanceManager` supports two storage backends. In-memory storage is zero-dependency and useful for testing. SQLite storage persists across restarts, supports concurrent reads, and gives your compliance team a standard database they can query directly.
+
+```python
+from semantica.provenance import ProvenanceManager
+
+# In-memory — session only, no persistence
+prov = ProvenanceManager()
+
+# SQLite — persists to disk, free concurrent reads
+prov = ProvenanceManager(storage_path="provenance.db")
+
+# Custom backend — pass any ProvenanceStorage implementation
+from semantica.provenance.storage import SQLiteStorage
+prov = ProvenanceManager(storage=SQLiteStorage("audit.db"))
+```
+
+For any regulated deployment — security operations, clinical data, financial risk — use `storage_path`. A SQLite file can be backed up, versioned, and queried with standard tools without requiring a server.
+
+## Recording provenance when ingesting data
+
+The moment data enters your graph is the moment provenance must be recorded. `track_entity()` captures the source document, the timestamp, the operator or pipeline that ran the extraction, a verbatim quote from the source, and a confidence score. It returns a `ProvenanceEntry` with a SHA-256 checksum computed automatically.
+
+```python
+# Ingesting CVE-2024-3400 from NVD and a commercial feed
+# Both are tracked separately so the full multi-source picture is preserved.
+
+entry_nvd = prov.track_entity(
+ entity_id="cve-2024-3400",
+ source="NVD_feed_2024-04-12",
+ metadata={
+ "cvss_score": 10.0,
+ "vector": "AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H",
+ "exploit_status": "unconfirmed",
+ },
+ confidence=0.98,
+ entity_type="vulnerability",
+ activity_id="nvd_feed_ingestion",
+ source_location="CVE-2024-3400 JSON record",
+ source_quote='{"cvssMetricV31":[{"cvssData":{"baseScore":10.0}}]}',
+ agent_id="nvd_ingest_pipeline_v2",
+)
+
+print(f"Entity tracked : {entry_nvd.entity_id}")
+print(f"Source : {entry_nvd.source_document}")
+print(f"Timestamp : {entry_nvd.timestamp}")
+print(f"Checksum : {entry_nvd.checksum}") # SHA-256 hex digest
+print(f"First seen : {entry_nvd.first_seen}") # set on first call only
+```
+
+```text
+Entity tracked : cve-2024-3400
+Source : NVD_feed_2024-04-12
+Timestamp : 2024-04-12T14:22:07.881Z
+Checksum : 3f7a9c2d... # tamper-detectable
+First seen : 2024-04-12T14:22:07.881Z
+```
+
+Now track the same entity arriving from the commercial feed an hour later. Calling `track_entity()` again on the same `entity_id` automatically archives the NVD entry as a history record and creates a new current entry linked to it via `parent_entity_id`:
+
+```python
+entry_commercial = prov.track_entity(
+ entity_id="cve-2024-3400",
+ source="commercial_feed_2024-04-12",
+ metadata={
+ "cvss_score": 9.8,
+ "exploit_status": "in_wild",
+ "observed_exploitation": True,
+ },
+ confidence=0.91,
+ entity_type="vulnerability",
+ activity_id="commercial_feed_ingestion",
+ agent_id="threat_ingest_pipeline_v2",
+)
+
+# The NVD entry is now archived as cve-2024-3400:v:2024-04-12T14:22:07
+# The commercial entry is the new current state
+# entry_commercial.parent_entity_id == "cve-2024-3400:v:2024-04-12T14:22:07"
+```
+
+This version chaining happens automatically. You do not need to manage history entries manually.
+
+## Tracking multi-source property values
+
+When the same property appears in multiple sources with different values — exactly the CVE score situation — use `track_property_source()` to record each attribution separately. This feeds directly into conflict detection downstream: the conflict module can compare all tracked values for a property and surface disagreements with full source metadata attached.
+
+```python
+from semantica.provenance.schemas import SourceReference
+
+nvd_ref = SourceReference(
+ document="NVD_feed_2024-04-12",
+ section="cvssMetricV31",
+ confidence=0.98,
+ metadata={"publisher": "NIST", "feed_type": "NVD"},
+)
+
+commercial_ref = SourceReference(
+ document="commercial_feed_2024-04-12",
+ section="cvss_assessment",
+ confidence=0.91,
+ metadata={"publisher": "ThreatFeed-Co", "observed": True},
+)
+
+# Track each source's value separately under the same entity + property key
+prov.track_property_source("cve-2024-3400", "cvss_score", 10.0, nvd_ref)
+prov.track_property_source("cve-2024-3400", "cvss_score", 9.8, commercial_ref)
+
+# Property sources are stored under "<entity_id>_<property_name>"
+# Later: retrieve all sources for this property to answer "where did 9.8 come from?"
+sources = prov.get_all_sources("cve-2024-3400_cvss_score")
+for s in sources:
+ print(f"{s['source']:<35} confidence={s['confidence']:.2f} loc={s['location'] or '—'}")
+```
+
+```text
+NVD_feed_2024-04-12 confidence=0.98 loc=cvssMetricV31
+commercial_feed_2024-04-12 confidence=0.91 loc=cvss_assessment
+```
+
+When the regulator asks "where did the 9.8 come from?", this is the answer: `commercial_feed_2024-04-12`, section `cvss_assessment`, confidence 0.91, with full metadata showing it was a commercial publisher that reported observed exploitation.
+
+## Tracing the lineage of a node
+
+Six months after ingestion, run a lineage trace. `get_lineage()` returns the full version chain — every state the entity has passed through, oldest to newest — along with summary metadata:
+
+```python
+lineage = prov.get_lineage("cve-2024-3400")
+
+print(f"Entity : {lineage['entity_id']}")
+print(f"First seen : {lineage['first_seen']}")
+print(f"Last updated: {lineage['last_updated']}")
+print(f"History depth: {lineage['entity_count']} entries")
+print(f"Sources seen : {lineage['source_documents']}")
+print()
+print("Full version chain (oldest → newest):")
+for entry in lineage["lineage_chain"]:
+ print(f" [{entry['timestamp'][:19]}] agent={entry['agent_id']}")
+ print(f" source={entry['source_document']}")
+ print(f" activity={entry['activity_id']}")
+```
+
+```text
+Entity : cve-2024-3400
+First seen : 2024-04-12T14:22:07.881Z
+Last updated: 2024-10-08T09:11:44.302Z
+History depth: 4 entries
+Sources seen : ['NVD_feed_2024-04-12', 'commercial_feed_2024-04-12',
+ 'NVD_feed_2024-07-18', 'commercial_feed_2024-10-08']
+
+Full version chain (oldest → newest):
+ [2024-04-12T14:22:07] agent=nvd_ingest_pipeline_v2
+ source=NVD_feed_2024-04-12
+ activity=nvd_feed_ingestion
+ [2024-04-12T15:18:33] agent=threat_ingest_pipeline_v2
+ source=commercial_feed_2024-04-12
+ activity=commercial_feed_ingestion
+ [2024-07-18T08:04:11] agent=nvd_ingest_pipeline_v2
+ source=NVD_feed_2024-07-18
+ activity=nvd_feed_ingestion # NVD updated their score
+ [2024-10-08T09:11:44] agent=threat_ingest_pipeline_v2
+ source=commercial_feed_2024-10-08
+ activity=commercial_feed_ingestion
+```
+
+The chain answers all three of the regulator's questions. The 9.8 came from `commercial_feed_2024-04-12`. The operator was `threat_ingest_pipeline_v2`. The score has changed — NVD updated their record on July 18 — and the chain shows exactly when.
+
+## Verifying integrity
+
+Every `ProvenanceEntry` carries a SHA-256 checksum computed at write time. If any field is modified after the fact — by a misconfigured pipeline, a database migration, or deliberate tampering — the checksum will not match on recomputation. Run integrity checks as part of any compliance audit:
+
+```python
+from semantica.provenance.integrity import compute_checksum
+
+raw_entries = prov.trace_lineage("cve-2024-3400")
+
+print("Integrity check:")
+for e in raw_entries:
+ stored = e.checksum
+ computed = compute_checksum(e)
+ status = "OK" if stored == computed else "TAMPERED"
+ print(f" [{status}] {e.entity_id[:50]} {(stored or '')[:16]}...")
+```
+
+```text
+Integrity check:
+ [OK] cve-2024-3400 3f7a9c2d...
+ [OK] cve-2024-3400:v:2024-04-12T14:22:07 a1b2c3d4...
+ [OK] cve-2024-3400:v:2024-04-12T15:18:33 e5f6a7b8...
+ [OK] cve-2024-3400:v:2024-07-18T08:04:11 c9d0e1f2...
+```
+
+A `TAMPERED` status means the stored hash does not match what would be computed from the current field values — evidence of post-write modification that must be investigated before the record is used for compliance purposes.
+
+## Tracking document chunks and their children
+
+Provenance is not just for entities. When a document is split into chunks for RAG or NLP processing, each chunk needs its own provenance record linking it to the source file and byte range. Child chunks (from recursive splitting) link to their parent via `parent_chunk_id`, which maps to `prov:wasDerivedFrom` in the W3C model:
+
+```python
+# Track the parent chunk (a section of an advisory PDF)
+prov.track_chunk(
+ chunk_id="advisory_section_3",
+ source_document="CISA_advisory_AA24-099A.pdf",
+ source_path="/feeds/cisa/advisories/AA24-099A.pdf",
+ start_index=4096,
+ end_index=8192,
+)
+
+# Track a child chunk derived from recursive splitting
+prov.track_chunk(
+ chunk_id="advisory_section_3a",
+ source_document="CISA_advisory_AA24-099A.pdf",
+ source_path="/feeds/cisa/advisories/AA24-099A.pdf",
+ start_index=4096,
+ end_index=6144,
+ parent_chunk_id="advisory_section_3", # prov:wasDerivedFrom
+)
+
+# Retrieve the provenance record for a chunk
+record = prov.get_provenance("advisory_section_3a")
+if record:
+ print(f"Source : {record['source_document']}")
+ print(f"Range : bytes {record['start_index']}–{record['end_index']}")
+ print(f"Parent : {record['parent_entity_id']}") # advisory_section_3
+ print(f"Checksum : {record['checksum']}")
+```
+
+For GDPR right-of-erasure workflows, the byte range in each chunk's provenance record tells you exactly which part of which document to delete when a data subject makes a deletion request.
+
+## Statistics across the provenance store
+
+After a large ingestion run, `get_statistics()` gives a summary of everything tracked:
+
+```python
+stats = prov.get_statistics()
+
+print(f"Total tracked : {stats['total_entries']}")
+print(f"By entity type : {stats['entity_types']}")
+print(f"Unique sources : {stats['unique_sources']}")
+```
+
+```text
+Total tracked : 14,822
+By entity type : {'vulnerability': 3041, 'chunk': 8204, 'relationship': 2891,
+ 'property': 686}
+Unique sources : 12
+```
+
+This summary is the starting point for a compliance attestation: you can state the total number of tracked records, the number of distinct data sources, and the breakdown by record type.
+
+## Domain examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+A signals intelligence fusion cell tracks custody of every intelligence entity from raw collection through analytic processing to finished product. Each tier of the chain — raw collection, NER extraction, fusion, and finished intelligence — must be recorded separately with the appropriate classification handling and operator identity. The provenance chain is the chain of custody: it proves that a finished intelligence product is traceable to authorized collection and authorized analysis at every step.
+
+Under ITAR and intelligence community sharing agreements, the provenance record must show which collection method produced the raw data, which analyst processed it, and which fusion activity combined it with other intelligence before the entity reached the finished product. `track_chunk()`, `track_entity()`, and `track_relationship()` each correspond to one tier of that chain.
+
+```python
+from semantica.provenance import ProvenanceManager
+from semantica.provenance.schemas import SourceReference
+
+prov = ProvenanceManager(storage_path="intel_provenance.db")
+
+# Tier 1: Raw collection
+prov.track_chunk(
+ chunk_id="osint_collection_20260621_0442Z",
+ source_document="COLLECTION_TASKING_TK-2026-0192",
+ source_path="/osint/raw/20260621_0442Z.txt",
+ start_index=0,
+ end_index=2048,
+ classification="UNCLASSIFIED//FOUO",
+ collection_method="OSINT",
+ collector_id="STATION_ECHO",
+)
+
+# Tier 2: Entity extracted from collection
+prov.track_entity(
+ entity_id="threat_actor_DELTA9",
+ source="osint_collection_20260621_0442Z",
+ metadata={"label": "THREAT_ACTOR", "confidence_level": "C2"},
+ confidence=0.87,
+ entity_type="threat_actor",
+ activity_id="ner_extraction",
+ source_location="paragraph_3",
+ agent_id="analyst_ALPHA",
+)
+
+# Tier 3: Campaign relationship from all-source fusion
+prov.track_relationship(
+ relationship_id="DELTA9_operates_CAMPAIGN_IRON",
+ source="FUSION_REPORT_FP-2026-0447",
+ metadata={"type": "operates", "confidence": 0.81},
+ confidence=0.81,
+ activity_id="all_source_fusion",
+ agent_id="fusion_cell_BRAVO",
+)
+
+# Tier 4: Property from two independent INT sources
+humint_src = SourceReference(
+ document="HUMINT_REPORT_HR-2026-0821",
+ confidence=0.91,
+ metadata={"classification": "SECRET", "source_country": "PARTNER_5EYES"},
+)
+imint_src = SourceReference(
+ document="IMINT_PRODUCT_IP-2026-1104",
+ page=3,
+ section="Ground Truth Assessment",
+ confidence=0.87,
+ metadata={"sensor": "OPIR", "resolution_m": 0.3},
+)
+prov.track_property_source("DELTA9", "location_country", "COUNTRY_X", humint_src)
+prov.track_property_source("DELTA9", "location_country", "COUNTRY_X", imint_src)
+
+# Finished product audit — full chain of custody
+lineage = prov.get_lineage("threat_actor_DELTA9")
+print("Chain of custody:")
+for entry in lineage["lineage_chain"]:
+ print(f" [{entry['timestamp'][:19]}] {entry['activity_id']} agent={entry['agent_id']}")
+
+# Corroborating INT sources for the location assessment
+sources = prov.get_all_sources("DELTA9_location_country")
+for s in sources:
+ print(f" INT source: {s['source']} (conf={s['confidence']:.2f})")
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+A SOC threat intelligence platform tracks every CVE from its first NVD ingestion through enrichment runs, CVSS updates, and analyst annotations. The provenance chain answers the question that matters most during incident response: "Is this vulnerability record current, and has the CVSS score been revised since we last checked?"
+
+The version chain created by repeated `track_entity()` calls on the same `entity_id` gives you a complete update history. If NVD revised a score from 7.5 to 9.8 following a proof-of-concept release, the chain shows the exact timestamp of that revision and which pipeline wrote the updated value.
+
+```python
+from semantica.provenance import ProvenanceManager
+from semantica.provenance.schemas import SourceReference
+from semantica.provenance.integrity import compute_checksum
+
+prov = ProvenanceManager(storage_path="soc_provenance.db")
+
+# Initial NVD ingestion
+prov.track_entity(
+ entity_id="cve-2023-44487",
+ source="NVD_feed_2023-10-10",
+ metadata={"cvss_score": 7.5, "description": "HTTP/2 Rapid Reset DDoS"},
+ confidence=0.98,
+ entity_type="vulnerability",
+ activity_id="nvd_feed_ingestion",
+ agent_id="ingest_pipeline_v2",
+)
+
+# Six weeks later: NVD revised the score after PoC publication
+prov.track_entity(
+ entity_id="cve-2023-44487",
+ source="NVD_feed_2023-11-22",
+ metadata={"cvss_score": 7.5, "kev_added": True, "known_exploited": True},
+ confidence=0.98,
+ entity_type="vulnerability",
+ activity_id="nvd_feed_update",
+ agent_id="ingest_pipeline_v2",
+)
+
+# Track CISA KEV addition as a separate property source
+kev_ref = SourceReference(
+ document="CISA_KEV_catalog_2023-11-22",
+ section="Known Exploited Vulnerabilities",
+ confidence=1.0,
+ metadata={"publisher": "CISA", "mandatory_remediation": True},
+)
+prov.track_property_source("cve-2023-44487", "known_exploited", True, kev_ref)
+
+# Incident response query: full history for this CVE
+lineage = prov.get_lineage("cve-2023-44487")
+print(f"CVE first seen : {lineage['first_seen'][:10]}")
+print(f"CVE last updated: {lineage['last_updated'][:10]}")
+print(f"Update count : {lineage['entity_count']} records")
+
+# Integrity check before relying on the record for a patch decision
+entries = prov.trace_lineage("cve-2023-44487")
+for e in entries:
+ ok = compute_checksum(e) == e.checksum
+ print(f" [{('OK' if ok else 'TAMPERED')}] {e.timestamp[:19]} source={e.source_document}")
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+A clinical evidence graph tracks efficacy data from source publications through structured extraction to regulatory submission. The W3C PROV-O chain satisfies ICH E6(R2) GCP requirements for data traceability and 21 CFR Part 11 requirements for electronic record integrity. Every entity in the submission package must be traceable to a source document, an extraction activity, and an operator.
+
+`track_property_source()` is particularly important here: when two independent studies report different efficacy values for the same endpoint, each must be tracked separately with full citation metadata. The resulting multi-source record is the evidence base for a meta-analysis, and the provenance entries become the supporting documentation in the regulatory dossier.
+
+```python
+from semantica.provenance import ProvenanceManager
+from semantica.provenance.schemas import SourceReference
+from semantica.provenance.integrity import compute_checksum
+
+prov = ProvenanceManager(storage_path="clinical_provenance.db")
+
+# Track the source document chunk (Phase III study report section)
+prov.track_chunk(
+ chunk_id="phase3_primary_endpoint_C4591001",
+ source_document="STUDY_REPORT_BNT162b2_C4591001_MOD2",
+ source_path="/submissions/EMA_rolling_review/mod2_clinical_overview.pdf",
+ start_index=4096,
+ end_index=6144,
+ study_phase="Phase_III",
+ ctgov="NCT04368728",
+ sponsor="BioNTech_Pfizer",
+)
+
+# Track extracted efficacy entity with verbatim source quote
+prov.track_entity(
+ entity_id="VE_primary_BNT162b2_C4591001",
+ source="phase3_primary_endpoint_C4591001",
+ metadata={"value": "95.0%", "CI_95": "[90.3–97.6]", "label": "EFFICACY_MEASURE"},
+ confidence=0.99,
+ entity_type="clinical_endpoint",
+ activity_id="structured_data_extraction",
+ source_quote="Vaccine efficacy against COVID-19 was 95.0% (95% CI, 90.3–97.6)",
+ agent_id="meddra_extraction_pipeline_v3",
+)
+
+# Multi-study property tracking for meta-analysis
+study1 = SourceReference(
+ document="NEJM_doi_10.1056_NEJMoa2034577",
+ page=9, section="Table 2",
+ confidence=0.99,
+ metadata={"study_id": "C4591001", "n_participants": 43448},
+)
+study2 = SourceReference(
+ document="Lancet_doi_10.1016_S0140-6736_21_00448-7",
+ page=6, section="Results",
+ confidence=0.97,
+ metadata={"study_id": "EXT_COHORT", "n_participants": 9119},
+)
+prov.track_property_source("BNT162b2", "vaccine_efficacy_symptomatic_covid19", "95.0", study1)
+prov.track_property_source("BNT162b2", "vaccine_efficacy_symptomatic_covid19", "94.1", study2)
+
+# Regulatory submission audit — evidence chain
+lineage = prov.get_lineage("VE_primary_BNT162b2_C4591001")
+print("Evidence chain for regulatory submission:")
+for entry in lineage["lineage_chain"]:
+ print(f" {entry['timestamp'][:10]} | {entry['source_document'][:45]} | "
+ f"agent={entry['agent_id']}")
+
+# Integrity verification (21 CFR Part 11 requirement)
+entries = prov.trace_lineage("VE_primary_BNT162b2_C4591001")
+for e in entries:
+ status = "OK" if compute_checksum(e) == e.checksum else "TAMPERED"
+ print(f" Integrity [{status}]: {e.entity_id}")
+
+stats = prov.get_statistics()
+print(f"\nTotal evidence records in dossier: {stats['total_entries']}")
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+A mortgage origination system records full provenance for every credit decision, satisfying SR 11-7 model risk management guidelines and EBA model documentation requirements. Every feature used in the underwriting model — credit score, DTI ratio, property valuation — must be traceable to its source data pull, the operator that ran the model, and the timestamp of the decision.
+
+Property valuation is tracked from two sources (RICS appraisal and AVM estimate) using `track_property_source()`, giving the compliance team a complete picture of how the LTV was calculated and which valuation method the model ultimately relied on.
+
+```python
+from semantica.provenance import ProvenanceManager
+from semantica.provenance.schemas import SourceReference
+
+prov = ProvenanceManager(storage_path="credit_provenance.db")
+app_id = "APP-2026-994421"
+
+# Track the bureau data pull
+prov.track_chunk(
+ chunk_id=f"{app_id}_bureau_pull",
+ source_document=f"EXPERIAN_CREDITEXPERT_{app_id}_2026-06-21",
+ source_path=f"/bureau/experian/{app_id}/2026-06-21.json",
+ start_index=0,
+ end_index=4096,
+ bureau="Experian",
+ pull_timestamp="2026-06-21T09:14:32Z",
+ consent_ref=f"CONSENT-{app_id}",
+)
+
+# Batch-track extracted credit features
+features = [
+ {"id": f"{app_id}_credit_score", "confidence": 1.0, "value": 714},
+ {"id": f"{app_id}_dti_ratio", "confidence": 1.0, "value": 0.38},
+ {"id": f"{app_id}_derogatory_count_7yr", "confidence": 1.0, "value": 0},
+]
+prov.track_entities_batch(
+ features,
+ source=f"{app_id}_bureau_pull",
+ entity_type="credit_feature",
+ activity_id="bureau_parsing",
+ agent_id="credit_data_service_v2",
+)
+
+# Track competing property valuations
+rics_val = SourceReference(
+ document=f"RICS_VALUATION_{app_id}_2026-06-18",
+ page=3, section="Market Value Assessment",
+ confidence=0.96,
+ metadata={"valuer": "JLL_Residential", "method": "comparable_sales"},
+)
+avm_val = SourceReference(
+ document=f"AVM_ESTIMATE_{app_id}_2026-06-21",
+ confidence=0.84,
+ metadata={"provider": "Hometrack_AVM", "model_version": "v8.3"},
+)
+prov.track_property_source(app_id, "property_value_GBP", "410000", rics_val)
+prov.track_property_source(app_id, "property_value_GBP", "403500", avm_val)
+
+# Track the underwriting decision itself
+prov.track_entity(
+ entity_id=f"DECISION_{app_id}",
+ source=f"{app_id}_bureau_pull",
+ metadata={"outcome": "approved_conditional_lmi", "model": "underwriting_model_v4"},
+ confidence=0.89,
+ entity_type="credit_decision",
+ activity_id="automated_underwriting",
+ agent_id="underwriting_model_v4",
+)
+
+# SR 11-7 audit output
+print("=== MODEL AUDIT TRAIL ===")
+lineage = prov.get_lineage(f"DECISION_{app_id}")
+for entry in lineage["lineage_chain"]:
+ print(f" [{entry['timestamp'][:19]}] {entry['activity_id']} agent={entry['agent_id']}")
+
+print("\n=== PROPERTY VALUATION SOURCES ===")
+for s in prov.get_all_sources(f"{app_id}_property_value_GBP"):
+ print(f" {s['source'][:55]} conf={s['confidence']:.2f}")
+
+stats = prov.get_statistics()
+print(f"\nTotal audit records: {stats['total_entries']} | Sources: {stats['unique_sources']}")
+```
+
+</Tab>
+
+</Tabs>
+
+## The W3C PROV-O mapping
+
+Every `ProvenanceEntry` maps directly to W3C PROV-O terms. If your compliance team or a regulator requires a PROV-O export, the field mapping is one-to-one:
+
+| PROV-O Term | `ProvenanceEntry` field | What it records |
+| :--- | :--- | :--- |
+| `prov:Entity` | `entity_id` | The tracked object — entity, chunk, relationship, or property |
+| `prov:Activity` | `activity_id` | The process that produced it — `"ner_extraction"`, `"bureau_parsing"` |
+| `prov:Agent` | `agent_id` | Who ran the activity — pipeline name, analyst ID |
+| `prov:wasDerivedFrom` | `parent_entity_id` | The previous version of this entity — enables version chaining |
+| `prov:used` | `used_entities` | Entity IDs consumed to produce this one |
+| `prov:generatedAtTime` | `timestamp` | ISO datetime, auto-set to `datetime.utcnow()` at write time |
+
+The `checksum` field is not part of the PROV-O standard — it is Semantica's tamper-detection extension. Every entry's SHA-256 is computed from its content fields at write time and can be recomputed at any time to verify the record has not been modified.
+
+## Related Guides
+
+- [Semantic Extraction](semantic-extraction) — the NER and relation extraction pipeline that auto-generates provenance entries for every extracted entity
+- [Conflict Resolution](conflict-resolution) — provenance property sources feed directly into conflict detection; every resolved value is traceable to its source
+- [Deduplication](deduplication) — merge operations are recorded in merge history; pair with provenance for a complete lineage from source to canonical entity
+- [Provenance Reference](../reference/provenance) — full storage backend API, `InMemoryStorage`, `SQLiteStorage`, and `ProvenanceEntry` schema
diff --git a/docs/guides/reasoning.md b/docs/guides/reasoning.md
new file mode 100644
index 00000000..8898fdf6
--- /dev/null
+++ b/docs/guides/reasoning.md
@@ -0,0 +1,766 @@
+---
+title: "Reasoning & Rules"
+description: "Apply forward-chaining, backward-chaining, Datalog, SPARQL, RETE, temporal interval, and LLM-based reasoning over your knowledge graph — derive new facts, check constraints, and explain inferences."
+---
+
+Semantica's reasoning layer encodes domain logic as rules and applies it to your knowledge graph to derive conclusions that no single document states explicitly. Eight complementary reasoning modes — from symbol-rule forward chaining to recursive Datalog and LLM-backed freeform queries — let you choose the right tool for each inference problem without switching frameworks.
+
+<Info>
+The reasoning module operates over facts you supply directly or load from a `ContextGraph`. Derived facts are added to working memory and are immediately available for further inference in the same session. To persist derived facts back into the graph, pass them to `AgentContext.store()`.
+</Info>
+
+## Choosing a reasoning mode
+
+| Mode | Best for | Class |
+|---|---|---|
+| Forward chaining | Materialise all implied facts from ground truth | `Reasoner.forward_chain()` |
+| Backward chaining | Prove a specific goal; get the minimal evidence chain | `Reasoner.backward_chain()` |
+| Datalog | Recursive traversal of arbitrary depth (supply chains, org graphs) | `DatalogReasoner` |
+| SPARQL | Pattern-matching queries over enriched working memory | `SPARQLReasoner` |
+| RETE | 100+ rule sets — incremental fact propagation via alpha/beta network | `ReteEngine` |
+| Temporal | Allen interval relations between time windows | `TemporalReasoningEngine` |
+| Natural language | LLM-backed freeform queries over graph context | `GraphReasoner` |
+| Explanation | Translate inference results into human-readable justifications | `ExplanationGenerator` |
+
+## Step 1 — Ground facts and working memory
+
+The `Reasoner` class maintains a set of ground facts and a list of rules. Facts can be added as predicate strings or loaded from a `ContextGraph`. Start with the explicit knowledge your extraction pipeline produced:
+
+```python
+from semantica.reasoning import Reasoner, Rule, RuleType
+
+reasoner = Reasoner()
+
+# Ground facts: Predicate(arg) or Predicate(arg1, arg2)
+reasoner.add_fact("ThreatActor(APT29)")
+reasoner.add_fact("ThreatActor(GAMMA-7)")
+reasoner.add_fact("ThreatActor(DELTA-3)")
+reasoner.add_fact("Exploits(APT29, CVE-2025-3400)")
+reasoner.add_fact("Exploits(GAMMA-7, CVE-2025-1234)")
+reasoner.add_fact("Exploits(GAMMA-7, CVE-2025-5678)")
+reasoner.add_fact("CriticalVuln(CVE-2025-3400)")
+reasoner.add_fact("CriticalVuln(CVE-2025-1234)")
+reasoner.add_fact("CriticalVuln(CVE-2025-5678)")
+reasoner.add_fact("Targets(APT29, NATOLogistics)")
+reasoner.add_fact("Targets(GAMMA-7, NATOLogistics)")
+reasoner.add_fact("SuppliedExploits(DELTA-3, GAMMA-7)")
+reasoner.add_fact("SectorOverlap(NATOLogistics, CriticalInfrastructure)")
+```
+
+These ground facts represent what documents explicitly stated. The rules you add next tell the system what those facts *imply*.
+
+## Step 2 — Forward chaining: materialising derived facts
+
+Forward chaining starts from ground facts and applies every matching rule until no new conclusions can be drawn — reaching fixpoint:
+
+```python
+# String-format rules are parsed automatically
+# Variables are single uppercase letters or multi-character uppercase words
+reasoner.add_rule(
+ "IF ThreatActor(X) AND Exploits(X, Y) AND CriticalVuln(Y) THEN HighRiskActor(X)"
+)
+reasoner.add_rule(
+ "IF HighRiskActor(X) AND Targets(X, Z) THEN CriticalTarget(Z)"
+)
+reasoner.add_rule(
+ "IF SuppliedExploits(A, B) AND HighRiskActor(B) THEN HighRiskSupplier(A)"
+)
+
+# forward_chain() applies all rules until fixpoint
+derived = reasoner.forward_chain()
+
+for result in derived:
+ print("{:<40s} conf={:.0%} rule={}".format(
+ result.conclusion,
+ result.confidence,
+ result.rule_used.name if result.rule_used else "n/a",
+ ))
+```
+
+```text
+HighRiskActor(APT29) conf=100% rule=Rule 1
+HighRiskActor(GAMMA-7) conf=100% rule=Rule 1
+CriticalTarget(NATOLogistics) conf=100% rule=Rule 2
+HighRiskSupplier(DELTA-3) conf=100% rule=Rule 3
+```
+
+DELTA-3 is flagged even though no document described it that way — the system traced: DELTA-3 supplied GAMMA-7, and GAMMA-7 exploits critical CVEs. For rules that need priority ordering or graded confidence, use the `Rule` dataclass:
+
+```python
+# Higher priority rules fire first; confidence propagates into InferenceResult.confidence
+reasoner.add_rule(Rule(
+ rule_id="attr-1",
+ name="ttp_match_attribution",
+ conditions=["ThreatActor(X)", "Exploits(X, CVE)", "CriticalVuln(CVE)"],
+ conclusion="HighRiskActor(X)",
+ rule_type=RuleType.IMPLICATION,
+ confidence=0.92,
+ priority=10,
+))
+
+reasoner.add_rule(Rule(
+ rule_id="attr-2",
+ name="supplier_elevation",
+ conditions=["SuppliedExploits(A, B)", "HighRiskActor(B)"],
+ conclusion="HighRiskSupplier(A)",
+ rule_type=RuleType.IMPLICATION,
+ confidence=0.85,
+ priority=5,
+))
+```
+
+## Step 3 — Backward chaining: proving a specific goal
+
+Backward chaining tests a single hypothesis by working backward through rules — the right tool when you need a yes/no answer and the minimal evidence chain without deriving every other possible fact first:
+
+```python
+# backward_chain() returns an InferenceResult if the goal is provable, None otherwise
+result = reasoner.backward_chain("HighRiskSupplier(DELTA-3)", max_depth=5)
+
+if result:
+ print("Proved: {}".format(result.conclusion))
+ print("Via premises:")
+ for p in result.premises:
+ print(" - {}".format(p))
+ print("Confidence: {:.0%}".format(result.confidence))
+else:
+ print("Goal not provable — DELTA-3 is not classified as a high-risk supplier "
+ "given current facts and rules")
+```
+
+```text
+Proved: HighRiskSupplier(DELTA-3)
+Via premises:
+ - SuppliedExploits(DELTA-3, GAMMA-7)
+ - HighRiskActor(GAMMA-7)
+Confidence: 85%
+```
+
+The premises list is the explanation chain — each item is a fact that was necessary to reach the conclusion. Show this to analysts when they ask "why is DELTA-3 classified as high-risk?"
+
+## Step 4 — Recursive inference with Datalog
+
+`DatalogReasoner` handles questions requiring arbitrary-depth traversal — "which actors can transitively reach critical infrastructure?" — using recursive Horn clause rules with semi-naive bottom-up fixpoint evaluation:
+
+```python
+from semantica.reasoning import DatalogReasoner
+
+dl = DatalogReasoner()
+
+# EDB (Extensional DB) — base facts; arguments are constants (lowercase)
+dl.add_fact("supplied(delta3, gamma7)")
+dl.add_fact("supplied(gamma7, apt29_affiliate)")
+dl.add_fact("supplied(apt29_affiliate, apt29)")
+dl.add_fact("targets(apt29, nato_logistics)")
+dl.add_fact("targets(gamma7, nato_logistics)")
+dl.add_fact("sector(nato_logistics, critical_infrastructure)")
+
+# IDB (Intensional DB) — recursive rules; uppercase = variable
+# Base case: direct supply link
+dl.add_rule("reaches(X, Y) :- supplied(X, Y).")
+# Recursive case: X reaches Y if X supplies Z and Z reaches Y
+dl.add_rule("reaches(X, Y) :- supplied(X, Z), reaches(Z, Y).")
+
+# Derived predicate combining reachability with sector membership
+dl.add_rule("sector_exposure(Actor, Sector) :- reaches(Actor, Target), sector(Target, Sector).")
+dl.add_rule("sector_exposure(Actor, Sector) :- targets(Actor, Target), sector(Target, Sector).")
+
+# derive_all() runs semi-naive fixpoint until no new facts emerge
+dl.derive_all()
+
+# Query with free variables — returns list of binding dicts
+exposures = dl.query("sector_exposure(?actor, critical_infrastructure)")
+for row in exposures:
+ print("CI-exposed actor: {}".format(row["actor"]))
+```
+
+```text
+CI-exposed actor: delta3
+CI-exposed actor: gamma7
+CI-exposed actor: apt29_affiliate
+CI-exposed actor: apt29
+```
+
+DELTA-3 appears even though no document connects it directly to critical infrastructure. Datalog traced the full chain: delta3 → gamma7 → apt29_affiliate → apt29 → nato_logistics → critical_infrastructure.
+
+Bind variables to ask directed questions:
+
+```python
+# Which sectors does delta3 have exposure to?
+rows = dl.query("sector_exposure(delta3, ?sector)")
+for row in rows:
+ print("delta3 → sector: {}".format(row["sector"]))
+```
+
+Skip manual `add_fact()` calls by loading a `ContextGraph` directly:
+
+```python
+from semantica.context import ContextGraph
+
+graph = ContextGraph()
+# ... graph populated by AgentContext.store() or extraction pipeline ...
+count = dl.load_from_graph(graph)
+print("Loaded {} facts from graph".format(count))
+```
+
+## Step 5 — SPARQL queries over enriched working memory
+
+After forward chaining has derived new facts, `SPARQLReasoner` lets you query the enriched working memory using SPARQL triple-pattern matching with optional inference expansion:
+
+```python
+from semantica.reasoning import SPARQLReasoner
+
+sparql = SPARQLReasoner()
+
+# Inference rules expand the SPARQL query before execution
+sparql.add_inference_rule(
+ "IF ThreatActor(X) AND Exploits(X, Y) AND CriticalVuln(Y) THEN HighRiskActor(X)"
+)
+
+query = """
+ SELECT ?actor ?cve WHERE {
+ ?actor <Exploits> ?cve .
+ ?cve <CriticalVuln> true .
+ }
+"""
+
+# execute_query() runs: expansion → inference → deduplication
+result = sparql.execute_query(query)
+
+for binding in result.bindings:
+ print("Actor: {:15s} CVE: {}".format(
+ binding.get("actor", "?"),
+ binding.get("cve", "?"),
+ ))
+
+# metadata shows how many results came from inference vs ground facts
+print("Original: {} Inferred: {}".format(
+ result.metadata.get("original_count", 0),
+ result.metadata.get("inferred_count", 0),
+))
+```
+
+Inspect the expanded query before running it:
+
+```python
+# See the query after inference rules are applied
+expanded = sparql.expand_query(query)
+print(expanded)
+```
+
+## Step 6 — RETE engine for large rule sets
+
+`ReteEngine` implements the RETE algorithm — a network of alpha nodes (single-condition matching) and beta nodes (join operations) that avoids re-evaluating unchanged conditions on every new fact. Use it when you have 100+ rules or need incremental fact propagation in a streaming or event-driven setting:
+
+```python
+from semantica.reasoning import ReteEngine, Rule, RuleType, Fact
+
+# Define rules as Rule objects — same Rule class used by Reasoner
+rules = [
+ Rule(
+ rule_id="r1", name="port_scan_detected",
+ conditions=["PortScan(Source)", "HighFrequency(Source)"],
+ conclusion="Scanning(Source)",
+ confidence=0.90, priority=10,
+ ),
+ Rule(
+ rule_id="r2", name="c2_beacon_identified",
+ conditions=["Scanning(Source)", "BeaconPattern(Source, Dest)"],
+ conclusion="C2Channel(Source, Dest)",
+ confidence=0.85, priority=8,
+ ),
+ Rule(
+ rule_id="r3", name="lateral_movement_detected",
+ conditions=["C2Channel(Source, Dest)", "InternalHost(Dest)"],
+ conclusion="LateralMovement(Source, Dest)",
+ confidence=0.80, priority=5,
+ ),
+]
+
+engine = ReteEngine()
+engine.build_network(rules) # compile rules into alpha/beta/terminal node network
+
+# Facts are structured: Fact(fact_id, predicate, [arguments])
+engine.add_fact(Fact("f1", "PortScan", ["192.168.1.50"]))
+engine.add_fact(Fact("f2", "HighFrequency", ["192.168.1.50"]))
+engine.add_fact(Fact("f3", "BeaconPattern", ["192.168.1.50", "10.0.0.5"]))
+engine.add_fact(Fact("f4", "InternalHost", ["10.0.0.5"]))
+
+# match_patterns() returns Match objects: rule + matched facts + confidence
+matches = engine.match_patterns()
+print("Rule activations: {}".format(len(matches)))
+
+# execute_matches() fires each matched rule and returns the derived conclusions
+conclusions = engine.execute_matches(matches)
+for c in conclusions:
+ print("Derived:", c)
+
+# Network diagnostics — useful for verifying rule compilation
+stats = engine.get_network_stats()
+print("Nodes: {total_nodes} Alpha: {alpha_nodes} Beta: {beta_nodes} Facts: {facts}".format(**stats))
+
+# Clear working memory without recompiling the rule network
+engine.reset()
+```
+
+The rule network is compiled once by `build_network()`. Each subsequent `add_fact()` call propagates incrementally through only the nodes whose conditions it satisfies — not the full rule set — which keeps evaluation cost proportional to the number of new activations rather than the total rule count.
+
+## Step 7 — Temporal interval reasoning
+
+`TemporalReasoningEngine` computes Allen interval relations between time windows, letting you identify whether two events overlap, one contains the other, they meet at a boundary, and so on across your graph:
+
+```python
+from datetime import datetime, timezone
+from semantica.reasoning import TemporalReasoningEngine, TemporalInterval, IntervalRelation
+
+engine = TemporalReasoningEngine()
+
+def dt(value: str) -> datetime:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
+
+# Encode time windows as datetimes
+nightfall = TemporalInterval(start=dt("2025-01-01T00:00:00Z"), end=dt("2025-03-31T23:59:59Z"))
+sandstorm = TemporalInterval(start=dt("2025-03-15T00:00:00Z"), end=dt("2025-06-30T23:59:59Z"))
+frostbite = TemporalInterval(start=dt("2025-07-01T00:00:00Z"), end=dt("2025-09-30T23:59:59Z"))
+
+relation_ns = engine.relation(nightfall, sandstorm)
+relation_nf = engine.relation(nightfall, frostbite)
+
+print("NIGHTFALL vs SANDSTORM:", relation_ns)
+# IntervalRelation.OVERLAPS — both active simultaneously in mid-March 2025
+# Warrants investigation for shared C2 infrastructure or coordination
+
+print("NIGHTFALL vs FROSTBITE:", relation_nf)
+# IntervalRelation.BEFORE — no temporal overlap; likely independent campaigns
+```
+
+The 13 Allen relations cover every possible temporal relationship:
+
+| Relation | Meaning |
+|---|---|
+| `BEFORE` | A ends before B starts |
+| `MEETS` | A ends exactly where B starts (no gap, no overlap) |
+| `OVERLAPS` | A starts before B and ends during B |
+| `STARTS` | A and B start together; A ends first |
+| `DURING` | A is fully contained within B |
+| `FINISHES` | A and B end together; A starts later |
+| `EQUALS` | A and B are identical intervals |
+| `AFTER`, `MET_BY`, `OVERLAPPED_BY`, `STARTED_BY`, `CONTAINS`, `FINISHED_BY` | Inverses of the above |
+
+An `OVERLAPS` or `EQUALS` result between two campaigns attributed to different actors is a signal worth flagging for analyst review — a temporal coincidence is a hypothesis, not a conclusion.
+
+## Step 8 — LLM-based graph reasoning
+
+`GraphReasoner` routes freeform natural language queries through an LLM provider, using the graph as grounded context. Use it for exploratory questions that do not map cleanly to a predefined rule set:
+
+```python
+from semantica.reasoning import GraphReasoner
+from semantica.context import ContextGraph
+
+# Initialise with any supported LLM provider
+gr = GraphReasoner(provider="openai", model="gpt-4o-mini")
+
+# Build a knowledge graph
+graph = ContextGraph()
+graph.add_node("apt29", "ThreatActor", "APT29 / NOBELIUM", country="Russia")
+graph.add_node("cve-2025-3400", "Vulnerability", "PAN-OS RCE", cvss=9.8)
+graph.add_node("nato_logistics", "Target", "NATO Logistics Network")
+graph.add_edge("apt29", "cve-2025-3400", "exploits", weight=0.97)
+graph.add_edge("apt29", "nato_logistics", "targets", weight=0.88)
+
+# GraphReasoner expects {"entities": [...], "relationships": [...]}
+raw = graph.to_dict()
+graph_data = {
+ "entities": raw.get("nodes", []),
+ "relationships": raw.get("edges", []),
+}
+
+answer = gr.reason(
+ graph=graph_data,
+ query="Which threat actors pose the highest risk to NATO infrastructure, "
+ "and what evidence in the graph supports that assessment?"
+)
+print(answer)
+```
+
+`GraphReasoner` is well suited for early-stage investigation — when the question is exploratory and you have not yet formalised inference rules. For reproducible, auditable decisions, use `Reasoner` or `DatalogReasoner` instead.
+
+## Step 9 — Explaining inferences in natural language
+
+`ExplanationGenerator` translates any `InferenceResult` (from forward or backward chaining) into a human-readable explanation, a step-by-step `ReasoningPath`, and a `Justification` with supporting evidence:
+
+```python
+from semantica.reasoning import Reasoner, Rule, RuleType, ExplanationGenerator
+
+# Run inference first
+reasoner = Reasoner()
+reasoner.add_fact("ThreatActor(APT29)")
+reasoner.add_fact("Exploits(APT29, CVE-2025-3400)")
+reasoner.add_fact("CriticalVuln(CVE-2025-3400)")
+
+reasoner.add_rule(Rule(
+ rule_id="r1", name="high_risk_actor",
+ conditions=["ThreatActor(X)", "Exploits(X, Y)", "CriticalVuln(Y)"],
+ conclusion="HighRiskActor(X)",
+ confidence=0.92,
+))
+
+derived = reasoner.forward_chain()
+
+# detail_level options: "simple", "detailed", "verbose"
+gen = ExplanationGenerator(generate_nl=True, detail_level="detailed")
+
+for result in derived:
+ exp = gen.generate_explanation(result)
+ print("Conclusion: {}".format(exp.conclusion))
+ print("Explanation: {}".format(exp.natural_language))
+ print()
+
+ # Step-by-step reasoning path
+ path = gen.show_reasoning_path(result)
+ print("Reasoning path ({} steps, confidence {:.0%}):".format(
+ len(path.steps), path.total_confidence
+ ))
+ for step in path.steps:
+ print(" [{}] {}".format(step.step_id, step.description))
+
+ # Justification with full evidence list
+ just = gen.justify_conclusion(result.conclusion, path)
+ print("Justification: {}".format(just.explanation_text))
+ print("Supporting evidence: {}".format(just.supporting_evidence))
+```
+
+```text
+Conclusion: HighRiskActor(APT29)
+Explanation: Given the premises: ThreatActor(APT29), Exploits(APT29, CVE-2025-3400),
+ CriticalVuln(CVE-2025-3400), we conclude: HighRiskActor(APT29)
+ using rule 'high_risk_actor'.
+```
+
+Three detail levels control explanation verbosity: `"simple"` gives a one-line summary, `"detailed"` lists premises and the rule name, and `"verbose"` produces a full confidence-annotated narrative.
+
+## Putting it together: a complete reasoning pipeline
+
+A pipeline combining forward chaining, Datalog reachability, and natural language explanations for a threat intelligence graph:
+
+```python
+from semantica.reasoning import (
+ Reasoner, Rule, RuleType,
+ DatalogReasoner, ExplanationGenerator,
+)
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+
+def run_threat_reasoning(graph: ContextGraph) -> dict:
+ """Apply inference rules to a threat intelligence graph."""
+
+ # --- Forward chaining: derive actor classifications ---
+ reasoner = Reasoner()
+
+ for edge in graph.find_edges():
+ src = edge.get("source", "")
+ dst = edge.get("target", "")
+ rel = edge.get("type", "related_to")
+ if src and dst:
+ reasoner.add_fact("{}({}, {})".format(rel.replace(" ", "_"), src, dst))
+
+ for node in graph.find_nodes():
+ name = node.get("name", node.get("id", ""))
+ ntype = node.get("type", "Entity")
+ if name:
+ reasoner.add_fact("{}({})".format(ntype.replace(" ", "_"), name))
+
+ reasoner.add_rule(Rule(
+ rule_id="r1", name="high_risk_actor",
+ conditions=["ThreatActor(X)", "Exploits(X, CVE)", "CriticalVuln(CVE)"],
+ conclusion="HighRiskActor(X)", confidence=0.92, priority=10,
+ ))
+ reasoner.add_rule(Rule(
+ rule_id="r2", name="critical_target",
+ conditions=["HighRiskActor(X)", "Targets(X, Z)"],
+ conclusion="CriticalTarget(Z)", confidence=0.88, priority=8,
+ ))
+ reasoner.add_rule(Rule(
+ rule_id="r3", name="supplier_elevation",
+ conditions=["SuppliedExploits(A, B)", "HighRiskActor(B)"],
+ conclusion="HighRiskSupplier(A)", confidence=0.85, priority=5,
+ ))
+
+ derived = reasoner.forward_chain()
+
+ high_risk_actors = [r for r in derived if "HighRiskActor" in r.conclusion]
+ critical_targets = [r for r in derived if "CriticalTarget" in r.conclusion]
+ high_risk_suppliers = [r for r in derived if "HighRiskSupplier" in r.conclusion]
+
+ # --- Backward chaining: verify a specific supplier hypothesis ---
+ supplier_result = reasoner.backward_chain("HighRiskSupplier(DELTA-3)", max_depth=5)
+
+ # --- Datalog: transitive supply-chain reachability ---
+ dl = DatalogReasoner()
+ dl.load_from_graph(graph)
+ dl.add_rule("reaches(X, Y) :- supplied(X, Y).")
+ dl.add_rule("reaches(X, Y) :- supplied(X, Z), reaches(Z, Y).")
+ dl.add_rule("sector_exposure(Actor, Sector) :- reaches(Actor, T), sector(T, Sector).")
+ dl.add_rule("sector_exposure(Actor, Sector) :- targets(Actor, T), sector(T, Sector).")
+ dl.derive_all()
+ ci_exposures = dl.query("sector_exposure(?actor, critical_infrastructure)")
+
+ # --- ExplanationGenerator: analyst-readable justifications ---
+ gen = ExplanationGenerator(generate_nl=True, detail_level="detailed")
+ explanations = {}
+ for result in high_risk_actors:
+ exp = gen.generate_explanation(result)
+ explanations[result.conclusion] = exp.natural_language
+
+ return {
+ "high_risk_actors": [r.conclusion for r in high_risk_actors],
+ "critical_targets": [r.conclusion for r in critical_targets],
+ "high_risk_suppliers": [r.conclusion for r in high_risk_suppliers],
+ "delta3_flagged": supplier_result is not None,
+ "ci_exposed_actors": [row["actor"] for row in ci_exposures],
+ "total_derived": len(derived),
+ "explanations": explanations,
+ }
+
+
+intel_graph = ContextGraph(advanced_analytics=True)
+agent = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=intel_graph,
+)
+# ... populate via agent.store() or extraction pipeline ...
+
+report = run_threat_reasoning(intel_graph)
+print("Derived {} new facts".format(report["total_derived"]))
+print("High-risk actors: {}".format(report["high_risk_actors"]))
+print("CI-exposed actors: {}".format(report["ci_exposed_actors"]))
+print("DELTA-3 flagged: {}".format(report["delta3_flagged"]))
+
+for conclusion, text in report["explanations"].items():
+ print("\n[{}]\n {}".format(conclusion, text))
+```
+
+## Domain examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+Attribution chains in threat intelligence require multi-hop confidence propagation: a TTP match raises the probability of actor attribution, corroborating ASN geolocation raises it further, and a known targeting pattern for the attributed sector raises it to actionable confidence. Each hop is a separate rule with its own confidence weight, and `InferenceResult` carries the propagated value through the chain.
+
+```python
+from semantica.reasoning import Reasoner, Rule, RuleType
+
+reasoner = Reasoner()
+
+# SIGINT-derived facts
+reasoner.add_fact("C2Beacon(10.0.0.5, AS59796)")
+reasoner.add_fact("ASN_Country(AS59796, Russia)")
+reasoner.add_fact("TTP(T1566.001, APT29)") # MITRE ATT&CK mapping
+reasoner.add_fact("ObservedTTP(10.0.0.5, T1566.001)")
+reasoner.add_fact("TargetSector(10.0.0.5, Aerospace)")
+
+# Three-stage attribution ruleset with confidence ladder
+reasoner.add_rule(Rule(
+ rule_id="attr-1", name="ttp_match",
+ conditions=["ObservedTTP(IP, TTP)", "TTP(TTP, Actor)"],
+ conclusion="SuspectedActor(IP, Actor)",
+ confidence=0.75, priority=10,
+))
+reasoner.add_rule(Rule(
+ rule_id="attr-2", name="asn_corroboration",
+ conditions=["SuspectedActor(IP, Actor)", "C2Beacon(IP, ASN)", "ASN_Country(ASN, Country)"],
+ conclusion="CorroboratedActor(IP, Actor, Country)",
+ confidence=0.90, priority=5,
+))
+reasoner.add_rule(Rule(
+ rule_id="attr-3", name="sector_confirmation",
+ conditions=["CorroboratedActor(IP, Actor, Russia)", "TargetSector(IP, Aerospace)"],
+ conclusion="HighConfidenceAttribution(IP, Actor)",
+ confidence=0.95, priority=1,
+))
+
+derived = reasoner.forward_chain()
+attributions = [r for r in derived if "HighConfidenceAttribution" in r.conclusion]
+
+for a in attributions:
+ print("{:50s} conf={:.0%}".format(a.conclusion, a.confidence))
+ print(" Premises: {}".format(a.premises))
+
+# HighConfidenceAttribution(10.0.0.5, APT29) conf=95%
+# Premises: ['SuspectedActor(10.0.0.5, APT29)', 'CorroboratedActor(10.0.0.5, APT29, Russia)', ...]
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+Zero-trust access control decisions can be evaluated at query time by encoding policy as rules and backward-chaining against a specific access request. The proof — or its absence — is the explainable decision record, ready for audit.
+
+If the backward chain fails, the premises list in the partial result tells the analyst exactly which policy condition was not satisfied — far more useful than a generic "access denied" message.
+
+```python
+from semantica.reasoning import Reasoner, Rule, RuleType
+
+reasoner = Reasoner()
+
+# Identity and resource facts for the current session
+reasoner.add_fact("User(alice)")
+reasoner.add_fact("HasMFA(alice)")
+reasoner.add_fact("Role(alice, analyst)")
+reasoner.add_fact("Clearance(alice, SECRET)")
+reasoner.add_fact("Resource(kube-api, tier1)")
+reasoner.add_fact("RequiresClearance(kube-api, SECRET)")
+reasoner.add_fact("RequiresMFA(tier1)")
+
+# Zero-trust access policy as inference rules
+reasoner.add_rule(
+ "IF User(U) AND HasMFA(U) AND RequiresMFA(T) AND Resource(R, T) THEN MFASatisfied(U, R)"
+)
+reasoner.add_rule(
+ "IF User(U) AND Clearance(U, C) AND RequiresClearance(R, C) THEN ClearanceSatisfied(U, R)"
+)
+reasoner.add_rule(
+ "IF MFASatisfied(U, R) AND ClearanceSatisfied(U, R) THEN AccessGranted(U, R)"
+)
+
+# Backward-chain the access decision
+result = reasoner.backward_chain("AccessGranted(alice, kube-api)", max_depth=5)
+
+if result:
+ print("ACCESS GRANTED: {}".format(result.conclusion))
+ print("Justified by:")
+ for p in result.premises:
+ print(" - {}".format(p))
+else:
+ print("ACCESS DENIED — one or more policy conditions not satisfied")
+ partial = reasoner.forward_chain()
+ for r in partial:
+ print(" Partial: {}".format(r.conclusion))
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+Drug-drug interaction detection is a natural fit for forward chaining: facts about enzyme inhibition and metabolic pathways are static, the rules about interaction risk are standardised pharmacology, and the output — a `ClinicallySignificantInteraction` derived fact — needs to fire reliably before a prescription is confirmed.
+
+Datalog handles the transitive case: if drug A induces enzyme E1, and E1 metabolises drug B, the full exposure chain can be traced recursively without knowing its depth in advance.
+
+```python
+from semantica.reasoning import Reasoner, DatalogReasoner
+
+# Forward-chain: detect clinically significant interactions
+reasoner = Reasoner()
+
+reasoner.add_fact("Metabolizes(CYP2C9, Warfarin)")
+reasoner.add_fact("Inhibits(Amiodarone, CYP2C9)")
+reasoner.add_fact("DrugInPatient(Warfarin)")
+reasoner.add_fact("DrugInPatient(Amiodarone)")
+reasoner.add_fact("TherapeuticWindow(Warfarin, narrow)")
+
+reasoner.add_rule(
+ "IF Inhibits(DrugA, Enzyme) AND Metabolizes(Enzyme, DrugB) "
+ "AND DrugInPatient(DrugA) AND DrugInPatient(DrugB) "
+ "THEN PotentialInteraction(DrugA, DrugB)"
+)
+reasoner.add_rule(
+ "IF PotentialInteraction(DrugA, DrugB) AND TherapeuticWindow(DrugB, narrow) "
+ "THEN ClinicallySignificantInteraction(DrugA, DrugB)"
+)
+
+derived = reasoner.forward_chain()
+for r in derived:
+ if "ClinicallySignificant" in r.conclusion:
+ print("ALERT: {} (conf={:.0%})".format(r.conclusion, r.confidence))
+ print(" Rule: {}".format(r.rule_used.name if r.rule_used else "n/a"))
+
+# ALERT: ClinicallySignificantInteraction(Amiodarone, Warfarin) (conf=100%)
+
+# Datalog: transitive enzyme induction chain
+dl = DatalogReasoner()
+dl.add_fact("metabolises(CYP3A4, midazolam)")
+dl.add_fact("metabolises(CYP3A4, cyclosporin)")
+dl.add_fact("induces(rifampicin, CYP3A4)")
+dl.add_rule("reduces_exposure(X, Drug) :- induces(X, Enzyme), metabolises(Enzyme, Drug).")
+dl.add_rule("reduces_exposure(X, Drug) :- induces(X, Z), reduces_exposure(Z, Drug).")
+
+dl.derive_all()
+reductions = dl.query("reduces_exposure(rifampicin, ?drug)")
+for row in reductions:
+ print("Rifampicin reduces exposure to: {}".format(row["drug"]))
+
+# Rifampicin reduces exposure to: midazolam
+# Rifampicin reduces exposure to: cyclosporin
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+Basel III capital adequacy rules translate naturally into forward-chaining inference rules: each regulatory condition is a fact, each article is a rule, and the capital decision is a derived conclusion. The rule chain is the audit trail — an examiner can inspect exactly which conditions fired and in what order.
+
+Backward chaining is useful for stress testing: "under what conditions would this loan receive a `ConditionalApproval`?" answers by proving the goal and surfacing the minimal set of required facts.
+
+```python
+from semantica.reasoning import Reasoner, Rule, RuleType
+
+reasoner = Reasoner()
+
+# Loan application facts
+reasoner.add_fact("Loan(LOAN-2025-88421)")
+reasoner.add_fact("LTV(LOAN-2025-88421, 0.78)")
+reasoner.add_fact("PD(LOAN-2025-88421, 0.023)")
+reasoner.add_fact("LGD(LOAN-2025-88421, 0.45)")
+reasoner.add_fact("AssetClass(LOAN-2025-88421, CRE)")
+reasoner.add_fact("DSCR(LOAN-2025-88421, 1.12)")
+
+# Basel III CRE20 capital rules
+reasoner.add_rule(Rule(
+ rule_id="cre20-1", name="ltv_rwa_bucket",
+ conditions=["Loan(L)", "LTV(L, V)", "AssetClass(L, CRE)"],
+ conclusion="RWABucket(L, high)",
+ confidence=0.98, priority=10,
+))
+reasoner.add_rule(Rule(
+ rule_id="cre20-2", name="dscr_adequate",
+ conditions=["Loan(L)", "DSCR(L, D)"],
+ conclusion="DSCRAdequate(L)",
+ confidence=0.95, priority=8,
+))
+reasoner.add_rule(Rule(
+ rule_id="cre20-3", name="conditional_approval",
+ conditions=["Loan(L)", "RWABucket(L, high)", "DSCRAdequate(L)"],
+ conclusion="ConditionalApproval(L)",
+ confidence=0.87, priority=5,
+))
+
+derived = reasoner.forward_chain()
+for r in derived:
+ print("{:45s} [{:.0%}]".format(r.conclusion, r.confidence))
+
+# RWABucket(LOAN-2025-88421, high) [98%]
+# DSCRAdequate(LOAN-2025-88421) [95%]
+# ConditionalApproval(LOAN-2025-88421) [87%]
+
+# Audit: prove the approval decision and show its full justification
+proof = reasoner.backward_chain("ConditionalApproval(LOAN-2025-88421)", max_depth=5)
+if proof:
+ print("\nAudit trail for {}:".format(proof.conclusion))
+ for p in proof.premises:
+ print(" - {}".format(p))
+```
+
+</Tab>
+
+</Tabs>
+
+## Related Guides
+
+- [Semantic Extraction](semantic-extraction) — extract the entities and relationships that populate the graph facts you reason over
+- [GraphRAG](graphrag) — retrieve graph-grounded context for LLM responses
+- [Ontology Management](ontology) — generate OWL ontologies to give your rules formal semantics
+- [Decision Intelligence](decision-intelligence) — record and trace inferred decisions through the full causal chain
+- [Context Graphs](context-graphs) — the knowledge graph that reasoning operates over
+- [MCP Server](mcp-server) — expose `run_reasoning` as a tool for Claude and other agents
diff --git a/docs/guides/semantic-extraction.md b/docs/guides/semantic-extraction.md
new file mode 100644
index 00000000..cbf79024
--- /dev/null
+++ b/docs/guides/semantic-extraction.md
@@ -0,0 +1,581 @@
+---
+title: "Semantic Extraction"
+description: "How Semantica extracts entities, relationships, events, and RDF triplets from unstructured text using pattern, ML, and LLM methods — with fallback chains, batch processing, and real-world pipelines for defense intelligence, cybersecurity, life science, and financial compliance."
+icon: "magnifying-glass"
+---
+
+`semantica.semantic_extract` turns unstructured text into structured graph-ready output: it identifies named entities, extracts relationships between them, detects time-anchored events, resolves coreferences, and serialises everything as RDF triplets. Use it to populate a `ContextGraph` from raw documents — intelligence reports, clinical notes, regulatory filings, or any free-text corpus.
+
+<Info>
+ Extracted entities and relationships feed into `ContextGraph` via `AgentContext.store()`. For how they are attributed back to source documents, see the [Provenance Guide](provenance). For how the populated graph is queried and traversed, see [Context Graphs](context-graphs).
+</Info>
+
+## Step 1 — Named Entity Recognition: who and what is in the text
+
+`NamedEntityRecognizer` extracts meaningful nouns from a document and lets you choose the underlying method depending on your latency budget and domain requirements:
+
+```python
+from semantica.semantic_extract import NamedEntityRecognizer
+
+# A finished intelligence report excerpt
+report = """
+ASSESSMENT (SECRET//NOFORN): GAMMA-7 threat actor, assessed with HIGH confidence
+to operate from COUNTRY_X, conducted OPERATION NIGHTFALL between Jan–Mar 2025.
+The group deployed HAMMERTOSS malware targeting NATO logistics networks via
+spear-phishing lures referencing Exercise STEADFAST DEFENDER 2025.
+Infrastructure cluster 185.220.101.0/24 was active throughout the campaign.
+A second actor, DELTA-3, provided GAMMA-7 with zero-day exploits (CVE-2025-1234,
+CVE-2025-5678) for Ivanti Connect Secure VPN appliances.
+"""
+
+# LLM-backed NER handles custom intelligence entity types that spaCy won't know.
+# Fallback chain: if llm returns nothing, try ml (spaCy), then pattern matching.
+ner = NamedEntityRecognizer(
+ methods=["llm", "ml", "pattern"],
+ confidence_threshold=0.75,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+)
+entities = ner.extract_entities(report)
+
+for e in entities:
+ print("[{:>5.2f}] {:15s} {}".format(e.confidence, e.label, e.text))
+
+# Expected output (abbreviated):
+# [ 0.94] THREAT_ACTOR GAMMA-7
+# [ 0.91] THREAT_ACTOR DELTA-3
+# [ 0.97] MALWARE HAMMERTOSS
+# [ 0.99] CVE CVE-2025-1234
+# [ 0.99] CVE CVE-2025-5678
+# [ 0.88] NETWORK 185.220.101.0/24
+# [ 0.85] ORG NATO
+```
+
+The `confidence` field tells you how certain the extractor is. Values below your threshold (here 0.75) are filtered before they reach you. The `label` field uses either standard CoNLL types (PERSON, ORG, GPE) or domain-specific ones the LLM infers from context (THREAT_ACTOR, MALWARE, CVE, NETWORK).
+
+Once you have the flat list of entities, group them by type to make the next steps easier:
+
+```python
+# classify_entities groups the flat list into a dict keyed by label
+grouped = ner.classify_entities(entities)
+
+print("Threat actors:", [e.text for e in grouped.get("THREAT_ACTOR", [])])
+# Threat actors: ['GAMMA-7', 'DELTA-3']
+
+print("Malware: ", [e.text for e in grouped.get("MALWARE", [])])
+# Malware: ['HAMMERTOSS']
+
+print("CVEs: ", [e.text for e in grouped.get("CVE", [])])
+# CVEs: ['CVE-2025-1234', 'CVE-2025-5678']
+
+# score_confidence re-scores with a statistical model — useful when your primary
+# method doesn't return calibrated probabilities (e.g., pattern matching)
+rescored = ner.score_confidence(entities)
+high_conf = [e for e in rescored if e.confidence >= 0.85]
+print("High-confidence entities: {}".format(len(high_conf)))
+```
+
+## Step 2 — Relation Extraction: how the entities connect
+
+`RelationExtractor` produces the web of connections between entities — who deployed what, who supplied whom, which CVE targets which product:
+
+```python
+from semantica.semantic_extract import RelationExtractor
+
+# dependency parsing picks up syntactic relations ("DELTA-3 provided GAMMA-7 with...")
+# pattern matching catches explicit verb phrases as a fallback
+rel = RelationExtractor(
+ method=["dependency", "pattern"],
+ relation_types=["operates_from", "deployed", "targets", "provided_to", "exploits"],
+ bidirectional=True, # also try object→subject direction
+ confidence_threshold=0.65,
+)
+
+# extract_relations takes the original text plus the entities you already found.
+# Passing entities avoids re-running NER and constrains the search space.
+relations = rel.extract_relations(report, entities)
+
+for r in relations:
+ print("[{:.2f}] {} --[{}]--> {}".format(
+ r.confidence, r.subject.text, r.predicate, r.object.text
+ ))
+
+# Example output:
+# [0.88] GAMMA-7 --[deployed]--> HAMMERTOSS
+# [0.82] DELTA-3 --[provided_to]--> GAMMA-7
+# [0.79] CVE-2025-1234 --[exploits]--> Ivanti Connect Secure
+# [0.85] GAMMA-7 --[targets]--> NATO
+```
+
+The `context` field on each `Relation` stores the surrounding sentence. This lets you audit why the extractor made a given connection — essential when analysts need to verify that a link is grounded in the source text before acting on it.
+
+## Step 3 — Event Detection: what happened, when, and to whom
+
+`EventDetector` surfaces structured time-anchored events — discrete occurrences with participants, time windows, and locations:
+
+```python
+from semantica.semantic_extract import EventDetector
+
+# method="llm" is the default and gives the best recall for implicit events.
+# method="pattern" is appropriate for offline, high-throughput pipelines.
+detector = EventDetector(method="llm", provider="anthropic")
+
+events = detector.detect_events(report)
+
+for ev in events:
+ print("[{}] time={} location={}".format(
+ ev.event_type, ev.time or "unknown", ev.location or "n/a"
+ ))
+ print(" participants: {}".format(ev.participants))
+ print(" text: {}".format(ev.text[:80]))
+
+# Example output:
+# [campaign] time=Jan–Mar 2025 location=n/a
+# participants: ['GAMMA-7', 'NATO']
+# text: GAMMA-7 conducted OPERATION NIGHTFALL between Jan–Mar 2025...
+# [supply_chain] time=unknown location=n/a
+# participants: ['DELTA-3', 'GAMMA-7']
+# text: DELTA-3 provided GAMMA-7 with zero-day exploits...
+```
+
+For batch processing, pass a list of dicts to `extract()`. Each dict carries a `content` key and an optional `id` for provenance tracking:
+
+```python
+# extract() handles concurrent processing internally
+batch_events = detector.extract([
+ {"content": report, "id": "FINTEL_2025_0192"},
+ {"content": advisory_2, "id": "FINTEL_2025_0193"},
+ # ... up to 200 documents
+])
+
+# batch_events is List[List[Event]] — one inner list per document
+for doc_idx, doc_events in enumerate(batch_events):
+ print("Doc {}: {} events".format(doc_idx, len(doc_events)))
+```
+
+## Step 4 — Coreference Resolution: one entity, many names
+
+`CoreferenceResolver` collapses references like "GAMMA-7", "the group", "they", and "the threat actor" into canonical chains so downstream extraction doesn't treat them as separate entities:
+
+```python
+from semantica.semantic_extract import CoreferenceResolver
+
+resolver = CoreferenceResolver(method="llm", provider="anthropic")
+
+# Pass the already-extracted entities so the resolver can anchor pronouns
+# to the correct named entities rather than guessing from scratch
+chains = resolver.resolve_coreferences(report, entities=entities)
+
+for chain in chains:
+ print("Representative: {}".format(chain.representative.text))
+ mentions = [m.text for m in chain.mentions if m.text != chain.representative.text]
+ print(" Also called: {}".format(mentions))
+
+# Example output:
+# Representative: GAMMA-7
+# Also called: ['the group', 'they', 'the threat actor']
+```
+
+With coreference resolved, you can now replace pronouns and aliases with canonical names before passing text to relation extraction — dramatically improving the quality of the relation graph.
+
+## Step 5 — Triplet Extraction and RDF Serialisation: graph-ready output
+
+`TripletExtractor` converts everything into subject-predicate-object triplets and serialises them as RDF, ready for graph ingestion and SPARQL queries:
+
+```python
+from semantica.semantic_extract import TripletExtractor
+
+tri = TripletExtractor(
+ method="llm",
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+ include_temporal=True, # attach time context to triplets when available
+ include_provenance=True, # embed source document reference in each triplet
+)
+
+# Feed in the entities and relations you already extracted — the extractor
+# uses them to constrain and validate what it produces
+triplets = tri.extract_triplets(report, entities, relations)
+
+# Filter malformed triplets before serialisation
+valid = tri.validate_triplets(triplets)
+print("Valid: {}/{}".format(len(valid), len(triplets)))
+
+for t in valid:
+ print("({}, {}, {}) conf={:.2f}".format(
+ t.subject, t.predicate, t.object, t.confidence
+ ))
+
+# Serialise to Turtle RDF for graph ingestion or STIX export
+turtle_rdf = tri.serialize_triplets(valid, format="turtle")
+print(turtle_rdf[:600])
+
+# formats: "turtle" | "ntriples" | "jsonld" | "xml"
+```
+
+A validated triplet like `(GAMMA-7, deployed, HAMMERTOSS)` with `include_temporal=True` will carry the time interval from the Event you detected in step 3 — keeping the graph queryable not just by what happened but by when.
+
+## Putting it together: a reusable extraction pipeline
+
+Chain all five steps into a single function you can call on every incoming document:
+
+```python
+from semantica.semantic_extract import (
+ NamedEntityRecognizer, RelationExtractor,
+ EventDetector, CoreferenceResolver, TripletExtractor,
+)
+from semantica.provenance import ProvenanceManager
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+
+def ingest_intel_report(
+ text: str,
+ doc_id: str,
+ agent: AgentContext,
+ prov: ProvenanceManager,
+ method: str = "llm",
+) -> dict:
+ """
+ Full extraction pipeline: NER → Coref → Relations → Events → Triplets → Graph.
+ Returns a summary dict with counts for monitoring dashboards.
+ """
+
+ # 1. Named entity recognition
+ ner = NamedEntityRecognizer(
+ methods=[method, "pattern"],
+ confidence_threshold=0.70,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+ )
+ entities = ner.extract_entities(text)
+ classified = ner.classify_entities(entities)
+
+ # 2. Coreference resolution — before relation extraction
+ resolver = CoreferenceResolver(method=method, provider="anthropic")
+ chains = resolver.resolve_coreferences(text, entities=entities)
+
+ # 3. Relation extraction
+ rel = RelationExtractor(
+ method=[method, "pattern"],
+ relation_types=["deployed", "targets", "exploits", "operates_from", "provided_to"],
+ confidence_threshold=0.65,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+ )
+ relations = rel.extract_relations(text, entities)
+
+ # 4. Event detection
+ detector = EventDetector(method=method, provider="anthropic")
+ events = detector.detect_events(text)
+
+ # 5. Triplet extraction and RDF serialisation
+ tri = TripletExtractor(
+ method=method,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+ include_temporal=True,
+ include_provenance=True,
+ )
+ triplets = tri.extract_triplets(text, entities, relations)
+ valid = tri.validate_triplets(triplets)
+ turtle = tri.serialize_triplets(valid, format="turtle")
+
+ # 6. Store in agent memory + knowledge graph
+ graph_stats = agent.store(
+ [{"content": text, "metadata": {"source": doc_id, "classification": "SECRET//NOFORN"}}],
+ extract_entities=True,
+ extract_relationships=True,
+ link_entities=True,
+ )
+
+ # 7. Provenance tracking — every entity linked back to its source document
+ prov.track_entities_batch(
+ [{"id": e.text.lower().replace(" ", "_"), "confidence": e.confidence}
+ for e in entities],
+ source=doc_id,
+ activity_id="intel_extraction_pipeline",
+ )
+
+ return {
+ "entities": len(entities),
+ "entity_types": {k: len(v) for k, v in classified.items()},
+ "coref_chains": len(chains),
+ "relations": len(relations),
+ "events": len(events),
+ "triplets_valid": len(valid),
+ "graph_nodes": graph_stats.get("graph_nodes", 0),
+ "graph_edges": graph_stats.get("graph_edges", 0),
+ "rdf_turtle": turtle,
+ }
+
+
+# Process all 200 reports
+intel_graph = ContextGraph(advanced_analytics=True)
+intel_agent = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768, index_path="intel.faiss"),
+ knowledge_graph=intel_graph,
+ decision_tracking=True,
+)
+prov = ProvenanceManager(storage_path="intel_provenance.db")
+
+# reports is a list of (text, doc_id) tuples loaded from your 200 documents
+for text, doc_id in reports:
+ summary = ingest_intel_report(text, doc_id, intel_agent, prov)
+ print("{}: {} entities, {} relations, {} events, {}/{} triplets valid".format(
+ doc_id,
+ summary["entities"],
+ summary["relations"],
+ summary["events"],
+ summary["triplets_valid"],
+ len(summary["rdf_turtle"]),
+ ))
+```
+
+## Domain examples
+
+<Tabs>
+ <Tab title="Defense — CTI/Threat">
+ Finished intelligence reports contain threat actors, malware, CVEs, infrastructure clusters, and operation timelines. LLM-backed NER handles custom entity labels (THREAT_ACTOR, OPERATION) that spaCy's off-the-shelf models miss, while RDF serialisation produces Turtle output compatible with STIX 2.1 object types.
+
+```python
+from semantica.semantic_extract import (
+ NamedEntityRecognizer, RelationExtractor, TripletExtractor,
+)
+
+ner = NamedEntityRecognizer(
+ methods=["llm", "pattern"],
+ confidence_threshold=0.75,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+)
+entities = ner.extract_entities(fintel_text)
+grouped = ner.classify_entities(entities)
+
+print("Threat actors:", [e.text for e in grouped.get("THREAT_ACTOR", [])])
+# ['APT29', 'COZY BEAR']
+print("Malware: ", [e.text for e in grouped.get("MALWARE", [])])
+# ['HAMMERTOSS', 'SUNBURST']
+print("CVEs: ", [e.text for e in grouped.get("CVE", [])])
+# ['CVE-2025-1234', 'CVE-2025-5678']
+
+rel = RelationExtractor(
+ method=["llm", "dependency"],
+ relation_types=["operates_from", "deployed", "targets", "exploits"],
+ confidence_threshold=0.70,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+)
+relations = rel.extract_relations(fintel_text, entities)
+
+tri = TripletExtractor(
+ method="llm",
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+ include_temporal=True,
+ include_provenance=True,
+)
+triplets = tri.extract_triplets(fintel_text, entities, relations)
+valid = tri.validate_triplets(triplets)
+turtle = tri.serialize_triplets(valid, format="turtle")
+# turtle now contains RDF triples for (APT29, deployed, HAMMERTOSS),
+# (APT29, targets, NATO_logistics), etc. — ready for STIX graph ingest
+```
+
+ </Tab>
+
+ <Tab title="Security — SOC/Incident">
+ Vulnerability advisories and SIEM alerts contain CVEs, IP addresses, domain indicators, malware families, and affected software versions. Offline NER with the `["ml", "pattern"]` chain gives sub-200ms latency, critical for real-time triage pipelines where LLM latency is unacceptable.
+
+```python
+from semantica.semantic_extract import (
+ NamedEntityRecognizer, RelationExtractor, TripletExtractor,
+)
+
+advisory = """
+CVE-2025-44228 (CVSS 10.0): Critical RCE in Apache Log4j2 versions 2.0–2.14.1.
+Threat actor WIZARD SPIDER exploiting via Cobalt Strike beacons since 2025-03-14.
+Indicators: 203.0.113.45, c2-update[.]ru. Mitigate: upgrade to Log4j2 >= 2.17.1.
+"""
+
+# Offline stack — no API key required, latency < 200 ms
+ner = NamedEntityRecognizer(
+ methods=["ml", "pattern"],
+ confidence_threshold=0.60,
+)
+entities = ner.extract_entities(advisory)
+grouped = ner.classify_entities(entities)
+
+print("CVEs: ", [e.text for e in grouped.get("CVE", [])])
+# ['CVE-2025-44228']
+print("IPs: ", [e.text for e in grouped.get("IP", [])])
+# ['203.0.113.45']
+print("Domains: ", [e.text for e in grouped.get("DOMAIN", [])])
+# ['c2-update[.]ru']
+print("Actors: ", [e.text for e in grouped.get("THREAT_ACTOR", [])])
+# ['WIZARD SPIDER']
+
+rel = RelationExtractor(
+ method=["dependency", "pattern"],
+ relation_types=["exploits", "delivers", "targets", "mitigated_by"],
+ confidence_threshold=0.60,
+)
+relations = rel.extract_relations(advisory, entities)
+
+tri = TripletExtractor(method="pattern", include_temporal=True)
+triplets = tri.extract_triplets(advisory, entities, relations)
+valid = tri.validate_triplets(triplets)
+ntriples = tri.serialize_triplets(valid, format="ntriples")
+print("Valid triplets: {}".format(len(valid)))
+# Valid triplets: 7
+# Each triple encodes one structured fact: (CVE-2025-44228, exploited_by, WIZARD_SPIDER), etc.
+```
+
+ </Tab>
+
+ <Tab title="Life Science — Clinical/Pharma">
+ Clinical trial reports contain drugs, diseases, efficacy outcomes, adverse events, and trial identifiers. The `d4data/biomedical-ner-all` HuggingFace model is trained on PubMed and returns biomedical-specific labels (DRUG, DISEASE, GENE, OUTCOME) that general-purpose models miss. RDF serialisation in Turtle can be submitted in EMA XEVMPD and FDA SPL compatible formats.
+
+```python
+from semantica.semantic_extract import (
+ NamedEntityRecognizer, RelationExtractor, TripletExtractor,
+)
+from semantica.provenance import ProvenanceManager
+from semantica.provenance.schemas import SourceReference
+
+paper = """
+Phase III trial NCT04368728: BNT162b2 (Pfizer-BioNTech) evaluated in 43,448
+participants aged >= 16 years. Vaccine efficacy: 95.0% (95% CI 90.3–97.6;
+p<0.0001) against symptomatic COVID-19. Bell's palsy observed in 4 vaccine
+vs 0 placebo participants (not statistically significant).
+"""
+
+ner = NamedEntityRecognizer(
+ method="huggingface",
+ huggingface_model="d4data/biomedical-ner-all",
+ confidence_threshold=0.75,
+)
+entities = ner.extract_entities(paper)
+grouped = ner.classify_entities(entities)
+
+print("Drugs: ", [e.text for e in grouped.get("DRUG", [])])
+# ['BNT162b2']
+print("Diseases: ", [e.text for e in grouped.get("DISEASE", [])])
+# ['COVID-19', "Bell's palsy"]
+print("Outcomes: ", [e.text for e in grouped.get("OUTCOME", [])])
+# ['vaccine efficacy 95.0%']
+
+rel = RelationExtractor(
+ method=["llm", "dependency"],
+ relation_types=["treats", "causes_adverse_event", "has_efficacy", "evaluated_in"],
+ confidence_threshold=0.65,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+)
+relations = rel.extract_relations(paper, entities)
+
+tri = TripletExtractor(
+ method="llm",
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+ triplet_types=["treats", "has_efficacy", "causes_adverse_event"],
+ include_temporal=True,
+ include_provenance=True,
+)
+triplets = tri.extract_triplets(paper, entities, relations)
+turtle = tri.serialize_triplets(tri.validate_triplets(triplets), format="turtle")
+
+# Provenance: track the efficacy figure to its exact source for ICH E6(R2) compliance
+prov = ProvenanceManager(storage_path="pharma_provenance.db")
+prov.track_property_source(
+ "BNT162b2", "vaccine_efficacy_pct", "95.0",
+ SourceReference(
+ document="DOI:10.1056/NEJMoa2034577",
+ page=9,
+ section="Table 2",
+ confidence=0.99,
+ metadata={"study_id": "C4591001", "n_participants": 43448},
+ )
+)
+```
+
+ </Tab>
+
+ <Tab title="Banking — Risk/Compliance">
+ Loan agreements, regulatory filings, and credit memos contain legal entities, financial instruments, counterparty relationships, and risk classifications. Pattern-based NER is fast enough for real-time loan origination workflows, while LLM extraction handles the dense legalese in regulatory documents where dependency parsing often fails.
+
+```python
+from semantica.semantic_extract import (
+ NamedEntityRecognizer, RelationExtractor, TripletExtractor,
+)
+
+credit_memo = """
+Borrower: ACME Manufacturing Ltd (registered UK). Guarantor: ACME Group PLC.
+Facility: GBP 25M revolving credit at SONIA + 175bps, maturing 2028-03-31.
+Collateral: first-ranking charge over ACME Manufacturing's UK fixed assets.
+LTV: 67%. PD: 1.8%. LGD: 42%. RWA bucket: Standard (CRE20).
+Exposure to counterparty sector: industrial manufacturing, risk tier 2.
+"""
+
+ner = NamedEntityRecognizer(
+ methods=["llm", "ml", "pattern"],
+ confidence_threshold=0.70,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+)
+entities = ner.extract_entities(credit_memo)
+grouped = ner.classify_entities(entities)
+
+print("Orgs: ", [e.text for e in grouped.get("ORG", [])])
+# ['ACME Manufacturing Ltd', 'ACME Group PLC']
+print("Money: ", [e.text for e in grouped.get("MONEY", [])])
+# ['GBP 25M']
+print("Dates: ", [e.text for e in grouped.get("DATE", [])])
+# ['2028-03-31']
+
+rel = RelationExtractor(
+ method=["llm", "dependency"],
+ relation_types=["guaranteed_by", "secured_by", "classified_as", "exposed_to"],
+ confidence_threshold=0.65,
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+)
+relations = rel.extract_relations(credit_memo, entities)
+
+tri = TripletExtractor(
+ method="llm",
+ provider="anthropic",
+ llm_model="claude-sonnet-4-6",
+ include_temporal=True,
+ include_provenance=True,
+)
+triplets = tri.extract_triplets(credit_memo, entities, relations)
+valid = tri.validate_triplets(triplets)
+jsonld = tri.serialize_triplets(valid, format="jsonld")
+# JSON-LD output can be loaded directly into a compliance graph
+# for Basel III RWA reporting and BCBS 239 data lineage requirements
+```
+
+ </Tab>
+</Tabs>
+
+## Choosing your extraction method
+
+The six extraction methods trade off speed, accuracy, and infrastructure:
+
+- `"pattern"` and `"regex"` — no dependencies, under 5 ms, ideal as the last fallback in any method chain. Reliable for narrow, predictable domains like CVE identifiers or IP addresses.
+- `"rules"` — linguistic rule-based detection, also offline, under 10 ms.
+- `"ml"` / `"spacy"` — general English NER at 50–200 ms with no API calls. Install with `pip install spacy && python -m spacy download en_core_web_sm`. The best default for production pipelines where LLM cost is a concern.
+- `"huggingface"` — domain-specific fine-tuned models at 200 ms–2 s. Use `d4data/biomedical-ner-all` for pharma, `dslim/bert-base-NER` for general high-accuracy NER. Install with `pip install "semantica[huggingface]"`.
+- `"llm"` — highest recall for implicit entities and custom label schemas, 1–10 s per document. Always pair with a fallback: `methods=["llm", "ml", "pattern"]`.
+
+The fallback behaviour is automatic: if the primary method returns an empty list, the framework walks down the chain until it finds results or exhausts the list. Pattern matching is always the implicit last resort.
+
+## Related Guides
+
+- [Provenance Guide](provenance) — track every extracted entity and chunk back to its source document
+- [Agent Memory Guide](agent-memory) — store extracted knowledge as searchable agent memories with graph enrichment
+- [Context Graphs Guide](context-graphs) — how extracted entities populate `ContextGraph` nodes and edges
+- [GraphRAG Guide](graphrag) — retrieve facts from the populated graph to ground LLM responses
+- [Reasoning Guide](reasoning) — derive new facts, run SPARQL queries, and apply inference rules over the extracted graph
+- [Semantic Extract Reference](../reference/semantic_extract) — full API for all extractor classes, providers, and validators
diff --git a/docs/guides/shacl-validation.md b/docs/guides/shacl-validation.md
new file mode 100644
index 00000000..5cce9817
--- /dev/null
+++ b/docs/guides/shacl-validation.md
@@ -0,0 +1,577 @@
+---
+title: "SHACL Validation"
+description: "Generate W3C SHACL shapes from OWL ontologies, validate RDF knowledge graphs against structural and semantic constraints, and surface structured violation reports."
+icon: "shield-check"
+---
+
+`SHACLGenerator` produces W3C SHACL constraint shapes from an OWL ontology, and `_run_pyshacl` validates your knowledge graph against them, returning a structured violation report. Use this to gate graph data before analytics, ISAC sharing, or regulatory submission — catching missing required properties, datatype violations, and cardinality breaches before they propagate.
+
+<Info>
+SHACL shapes are produced from the same ontology dict that `OntologyGenerator` builds. The full workflow is: graph → ontology → SHACL shapes → validation report. Each stage is one function call. `NodeShape`, `PropertyShape`, and `SHACLGraph` import from `semantica.ontology`. `SHACLValidationReport`, `SHACLViolation`, and `_run_pyshacl` import from `semantica.ontology.ontology_validator`.
+</Info>
+
+---
+
+## Step 1 — Build the ontology from your merged graph
+
+SHACL shapes are derived from an ontology. If you already have one from a previous run, skip this step.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.ontology import OntologyGenerator
+
+graph = ContextGraph()
+ctx = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ graph_expansion=True,
+)
+
+# Load the merged CTI data — in production this would be your full 12,000-node graph
+ctx.store(
+ [
+ "APT29 is a Russian state-sponsored threat actor targeting NATO governments.",
+ "CVE-2024-3400 is a critical vulnerability in PAN-OS exploited by APT29.",
+ "HAMMERTOSS is a backdoor malware family used by APT29 for C2 over Twitter.",
+ "PAN-OS is a network operating system developed by Palo Alto Networks.",
+ ],
+ extract_entities=True,
+ extract_relationships=True,
+)
+
+ontology = (
+ OntologyGenerator(base_uri="https://cti.example.org/ontology/", min_occurrences=1)
+ .generate_from_graph(graph.to_dict(), name="CyberOntology")
+)
+
+print(f"Classes inferred: {len(ontology.get('classes', []))}")
+# Classes inferred: 4 → ThreatActor, Vulnerability, Malware, Platform
+```
+
+---
+
+## Step 2 — Generate SHACL shapes from the ontology
+
+`SHACLGenerator` produces a `SHACLGraph` with one `NodeShape` per OWL class.
+
+```python
+from semantica.ontology import SHACLGenerator
+
+shacl_gen = SHACLGenerator(
+ base_uri="https://cti.example.org/shapes/",
+ include_inherited=True, # propagate parent-class constraints to sub-classes
+ severity="Violation", # default severity for all generated shapes
+ quality_tier="standard", # constraint strictness: "minimal" | "standard" | "strict"
+)
+
+shacl_graph = shacl_gen.generate(ontology)
+
+print(f"Node shapes generated: {len(shacl_graph.node_shapes)}")
+# Node shapes generated: 4 — one per class
+
+for ns in shacl_graph.node_shapes:
+ print(f" {ns.target_class} ({len(ns.property_shapes)} property constraints)")
+# https://cti.example.org/ontology/ThreatActor (2 property constraints)
+# https://cti.example.org/ontology/Vulnerability (3 property constraints)
+# https://cti.example.org/ontology/Malware (2 property constraints)
+# https://cti.example.org/ontology/Platform (1 property constraint)
+```
+
+The generated shapes tell you what the pipeline observed. They do not yet encode what your domain *requires*. The next section shows how to inject domain-specific mandatory constraints.
+
+---
+
+## Step 3 — Inject domain constraints
+
+Add mandatory `PropertyShape` constraints the pipeline cannot infer from data alone.
+
+```python
+from semantica.ontology import PropertyShape
+
+BASE = "https://cti.example.org/ontology/"
+
+for node_shape in shacl_graph.node_shapes:
+
+ if "Malware" in node_shape.target_class:
+ # family is required — missing it causes a Violation
+ node_shape.property_shapes.append(
+ PropertyShape(
+ path=f"{BASE}family",
+ min_count=1,
+ severity="Violation",
+ )
+ )
+ # attribution_confidence is recommended — missing it causes a Warning
+ node_shape.property_shapes.append(
+ PropertyShape(
+ path=f"{BASE}attribution_confidence",
+ min_count=1,
+ datatype="http://www.w3.org/2001/XMLSchema#float",
+ severity="Warning",
+ )
+ )
+
+ if "Vulnerability" in node_shape.target_class:
+ # cvss_score is required by your detection rules
+ node_shape.property_shapes.append(
+ PropertyShape(
+ path=f"{BASE}cvss_score",
+ min_count=1,
+ datatype="http://www.w3.org/2001/XMLSchema#float",
+ severity="Violation",
+ )
+ )
+
+ if "ThreatActor" in node_shape.target_class:
+ # name is required; nation_state classification is recommended
+ node_shape.property_shapes.append(
+ PropertyShape(path=f"{BASE}name", min_count=1, severity="Violation")
+ )
+ node_shape.property_shapes.append(
+ PropertyShape(path=f"{BASE}nation_state", min_count=1, severity="Warning")
+ )
+
+# Serialise the final shape graph to Turtle for reuse and version control
+shacl_ttl = shacl_gen.serialize(shacl_graph, format="turtle")
+
+with open("cti_shapes.ttl", "w") as f:
+ f.write(shacl_ttl)
+
+print("Shapes written to cti_shapes.ttl")
+```
+
+You can also construct shapes manually from scratch — useful when you need to express constraints the generator would never infer, such as a regex pattern on a CVE ID field:
+
+```python
+from semantica.ontology import NodeShape, PropertyShape, SHACLGraph
+
+# Require CVE IDs to match the canonical NIST format
+cve_id_shape = NodeShape(
+ target_class="https://cti.example.org/ontology/Vulnerability",
+ name="VulnerabilityShape",
+ closed=False,
+ severity="Violation",
+ property_shapes=[
+ PropertyShape(
+ path="https://cti.example.org/ontology/cve_id",
+ min_count=1,
+ pattern=r"^CVE-\d{4}-\d{4,}$", # e.g. CVE-2024-3400
+ severity="Violation",
+ ),
+ ],
+)
+# Inject into the existing shacl_graph or build a standalone SHACLGraph
+```
+
+---
+
+## Step 4 — Run validation and read the report
+
+Serialize the graph to RDF, then run `_run_pyshacl` against the shapes.
+
+```python
+from semantica.ontology.ontology_validator import _run_pyshacl
+from semantica.export import export_rdf
+import tempfile, os
+
+# Serialise the graph to a temporary Turtle file
+tmp = tempfile.NamedTemporaryFile(suffix=".ttl", delete=False, mode="w")
+export_rdf(graph.to_dict(), tmp.name, format="turtle")
+with open(tmp.name) as f:
+ data_ttl = f.read()
+os.unlink(tmp.name)
+
+# Run SHACL validation
+report = _run_pyshacl(
+ data_ttl,
+ shacl_ttl,
+ data_graph_format="turtle",
+ shacl_format="turtle",
+)
+
+# High-level summary
+print(f"Conforms : {report.conforms}")
+# Conforms : False ← at least one Violation found
+
+print(f"Violations : {report.violation_count}")
+# Violations : 3
+
+print(f"Warnings : {report.warning_count}")
+# Warnings : 2
+
+print(report.summary())
+# Graph does NOT conform: 3 violation(s).
+```
+
+The summary tells you something is wrong. Now drill into the details.
+
+---
+
+## Step 5 — Understand the violations
+
+Each `SHACLViolation` identifies the node, property path, and fix required.
+
+```python
+if not report.conforms:
+ # Print plain-English explanations for every violation
+ report.explain_violations()
+ # Node <https://cti.example.org/data/malware-002> is missing required property
+ # <https://cti.example.org/ontology/family>. At least 1 value(s) are required.
+ # Node <https://cti.example.org/data/vuln-003> is missing required property
+ # <https://cti.example.org/ontology/cvss_score>. At least 1 value(s) are required.
+ # Node <https://cti.example.org/data/vuln-003> has value 'CVE24-3400' for
+ # <https://cti.example.org/ontology/cve_id> which does not match the required pattern.
+
+ # Iterate for programmatic triage
+ for v in report.violations:
+ print(f"VIOLATION node={v.focus_node}")
+ print(f" path={v.result_path}")
+ print(f" rule={v.constraint}")
+ print(f" msg ={v.message}")
+ if v.value:
+ print(f" val ={v.value}")
+ if v.explanation:
+ print(f" fix ={v.explanation}")
+ print()
+
+ # Warnings are lower severity — review but do not block
+ for w in report.warnings:
+ print(f"WARNING {w.focus_node} {w.result_path} {w.message}")
+```
+
+The output maps directly to remediation tasks: `malware-002` needs a `family` property added; `vuln-003` needs a `cvss_score` and its `cve_id` corrected to the canonical format.
+
+---
+
+## Step 6 — Auto-remediate common violations
+
+Flag or patch nodes missing required properties, then re-validate to confirm.
+
+```python
+# Parse the report into a dict for programmatic processing
+report_dict = report.to_dict()
+
+# Collect nodes missing the 'family' property
+missing_family = [
+ v["focus_node"]
+ for v in report_dict.get("violations", [])
+ if "family" in (v.get("result_path") or "")
+]
+
+print(f"Malware nodes missing 'family': {len(missing_family)}")
+# In production: queue these for analyst enrichment or apply a default
+# e.g. graph.update_node(node_id, {"family": "UNKNOWN — requires triage"})
+
+# After remediation, re-run validation to confirm the fix
+# (re-export the patched graph to Turtle first, then call _run_pyshacl again)
+report2 = _run_pyshacl(patched_data_ttl, shacl_ttl)
+print(f"Violations after remediation: {report2.violation_count}")
+# Violations after remediation: 0
+```
+
+---
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+A DoD CTI team enforces STIX-compatible constraints on a threat graph before sharing it with ISAC partners. Every `ThreatActor` must declare a `name` and every `Vulnerability` must carry a `cvss_score`. The validation gate runs automatically on each nightly sync.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.ontology import OntologyGenerator, SHACLGenerator, PropertyShape
+from semantica.ontology.ontology_validator import _run_pyshacl
+from semantica.export import export_rdf
+import tempfile, os
+
+graph = ContextGraph()
+ctx = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ graph_expansion=True,
+)
+
+ctx.store([
+ "APT29 is a Russian state-sponsored threat actor targeting NATO governments.",
+ "CVE-2024-3400 is a critical PAN-OS vulnerability with CVSS 10.0, exploited by APT29.",
+ "HAMMERTOSS is a backdoor malware family used by APT29 for C2 over Twitter and GitHub.",
+], extract_entities=True, extract_relationships=True)
+
+ontology = (
+ OntologyGenerator(base_uri="https://cti.dod.mil/ontology/", min_occurrences=1)
+ .generate_from_graph(graph.to_dict(), name="CTIOntology")
+)
+
+shacl_gen = SHACLGenerator(
+ base_uri="https://cti.dod.mil/shapes/",
+ include_inherited=True,
+ severity="Violation",
+)
+shacl_graph = shacl_gen.generate(ontology)
+
+# STIX-aligned mandatory fields
+for ns in shacl_graph.node_shapes:
+ if "ThreatActor" in ns.target_class:
+ ns.property_shapes.append(
+ PropertyShape(path="https://cti.dod.mil/ontology/name", min_count=1, severity="Violation")
+ )
+ ns.property_shapes.append(
+ PropertyShape(path="https://cti.dod.mil/ontology/nation_state", min_count=1, severity="Warning")
+ )
+ if "Vulnerability" in ns.target_class:
+ ns.property_shapes.append(
+ PropertyShape(path="https://cti.dod.mil/ontology/cvss_score", min_count=1, severity="Violation")
+ )
+
+shacl_ttl = shacl_gen.serialize(shacl_graph, format="turtle")
+
+tmp = tempfile.NamedTemporaryFile(suffix=".ttl", delete=False, mode="w")
+export_rdf(graph.to_dict(), tmp.name, format="turtle")
+with open(tmp.name) as f:
+ data_ttl = f.read()
+os.unlink(tmp.name)
+
+report = _run_pyshacl(data_ttl, shacl_ttl)
+print(f"CTI graph conforms : {report.conforms}")
+print(f"Violations : {report.violation_count}")
+print(f"Warnings : {report.warning_count}")
+
+if not report.conforms:
+ report.explain_violations()
+ # Blocks the nightly ISAC share until violations are resolved
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+A SOC team validates zero-trust policy nodes before publishing them to the policy enforcement point. Every `Policy` node must carry a `version` (semver format) and an `effective_date`. A node missing either field is a Violation that blocks publication.
+
+```python
+from semantica.context import ContextGraph
+from semantica.ontology import OntologyGenerator, SHACLGenerator, PropertyShape
+from semantica.ontology.ontology_validator import _run_pyshacl
+from semantica.export import export_rdf
+import tempfile, os
+
+graph = ContextGraph()
+graph.add_node("policy-001", "Policy", "MFA Required for Tier-1 Resources",
+ version="1.0.0", effective_date="2025-01-01", owner="security_team")
+graph.add_node("policy-002", "Policy", "Admin Access Requires PAM Checkout")
+# policy-002 has no version or effective_date — Violations expected
+
+ontology = (
+ OntologyGenerator(base_uri="https://zerotrust.corp/ontology/", min_occurrences=1)
+ .generate_from_graph(graph.to_dict(), name="ZeroTrustOntology")
+)
+
+shacl_gen = SHACLGenerator(base_uri="https://zerotrust.corp/shapes/", severity="Violation")
+shacl_graph = shacl_gen.generate(ontology)
+
+BASE = "https://zerotrust.corp/ontology/"
+for ns in shacl_graph.node_shapes:
+ if "Policy" in ns.target_class:
+ ns.property_shapes += [
+ PropertyShape(
+ path=f"{BASE}version",
+ min_count=1,
+ pattern=r"^\d+\.\d+\.\d+$", # semver
+ severity="Violation",
+ ),
+ PropertyShape(
+ path=f"{BASE}effective_date",
+ min_count=1,
+ datatype="http://www.w3.org/2001/XMLSchema#date",
+ severity="Violation",
+ ),
+ ]
+
+shacl_ttl = shacl_gen.serialize(shacl_graph, format="turtle")
+
+tmp = tempfile.NamedTemporaryFile(suffix=".ttl", delete=False, mode="w")
+export_rdf(graph.to_dict(), tmp.name, format="turtle")
+with open(tmp.name) as f:
+ data_ttl = f.read()
+os.unlink(tmp.name)
+
+report = _run_pyshacl(data_ttl, shacl_ttl)
+print(f"Policy graph conforms: {report.conforms}")
+# Policy graph conforms: False
+
+for v in report.violations:
+ print(f" VIOLATION: {v.focus_node} — {v.result_path} — {v.message}")
+# VIOLATION: ...policy-002 — ...version — Less than 1 values on ...version
+# VIOLATION: ...policy-002 — ...effective_date — Less than 1 values on ...effective_date
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+A clinical informatics team validates trial ontology nodes before loading them into the trial registry system. Every `ClinicalTrial` node must declare a `phase` (one of Phase I–IV), a `primary_endpoint`, and a `principal_investigator`. Missing any of these blocks registry submission.
+
+```python
+from semantica.ontology import LLMOntologyGenerator, SHACLGenerator, PropertyShape
+from semantica.ontology.ontology_validator import _run_pyshacl
+from semantica.export import export_rdf
+import tempfile, os
+
+llm_gen = LLMOntologyGenerator(provider="openai", model="gpt-4o")
+ontology = llm_gen.generate_ontology_from_text(
+ """
+ A phase II oncology trial studies the efficacy of Compound XR-401 in NSCLC patients.
+ The trial is led by Principal Investigator Dr. Sarah Chen at Memorial Sloan Kettering.
+ Primary endpoint: overall response rate at 24 weeks.
+ Secondary endpoint: progression-free survival.
+ """
+)
+
+shacl_gen = SHACLGenerator(base_uri="https://purl.obolibrary.org/obo/TRIAL_shapes/")
+shacl_graph = shacl_gen.generate(ontology)
+
+TRIAL = "https://purl.obolibrary.org/obo/TRIAL_"
+for ns in shacl_graph.node_shapes:
+ if "ClinicalTrial" in ns.target_class or "Trial" in ns.target_class:
+ ns.property_shapes += [
+ PropertyShape(
+ path=f"{TRIAL}phase",
+ min_count=1,
+ in_values=["Phase I", "Phase II", "Phase III", "Phase IV"],
+ severity="Violation",
+ ),
+ PropertyShape(
+ path=f"{TRIAL}primary_endpoint",
+ min_count=1,
+ severity="Violation",
+ ),
+ PropertyShape(
+ path=f"{TRIAL}principal_investigator",
+ min_count=1,
+ severity="Warning",
+ ),
+ ]
+
+shacl_ttl = shacl_gen.serialize(shacl_graph, format="turtle")
+print(f"SHACL shapes generated — {len(shacl_graph.node_shapes)} node shapes")
+# SHACL shapes generated — 5 node shapes
+
+# Validate trial data
+tmp = tempfile.NamedTemporaryFile(suffix=".ttl", delete=False, mode="w")
+export_rdf(ontology, tmp.name, format="turtle")
+with open(tmp.name) as f:
+ data_ttl = f.read()
+os.unlink(tmp.name)
+
+report = _run_pyshacl(data_ttl, shacl_ttl)
+print(f"Trial data conforms: {report.conforms}")
+print(f"Warnings : {report.warning_count}")
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+A credit risk team validates every `LoanApplication` node against Basel III CRE20 mandatory fields (`ltv`, `pd`, `lgd`, `asset_class`) before the application enters the credit model. Any missing field is a Violation that rejects the record.
+
+```python
+from semantica.context import ContextGraph
+from semantica.ontology import OntologyGenerator, SHACLGenerator, PropertyShape
+from semantica.ontology.ontology_validator import _run_pyshacl
+from semantica.export import export_rdf
+import tempfile, os
+
+graph = ContextGraph()
+graph.add_node("loan-001", "LoanApplication", "Prime mortgage APP-2025-88421",
+ ltv=0.78, pd=0.023, lgd=0.45, asset_class="CRE")
+graph.add_node("loan-002", "LoanApplication", "SME working capital facility",
+ ltv=0.65)
+# loan-002 is missing pd, lgd, asset_class — three Violations expected
+
+ontology = (
+ OntologyGenerator(base_uri="https://basel.eba.eu/ontology/", min_occurrences=1)
+ .generate_from_graph(graph.to_dict(), name="BaselRiskOntology")
+)
+
+shacl_gen = SHACLGenerator(base_uri="https://basel.eba.eu/shapes/", severity="Violation")
+shacl_graph = shacl_gen.generate(ontology)
+
+BASE = "https://basel.eba.eu/ontology/"
+for ns in shacl_graph.node_shapes:
+ if "LoanApplication" in ns.target_class:
+ for field in ["ltv", "pd", "lgd", "asset_class"]:
+ ns.property_shapes.append(
+ PropertyShape(
+ path=f"{BASE}{field}",
+ min_count=1,
+ severity="Violation",
+ )
+ )
+
+shacl_ttl = shacl_gen.serialize(shacl_graph, format="turtle")
+
+tmp = tempfile.NamedTemporaryFile(suffix=".ttl", delete=False, mode="w")
+export_rdf(graph.to_dict(), tmp.name, format="turtle")
+with open(tmp.name) as f:
+ data_ttl = f.read()
+os.unlink(tmp.name)
+
+report = _run_pyshacl(data_ttl, shacl_ttl)
+print(f"Loan portfolio conforms: {report.conforms}")
+# Loan portfolio conforms: False
+
+print(f"Violations : {report.violation_count}")
+# Violations : 3
+
+for v in report.violations:
+ print(f" [{v.severity}] {v.focus_node.split('/')[-1]} — {v.result_path.split('/')[-1]}")
+# [Violation] loan-002 — pd
+# [Violation] loan-002 — lgd
+# [Violation] loan-002 — asset_class
+
+# Export violation report for regulatory audit trail
+report_dict = report.to_dict()
+```
+
+</Tab>
+
+</Tabs>
+
+---
+
+## Using SHACL validation as a CI/CD gate
+
+Call this function as a pre-publish gate; exit code 1 blocks the pipeline.
+
+```python
+import sys
+from semantica.ontology import OntologyGenerator, SHACLGenerator
+from semantica.ontology.ontology_validator import _run_pyshacl
+
+def validate_before_publish(data_graph_str: str, ontology: dict) -> None:
+ shacl_gen = SHACLGenerator(base_uri="https://example.org/shapes/")
+ shacl_graph = shacl_gen.generate(ontology)
+ shacl_ttl = shacl_gen.serialize(shacl_graph, format="turtle")
+
+ report = _run_pyshacl(data_graph_str, shacl_ttl)
+
+ if not report.conforms:
+ print(f"Graph validation FAILED — {report.violation_count} violation(s)")
+ report.explain_violations()
+ sys.exit(1)
+
+ print(f"Graph validation PASSED ({report.warning_count} warning(s))")
+```
+
+---
+
+## Related Guides
+
+- [Ontology Management](ontology) — generate the OWL ontology that SHACL shapes are derived from
+- [Reasoning & Rules](reasoning) — complement SHACL structural constraints with logical inference rules
+- [Export & Serialization](export) — serialize graph data to Turtle/RDF/XML for `_run_pyshacl` input
+- [Conflict Resolution](conflict-resolution) — detect and resolve data conflicts before SHACL validation
+- [Change Management](change-management) — version-gate SHACL shapes alongside ontology versions
diff --git a/docs/guides/visualization.md b/docs/guides/visualization.md
new file mode 100644
index 00000000..79b63827
--- /dev/null
+++ b/docs/guides/visualization.md
@@ -0,0 +1,540 @@
+---
+title: "Visualization"
+description: "Render knowledge graphs, ontology hierarchies, embedding projections, graph analytics, and temporal timelines as interactive HTML or static image files."
+icon: "chart-network"
+---
+
+`KGVisualizer`, `AnalyticsVisualizer`, `TemporalVisualizer`, and `OntologyVisualizer` turn graph dicts, analytics results, and ontologies into interactive HTML dashboards or static images in a single method call. Use them to present centrality rankings, community clusters, event timelines, and before/after snapshot diffs to stakeholders without writing any rendering code.
+
+<Info>
+ All visualizers accept `output="interactive"` (Plotly/pyvis HTML, shown in Jupyter or saved to file) or `output="static"` (PNG/SVG via Matplotlib). Omit `file_path` to get the figure object back for further manipulation.
+</Info>
+
+## Rendering the Full Knowledge Graph
+
+The first thing to put in front of stakeholders is the full network — nodes coloured by entity type, sized by degree centrality, with tooltips showing content on hover.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.visualization import KGVisualizer
+
+graph = ContextGraph(advanced_analytics=True)
+ctx = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ graph_expansion=True,
+)
+ctx.store([
+ "APT29 exploited CVE-2024-3400 targeting NATO defense contractors.",
+ "CVE-2024-3400 is a critical vulnerability in PAN-OS by Palo Alto Networks.",
+ "HAMMERTOSS is APT29's C2 backdoor operating over Twitter and GitHub.",
+ "APT29 conducted the SUNBURST supply chain attack against SolarWinds in 2020.",
+], extract_entities=True, extract_relationships=True)
+
+viz = KGVisualizer()
+
+# Interactive network — saved to HTML, opens in any browser
+viz.visualize_network(
+ graph = graph.to_dict(),
+ output = "interactive",
+ file_path = "reports/threat_graph.html",
+ node_color_by = "type", # colour each node by its entity type
+ node_size_by = "degree", # larger nodes = more connections
+ hover_data = ["type", "content"],
+)
+```
+
+The resulting HTML is fully self-contained — no server required. Share it as a file attachment and it renders in any browser with pan, zoom, and hover.
+
+For a static PNG suitable for a PDF report or a slide deck:
+
+```python
+viz.visualize_network(
+ graph = graph.to_dict(),
+ output = "static",
+ file_path = "reports/threat_graph.png",
+ node_color_by = "type",
+)
+```
+
+To highlight a specific attribution path through the graph — for example, the chain from APT29 through SUNBURST to SolarWinds — pass the node IDs as `highlight_path`:
+
+```python
+viz.visualize_network(
+ graph = graph.to_dict(),
+ output = "static",
+ file_path = "reports/apt29_path.png",
+ highlight_path = ["APT29", "SUNBURST", "SolarWinds"],
+)
+```
+
+## Showing Community Structure
+
+After community detection, you have a dict mapping community labels to node ID lists. `visualize_communities` on `KGVisualizer` overlays those clusters on the network; `AnalyticsVisualizer.visualize_community_structure` forwards to that same community graph view.
+
+```python
+from semantica.visualization import AnalyticsVisualizer
+
+# The community dict you get from graph analytics
+communities = {
+ "node_assignments": {
+ "apt29": 0,
+ "hammertoss": 0,
+ "nobelium": 0,
+ "sunburst": 0,
+ "cve-2024-3400": 1,
+ "pan-os": 1,
+ "globalprotect": 1,
+ "solarwinds": 2,
+ "orion-platform": 2,
+ "cve-2020-10148": 2,
+ },
+ "num_communities": 3,
+}
+
+# Network view with community colouring
+viz.visualize_communities(
+ graph = graph.to_dict(),
+ communities = communities,
+ output = "interactive",
+ file_path = "reports/communities_network.html",
+)
+
+# Standalone breakdown chart — for a slide on "what are the 12 clusters?"
+av = AnalyticsVisualizer()
+av.visualize_community_structure(
+ graph = graph.to_dict(),
+ communities = communities,
+ output = "interactive",
+ file_path = "reports/communities_breakdown.html",
+)
+```
+
+## Plotting Centrality Rankings
+
+The centrality dict maps node IDs to scores. Two calls cover the two use cases: a network view where node size reflects centrality, and a standalone ranked bar chart for the "top 10 most connected nodes" slide.
+
+```python
+centrality = {
+ "centrality": {
+ "apt29": 0.14,
+ "cve-2024-3400": 0.11,
+ "pan-os": 0.07,
+ "hammertoss": 0.06,
+ "nobelium": 0.05,
+ }
+}
+
+# Network coloured and sized by centrality score
+viz.visualize_centrality(
+ graph = graph.to_dict(),
+ centrality = centrality,
+ centrality_type= "pagerank",
+ output = "interactive",
+ file_path = "reports/centrality_network.html",
+)
+
+# Standalone ranked bar chart — most impactful nodes at a glance
+av.visualize_centrality_rankings(
+ centrality = centrality,
+ centrality_type = "pagerank",
+ output = "interactive",
+ file_path = "reports/centrality_rankings.html",
+)
+```
+
+## Analytics Charts: Connectivity and Degree Distribution
+
+After running graph analytics, two additional charts complete the picture. The connectivity chart shows how many disconnected components exist and how large each one is. The degree distribution shows the power-law shape of your graph — useful for confirming that your graph is scale-free (a few highly-connected hubs, many leaf nodes).
+
+```python
+# Connectivity — pass the analysis result dict directly
+# Keys the visualizer reads: "is_connected", "num_components", "component_sizes"
+connectivity = {
+ "is_connected": False,
+ "num_components": 3,
+ "component_sizes": [42, 8, 2],
+}
+
+av.visualize_connectivity(
+ connectivity = connectivity,
+ output = "interactive",
+ file_path = "reports/connectivity.html",
+)
+
+# Degree distribution — pass the graph dict directly
+av.visualize_degree_distribution(
+ graph = graph.to_dict(),
+ output = "interactive",
+ file_path = "reports/degree_distribution.html",
+)
+```
+
+<Info>
+ `visualize_connectivity` takes the connectivity analysis result dict — not `graph.to_dict()`. The dict must contain `"is_connected"`, `"num_components"`, and `"component_sizes"`. Compute it from your graph analytics output and pass the result.
+</Info>
+
+## Drawing a Timeline of Events
+
+When the story you are telling is temporal — a CVE lifecycle, an incident timeline, a campaign progression — `TemporalVisualizer.visualize_timeline` turns a list of timestamped events into a scrollable interactive chart.
+
+```python
+from semantica.visualization import TemporalVisualizer
+
+tv = TemporalVisualizer()
+
+# Events are passed inside a dict under the "events" key
+tv.visualize_timeline(
+ temporal_data = {"events": [
+ {"id": "pub", "label": "CVE-2024-3400 published", "timestamp": "2024-03-14T00:00:00"},
+ {"id": "exp", "label": "Zero-day exploitation begins", "timestamp": "2024-03-26T00:00:00"},
+ {"id": "patch", "label": "PAN-OS hotfix released", "timestamp": "2024-04-14T00:00:00"},
+ {"id": "rem", "label": "Contractor remediation confirmed","timestamp": "2024-04-30T00:00:00"},
+ ]},
+ output = "interactive",
+ file_path = "reports/cve_timeline.html",
+)
+```
+
+## Comparing Two Graph Snapshots Side-by-Side
+
+When the question is "what changed between March 14 and April 14?", `visualize_snapshot_comparison` takes two named snapshots from `TemporalVersionManager` and renders a side-by-side diff view showing nodes and edges added or removed.
+
+```python
+from semantica.change_management import TemporalVersionManager
+
+vm = TemporalVersionManager(storage_path="versions.db")
+snap1 = vm.get_version("pre_patch_march_14")
+snap2 = vm.get_version("post_patch_april_14")
+
+# Pass snapshots as a dict mapping label → snapshot dict
+tv.visualize_snapshot_comparison(
+ snapshots = {
+ "pre_patch_march_14": snap1,
+ "post_patch_april_14": snap2,
+ },
+ output = "interactive",
+ file_path = "reports/snapshot_diff.html",
+)
+```
+
+## Tracking Graph Growth Over Time
+
+The final chart for a stakeholder review is the growth curve — how many nodes and edges has the graph accumulated over the past year? `visualize_metrics_evolution` takes a history dict and a parallel timestamps list.
+
+```python
+# Build from TemporalVersionManager snapshots
+versions = vm.list_versions()
+versions.sort(key=lambda v: v["timestamp"])
+
+timestamps = [v["timestamp"][:10] for v in versions]
+metrics_history = {
+ "node_count": [len(v.get("nodes", [])) for v in versions],
+ "edge_count": [len(v.get("edges", [])) for v in versions],
+}
+
+tv.visualize_metrics_evolution(
+ metrics_history = metrics_history,
+ timestamps = timestamps,
+ output = "interactive",
+ file_path = "reports/graph_growth.html",
+)
+```
+
+Or populate the history dict directly from known quarterly milestones:
+
+```python
+tv.visualize_metrics_evolution(
+ metrics_history = {
+ "node_count": [50, 142, 309, 481],
+ "edge_count": [88, 387, 821, 1340],
+ },
+ timestamps = ["2025-01-01", "2025-04-01", "2025-07-01", "2025-10-01"],
+ output = "interactive",
+ file_path = "reports/graph_growth.html",
+)
+```
+
+## Domain Examples
+
+<Tabs>
+
+<Tab title="Defense — CTI/Threat">
+
+A full analyst briefing package: interactive threat network, community breakdown, CVE timeline, and graph growth curve — all generated from a live CTI graph before the morning standup.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer
+import os
+
+graph = ContextGraph(advanced_analytics=True)
+ctx = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ graph_expansion=True,
+)
+ctx.store([
+ "APT29 used HAMMERTOSS for C2 via Twitter and GitHub in 2020.",
+ "APT29 infrastructure cluster: 185.220.101.0/24, AS200651.",
+ "SolarWinds supply chain compromise attributed to APT29, campaign SUNBURST.",
+ "APT29 leveraged OAuth token theft against cloud workloads in 2023.",
+], extract_entities=True, extract_relationships=True)
+
+os.makedirs("reports", exist_ok=True)
+
+kg_viz = KGVisualizer()
+
+# Full network — interactive for the analyst portal
+kg_viz.visualize_network(
+ graph = graph.to_dict(),
+ output = "interactive",
+ file_path = "reports/cti_network.html",
+ node_color_by = "type",
+ node_size_by = "degree",
+ hover_data = ["type", "content"],
+)
+
+# Attribution path PNG for the slide deck
+kg_viz.visualize_network(
+ graph = graph.to_dict(),
+ output = "static",
+ file_path = "reports/apt29_sunburst_path.png",
+ highlight_path = ["APT29", "SUNBURST", "SolarWinds"],
+)
+
+# Connectivity overview
+av = AnalyticsVisualizer()
+av.visualize_connectivity(
+ connectivity = {"is_connected": True, "num_components": 1, "component_sizes": [24]},
+ output = "interactive",
+ file_path = "reports/connectivity.html",
+)
+
+# CVE-2024-3400 incident timeline
+tv = TemporalVisualizer()
+tv.visualize_timeline(
+ temporal_data = {"events": [
+ {"id": "pub", "label": "CVE-2024-3400 published", "timestamp": "2024-03-14"},
+ {"id": "exp", "label": "Zero-day exploitation", "timestamp": "2024-03-26"},
+ {"id": "patch", "label": "PAN-OS hotfix released", "timestamp": "2024-04-14"},
+ {"id": "rem", "label": "Remediation confirmed", "timestamp": "2024-04-30"},
+ ]},
+ output = "interactive",
+ file_path = "reports/cve_timeline.html",
+)
+```
+
+</Tab>
+
+<Tab title="Security — SOC/Incident">
+
+During an active incident, the SOC generates a lateral movement network with the attack path highlighted, a centrality ranking to identify which hosts are most pivotal, and a relationship matrix to show who connects to what.
+
+```python
+from semantica.context import ContextGraph
+from semantica.visualization import KGVisualizer, AnalyticsVisualizer
+
+graph = ContextGraph(advanced_analytics=True)
+
+for node_id, ntype, content in [
+ ("wkstn-047", "Host", "Compromised workstation WKSTN-047"),
+ ("dc01", "Host", "Domain controller DC01"),
+ ("jsmith", "User", "Compromised user jsmith"),
+ ("psexec", "Tool", "PsExec lateral movement tool"),
+ ("t1021", "MITRE", "T1021.002 SMB/Admin Shares"),
+]:
+ graph.add_node(node_id, ntype, content)
+
+graph.add_edge("wkstn-047", "dc01", "lateral_movement", weight=1.0)
+graph.add_edge("jsmith", "wkstn-047","session_on", weight=0.9)
+graph.add_edge("psexec", "wkstn-047","executed_on", weight=1.0)
+graph.add_edge("psexec", "t1021", "implements", weight=0.95)
+
+viz = KGVisualizer()
+
+# Incident network with lateral movement path highlighted
+viz.visualize_network(
+ graph = graph.to_dict(),
+ output = "interactive",
+ file_path = "soc/incident_graph.html",
+ node_color_by = "type",
+ highlight_path = ["wkstn-047", "dc01"],
+ hover_data = ["type", "content"],
+)
+
+# Relationship matrix — who connects to what
+viz.visualize_relationship_matrix(
+ graph = graph.to_dict(),
+ output = "interactive",
+ file_path = "soc/rel_matrix.html",
+)
+
+# Centrality rankings — which host is most pivotal?
+av = AnalyticsVisualizer()
+av.visualize_centrality_rankings(
+ centrality = {"wkstn-047": 0.35, "dc01": 0.28, "psexec": 0.22, "jsmith": 0.15},
+ centrality_type = "degree",
+ output = "interactive",
+ file_path = "soc/centrality.html",
+)
+```
+
+</Tab>
+
+<Tab title="Life Science — Clinical/Pharma">
+
+A drug repurposing exploration: interactive drug-target-disease network, OWL class hierarchy, UMAP embedding projection, and a similarity heatmap to spot structurally equivalent compounds.
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.visualization import KGVisualizer, EmbeddingVisualizer, OntologyVisualizer
+from semantica.ontology import OntologyGenerator
+
+graph = ContextGraph(advanced_analytics=True)
+ctx = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=graph,
+ graph_expansion=True,
+)
+ctx.store([
+ "Metformin activates AMPK and reduces hepatic glucose production in Type 2 Diabetes.",
+ "Dapagliflozin inhibits SGLT2 and reduces cardiovascular mortality in HFrEF.",
+ "Semaglutide agonises GLP-1R and reduces HbA1c in obesity and Type 2 Diabetes.",
+], extract_entities=True, extract_relationships=True)
+
+kg_viz = KGVisualizer()
+kg_viz.visualize_network(
+ graph = graph.to_dict(),
+ output = "interactive",
+ file_path = "drug_kg.html",
+ node_color_by = "type",
+ node_size_by = "degree",
+)
+
+# OWL class hierarchy
+ontology = OntologyGenerator(
+ base_uri="https://purl.obolibrary.org/obo/DRUG_",
+ min_occurrences=1,
+).generate_from_graph(graph.to_dict())
+
+ov = OntologyVisualizer()
+ov.visualize_hierarchy(ontology, output="interactive", file_path="drug_hierarchy.html")
+ov.visualize_structure(ontology, output="interactive", file_path="drug_ontology.html")
+
+# UMAP projection and similarity heatmap for drug embeddings
+embeddings = [[0.1, 0.2, 0.3], [0.15, 0.22, 0.31], [0.8, 0.7, 0.6]]
+labels = ["Metformin", "Dapagliflozin", "Semaglutide"]
+
+ev = EmbeddingVisualizer()
+ev.visualize_2d_projection(
+ embeddings, labels, method="umap",
+ output="interactive", file_path="drug_embeddings.html",
+)
+ev.visualize_similarity_heatmap(
+ embeddings, labels,
+ output="interactive", file_path="drug_similarity.html",
+)
+```
+
+</Tab>
+
+<Tab title="Banking — Risk/Compliance">
+
+Regulatory knowledge graph for model governance: entity network, OWL class hierarchy for documentation, and a graph growth curve across quarterly Basel III updates — all in static PNG for the model governance committee pack.
+
+```python
+from semantica.context import ContextGraph
+from semantica.change_management import TemporalVersionManager
+from semantica.visualization import KGVisualizer, TemporalVisualizer, OntologyVisualizer
+from semantica.ontology import OntologyGenerator
+
+graph = ContextGraph(advanced_analytics=True)
+vm = TemporalVersionManager(storage_path="regulatory_versions.db")
+
+for node, ntype, content in [
+ ("bcbs-cre20", "Regulation", "Basel III CRE20 — CRE capital requirements"),
+ ("metric-ltv", "Metric", "Loan-to-Value Ratio"),
+ ("metric-dscr", "Metric", "Debt Service Coverage Ratio"),
+ ("metric-pd", "Metric", "Probability of Default"),
+ ("metric-lgd", "Metric", "Loss Given Default"),
+]:
+ graph.add_node(node, ntype, content)
+
+graph.add_edge("bcbs-cre20", "metric-ltv", "requires", weight=1.0)
+graph.add_edge("bcbs-cre20", "metric-dscr", "requires", weight=1.0)
+graph.add_edge("bcbs-cre20", "metric-pd", "requires", weight=0.9)
+graph.add_edge("bcbs-cre20", "metric-lgd", "requires", weight=0.9)
+
+kg_viz = KGVisualizer()
+kg_viz.visualize_network(
+ graph = graph.to_dict(),
+ output = "static",
+ file_path = "regulatory/regulatory_kg.png",
+ node_color_by = "type",
+ node_size_by = "degree",
+)
+
+# OWL hierarchy — static PNG for the documentation appendix
+ontology = OntologyGenerator(
+ base_uri="https://basel.eba.eu/ontology/",
+ min_occurrences=1,
+).generate_from_graph(graph.to_dict())
+
+ov = OntologyVisualizer()
+ov.visualize_hierarchy(ontology, output="static", file_path="regulatory/class_hierarchy.png")
+
+# Graph growth curve across quarterly snapshots
+tv = TemporalVisualizer()
+tv.visualize_metrics_evolution(
+ metrics_history = {
+ "node_count": [12, 18, 25, 31],
+ "edge_count": [8, 15, 24, 32],
+ },
+ timestamps = ["2025-01-01", "2025-04-01", "2025-07-01", "2025-10-01"],
+ output = "interactive",
+ file_path = "regulatory/graph_growth.html",
+)
+
+# Snapshot comparison — what changed between Q2 and Q3 Basel update?
+snap1 = vm.get_version("basel_q2_2025")
+snap2 = vm.get_version("basel_q3_2025")
+if snap1 and snap2:
+ tv.visualize_snapshot_comparison(
+ snapshots = {"basel_q2_2025": snap1, "basel_q3_2025": snap2},
+ output = "interactive",
+ file_path = "regulatory/snapshot_diff.html",
+ )
+```
+
+</Tab>
+
+</Tabs>
+
+## Output Modes
+
+Every visualizer method accepts the same two output modes:
+
+| `output` value | Format | Best for |
+| :------------- | :----- | :------- |
+| `"interactive"` | Self-contained HTML (Plotly / pyvis) | Jupyter notebooks, analyst portals, email attachments |
+| `"static"` | PNG / SVG (Matplotlib) | PDF reports, slide decks, regulatory submissions |
+
+To get the figure object instead of writing to disk, omit `file_path`:
+
+```python
+fig = viz.visualize_network(graph.to_dict(), output="interactive")
+fig.show() # renders inline in Jupyter
+fig.write_html("out.html") # manual export
+```
+
+## Related Guides
+
+- [Context Graphs](context-graphs) — `graph.to_dict()` is the primary input for `KGVisualizer`
+- [Ontology Management](ontology) — `OntologyVisualizer` renders ontologies produced by `OntologyGenerator`
+- [Change Management](change-management) — `TemporalVersionManager` snapshots feed `visualize_metrics_evolution()` and `visualize_snapshot_comparison()`
+- [Graph Analytics](graph-analytics) — centrality scores, community dicts, and connectivity results that feed the `AnalyticsVisualizer`
+- [Export & Serialization](export) — export the same graph to GraphML, GEXF, or DOT for Gephi and Graphviz