# How to Implement Decision Intelligence with Causal Chains in Semantica AGI

> Learn to implement decision intelligence with causal chains in Semantica AGI. Transform raw data into auditable decisions and enforce policy compliance throughout the decision lifecycle.

- Repository: [Semantica /semantica](https://github.com/semantica-agi/semantica)
- Tags: how-to-guide
- Published: 2026-08-18

---

**Semantica AGI provides a full-stack pipeline that transforms raw data into auditable decisions by recording decision metadata, linking causal relationships via the Context subsystem, and exposing governance APIs that enforce policy compliance across the decision lifecycle.**

Semantica AGI is an open-source framework designed for transparent, policy-driven AI reasoning. By implementing decision intelligence with causal chains, developers can trace every choice from raw data ingestion through to final audit trails. The repository `semantica-agi/semantica` exposes this functionality through the **Context** subsystem (`semantica/context`), which serves as the central hub for recording decisions, establishing causal edges, and querying decision ancestry.

## Understanding the Three-Layer Architecture

The decision intelligence capabilities are built atop a structured data pipeline defined in [`ARCHITECTURE.md`](https://github.com/semantica-agi/semantica/blob/main/ARCHITECTURE.md). The system processes information through three distinct logical layers before decisions are recorded and linked.

**Ingestion → Normalization** (`semantica.ingest`, `semantica.parse`, `semantica.normalize`) pulls data from files, databases, streams, and cloud services, converting inputs into clean, split-ready fragments.

**Knowledge-Graph Construction** (`semantica.semantic_extract`, `semantica.conflicts`, `semantica.deduplication`, `semantica.kg`) extracts entities, relations, and events to assemble a **knowledge graph (KG)** with resolved conflicts and deduplicated nodes.

**Intelligence → Store → Serve** (`semantica.ontology`, `semantica.reasoning`, **`semantica.context`**, `semantica.vector_store`, `semantica.graph_store`) enriches the KG with validation and provenance, then creates the **causal-chain-enabled context graph** that powers decision recording and auditing.

## The Five-Stage Decision Intelligence Lifecycle

Semantica implements decision intelligence through five API-driven stages orchestrated by the Context class in [`semantica/context/__init__.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/__init__.py).

### 1. Recording Decisions with `record_decision()`

The lifecycle begins when `record_decision()` captures a decision along with its **scenario**, **reasoning**, **outcome**, **confidence**, and custom metadata. This function creates a **Decision node** in the context graph and generates a corresponding dense vector in the vector store for semantic retrieval.

### 2. Building Causal Chains via `add_causal_relationship()`

Decisions rarely exist in isolation. The `add_causal_relationship()` function (exposed through `semantica.context.causal`) links decisions, data artifacts, or KG facts via typed edges including **triggers**, **enables**, **causes**, and **precedes**. Each edge carries timestamps, confidence scores, and provenance metadata, enabling downstream traversal of decision ancestry.

### 3. Querying Decision History

The Context API provides semantic search capabilities through functions like `find_similar_decisions()`, which queries the vector store for precedent cases, and `trace_decision_chain()`, which performs graph traversals to reconstruct the full lineage of any decision node. The `analyze_decision_impact()` function evaluates ripple effects across downstream entities.

### 4. Governance and Policy Enforcement

Before finalization, `check_decision_rules()` evaluates policy scripts—such as compliance or risk-management rules—against the decision node and its causal context. This stage can block or flag decisions that violate organizational constraints, ensuring policy-driven AI reasoning.

### 5. Audit and Provenance Export

The final stage uses `export_decision_audit()` to serialize the complete provenance chain into W3C PROV-O, CSV, or JSON formats. This produces regulator-ready audit trails that capture the full causal history linking raw data to final outcomes.

## Representing Causal Relationships in the Graph

The causal subgraph uses a strict node-edge schema optimized for both graph traversals and vector similarity search.

**Node Types** include `Decision`, `Fact`, `Entity`, `Event`, and `Policy`. **Edge Types** include `causes`, `triggers`, `enables`, `precedes`, and `derivedFrom`.

The causal data is persisted in a **graph store** (Neo4j, Amazon Neptune, etc.) for relationship queries, while dense vector representations are stored in a **vector store** (FAISS, Qdrant, PgVector) via `semantica.vector_store` to enable fast semantic similarity matching across decision scenarios.

## Implementation Guide: Code Examples

The following practical implementation demonstrates the complete decision intelligence flow using the actual source APIs:

```python

# 1️⃣ Record a decision -------------------------------------------------

from semantica.context import Context

ctx = Context()                     # creates/loads the context graph

decision_id = ctx.record_decision(
    scenario="Approve loan for applicant #12345",
    category="finance",
    outcome="approved",
    reasoning="Credit score > 720, debt-to-income < 30 %",
    confidence=0.96,
    metadata={"applicant_id": "12345", "loan_amount": 250_000},
)
print(f"Decision recorded with ID: {decision_id}")

# 2️⃣ Link causal relationships ----------------------------------------

# Suppose the decision was triggered by a risk-model output

risk_output_id = ctx.add_fact(
    name="RiskModelScore",
    value=0.85,
    source="risk-model-v2",
)
ctx.add_causal_relationship(
    from_node=risk_output_id,
    to_node=decision_id,
    relationship_type="triggers",
    weight=0.85,
)

# 3️⃣ Query similar decisions -------------------------------------------

similar = ctx.find_similar_decisions(
    scenario="Approve loan for applicant #98765",
    limit=5,
)
for d in similar:
    print(d["decision_id"], d["outcome"], d["similarity"])

# 4️⃣ Trace the full causal chain ---------------------------------------

chain = ctx.trace_decision_chain(decision_id)
for step in chain:
    print(f"{step['type']}: {step['id']} → {step['relation']} → {step['target_id']}")

# 5️⃣ Govern the decision ------------------------------------------------

policy_result = ctx.check_decision_rules(decision_id, policy_name="CreditCompliance")
if not policy_result["allowed"]:
    raise RuntimeError(f"Decision {decision_id} violates policy: {policy_result['reason']}")

# 6️⃣ Export audit trail -------------------------------------------------

audit_json = ctx.export_decision_audit(decision_id, fmt="json")
with open("audit.json", "w") as f:
    f.write(audit_json)

```

**Key Imports Explained:**

- `Context` from [`semantica/context/__init__.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/__init__.py) provides the core API for recording and governing decisions.
- Helper functions like `find_similar_decisions` are implemented in [`semantica/vector_store/decision_vector_methods.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/decision_vector_methods.py).
- End-to-end usage patterns are validated in [`tests/vector_store/test_simple_end_to_end.py`](https://github.com/semantica-agi/semantica/blob/main/tests/vector_store/test_simple_end_to_end.py).

## Key Source Files for Decision Intelligence

| File | Role |
|------|------|
| [`ARCHITECTURE.md`](https://github.com/semantica-agi/semantica/blob/main/ARCHITECTURE.md) | Visual overview of the pipeline and decision-intelligence lifecycle with Mermaid diagrams describing data flow and KG enrichment. |
| [`semantica/context/__init__.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/__init__.py) | Core Context class implementing `record_decision`, causal linking, governance checks, and audit exports. |
| [`semantica/vector_store/decision_vector_methods.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/decision_vector_methods.py) | Vector-store utilities including `quick_decision`, `find_similar_decisions`, and `explain` for semantic search. |
| [`tests/vector_store/test_simple_end_to_end.py`](https://github.com/semantica-agi/semantica/blob/main/tests/vector_store/test_simple_end_to_end.py) | Concrete usage patterns demonstrating decision recording, causal edge linking, and query validation. |
| [`semantica/visualization/visualization_provenance.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/visualization_provenance.py) | Graph rendering tools for exploring and debugging causal decision chains. |

## Summary

- **Semantica AGI** implements decision intelligence through a **Context** subsystem that bridges knowledge graphs and vector stores.
- The **`record_decision()`** API captures decision metadata while **`add_causal_relationship()`** establishes traceable causal edges between decisions and data sources.
- **Causal chains** are represented as typed edges (`triggers`, `causes`, `enables`) connecting nodes like `Decision`, `Fact`, and `Entity` in both graph and vector stores.
- **Governance functions** like `check_decision_rules()` enforce compliance by evaluating policies against the causal context before finalizing decisions.
- Full **audit trails** are exportable via `export_decision_audit()` in W3C PROV-O or JSON formats for regulatory compliance.

## Frequently Asked Questions

### How does Semantica AGI store and query causal relationships between decisions?

Causal relationships are stored as typed edges in a graph database (Neo4j, Amazon Neptune) through the `semantica.graph_store` module, while `semantica.vector_store` maintains dense vector representations of decision scenarios for semantic similarity search. The `trace_decision_chain()` function traverses the graph edges (`causes`, `triggers`, `enables`), while `find_similar_decisions()` queries the vector store for precedent cases based on scenario embeddings.

### What is the difference between the knowledge graph and the context graph in Semantica?

The **knowledge graph** (KG) built by `semantica.kg` contains extracted entities, relations, and coreference chains from raw data. The **context graph** managed by `semantica.context` enriches this KG with decision-specific nodes, causal edges, and provenance metadata. While the KG represents general world knowledge, the context graph specifically tracks the decision lifecycle and policy governance states.

### Which file contains the implementation of decision governance and policy checking?

Policy enforcement is implemented in [`semantica/context/__init__.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/__init__.py) within the `Context` class. The `check_decision_rules()` method evaluates policy scripts against decision nodes and their causal ancestors, returning allowance flags and violation reasons. This integration allows real-time governance before decisions are finalized and exported.

### Can Semantica export decision trails for regulatory audits?

Yes. The `export_decision_audit()` function in [`semantica/context/__init__.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/__init__.py) serializes the complete causal chain—including all `Decision` nodes, `Fact` sources, and edge provenance—into W3C PROV-O, CSV, or JSON formats. This satisfies requirements for transparent, auditable AI systems in regulated industries like finance and healthcare.