How to Trace Decision Causality Using Semantica: A Complete Guide

Semantica traces decision causality by walking backward through a Context Graph, following explicit causal edges and implicit links derived from shared entities and timestamps to reconstruct complete causal chains.

Every decision recorded in the semantica-agi/semantica framework is stored as a node in a Context Graph with rich metadata including scenario descriptions, reasoning, confidence scores, and entity references. When you need to trace decision causality, the system reconstructs the lineage of how one decision led to another by traversing these interconnected nodes through both explicit and inferred relationships.

Understanding the Context Graph Structure

The foundation of causal tracing lies in how Semantica stores decisions. Each decision node contains metadata such as category, scenario, reasoning, outcome, confidence, timestamp, and the entities it mentions. According to the source code in semantica/context/context_graph.py, the record_decision method creates these nodes, while add_causal_relationship establishes explicit directional edges between them.

When a decision is recorded, the system indexes it by timestamp and entity references. This indexing enables the causal chain reconstruction that identifies which earlier decisions directly caused subsequent ones and which influenced them indirectly through shared context.

The Two-Layer Causal Tracing Architecture

Semantica implements decision causality tracing across two distinct layers: a low-level graph traversal engine and a high-level explainability interface.

Core Graph Traversal with trace_decision_causality

The primary algorithm resides in semantica/context/context_graph.py at line 75 within the ContextGraph.trace_decision_causality method. This function walks the graph backward from a target decision, following:

  • Explicit edges (added via add_causal_relationship with types like CAUSES or CAUSED)
  • Implicit links inferred from decisions sharing entities with earlier timestamps

The method returns a list of dictionaries, each describing a causal hop containing the source decision, target decision, relationship type, and edge weight. As implemented in the source, the traversal builds a reverse index of explicit causal edges (incoming_causal_edges) and recursively explores predecessors, stopping when max_depth is reached, a cycle is detected, or max_chains is exceeded.

High-Level Explainability with AgentContext

Most user-facing tools interact with AgentContext.trace_decision_explainability located in semantica/context/agent_context.py at line 208. This helper first extracts upstream and downstream chains using ContextGraph.get_causal_chain, then enriches them with relationship paths from the DecisionQuery layer (trace_decision_path from semantica/context/decision_query.py).

This two-layer approach ensures that low-level graph operations remain optimized while providing a comprehensive API for CLI tools, MCP integrations, and CrewAI implementations.

The Decision Intelligence Lifecycle

The causal-linking capability fits into Semantica's broader Decision Intelligence Lifecycle, which follows a "Record → Link → Query → Govern → Audit" flow as documented in the repository's Architecture documentation.

Step Implementation Code Location
Record ContextGraph.record_decision creates nodes with metadata semantica/context/context_graph.py
Link add_causal_relationship stores explicit edges; implicit links derived from shared entities/timestamps semantica/context/context_graph.py
Query trace_decision_causality traverses the reverse index with max_depth and max_chains limits semantica/context/context_graph.py
Explainability AgentContext.trace_decision_explainability combines chains with path queries semantica/context/agent_context.py
Govern & Audit Policy evaluation via PolicyEngine.check_decision_rules and W3C PROV-O export semantica/policy/ and semantica/provenance/

How the Causal Traversal Algorithm Works

The algorithm guaranteeing deterministic causal chains operates through four distinct phases:

  1. Reverse Index Construction: The system first builds an index of incoming_causal_edges to enable efficient backward traversal from any target decision.

  2. Recursive Predecessor Exploration: For each decision node, the algorithm first follows explicit causal edges, then identifies potential implicit causes by checking other decisions that share entities and bear earlier timestamps.

  3. Chain Reporting: Each discovered path is compiled using _build_causal_chain_report, preserving original scenario strings, edge types, and weights for human-readable output.

  4. Boundary Enforcement: The traversal respects configurable limits (max_depth, max_chains) and detects cycles. When limits are exceeded, the result includes a {"truncated": True} marker.

This design ensures explicit edges always dominate over inferred connections, providing deterministic results even in dense knowledge graphs.

Practical Implementation Examples

from semantica.context import AgentContext

# Initialize agent context

ctx = AgentContext()

# Record initial decision

d1 = ctx.record_decision(
    category="risk",
    scenario="Identify fraud pattern",
    reasoning="Unusual transaction volume detected",
    outcome="Flagged",
    confidence=0.92,
    entities=["account_123", "merchant_X"],
)

# Record subsequent decision

d2 = ctx.record_decision(
    category="mitigation",
    scenario="Block suspicious account",
    reasoning="High fraud risk from previous flags",
    outcome="Blocked",
    confidence=0.95,
    entities=["account_123"],
)

# Explicitly define causal relationship

ctx.add_causal_relationship(
    source_id=d1,
    target_id=d2,
    edge_type="CAUSED",
    weight=0.9,
)

High-Level Causal Tracing


# Trace full explainability including upstream/downstream chains

causal_info = ctx.trace_decision_explainability(d2)

print("Upstream causes:")
for hop in causal_info["upstream_decisions"]:
    print(f"- {hop['from_scenario']} → {hop['to_scenario']} ({hop['type']})")

Low-Level Graph Access


# Access the underlying ContextGraph directly

graph = ctx.knowledge_graph

# Trace with specific limits

chains = graph.trace_decision_causality(
    d2, 
    max_depth=3, 
    max_chains=10
)

for chain in chains:
    print("Causal Chain:")
    for hop in chain["path"]:
        print(f"  {hop['from_scenario']} → {hop['to_scenario']} [{hop['type']}]")

Summary

  • Decision causality in Semantica is traced through a Context Graph that stores decisions as nodes with rich metadata and relationships as edges.
  • The trace_decision_causality method in semantica/context/context_graph.py implements the core backward-walking algorithm, handling both explicit edges and implicit entity-sharing links.
  • For production use, trace_decision_explainability in semantica/context/agent_context.py provides the recommended high-level interface that combines upstream/downstream analysis with path querying.
  • The traversal algorithm uses reverse indexing for performance, respects cycle detection, and enforces configurable limits via max_depth and max_chains parameters.
  • Every causal hop preserves scenario strings and confidence weights, making the output suitable for audit trails, policy enforcement, and visualizations.

Frequently Asked Questions

What is the difference between explicit and implicit causal edges in Semantica?

Explicit causal edges are created when you call add_causal_relationship with a specific edge type such as CAUSES or INFLUENCES. Implicit links are inferred automatically by the trace_decision_causality algorithm when it detects that two decisions share common entities and the earlier decision predates the later one by timestamp. According to the source code in semantica/context/context_graph.py, explicit edges always take precedence during traversal, ensuring deterministic results.

How does Semantica prevent infinite loops when tracing decision causality?

The implementation includes cycle detection within the recursive traversal algorithm. When trace_decision_causality explores the graph, it tracks visited nodes to prevent re-processing. If the traversal reaches the configured max_depth or max_chains limits, it terminates and returns a truncated marker ({"truncated": True}) in the results, ensuring the function completes even in densely interconnected graphs.

Can I export causal chains for audit purposes?

Yes. The causal chains generated by trace_decision_causality and trace_decision_explainability contain structured data including scenario descriptions, reasoning, timestamps, and confidence scores suitable for audit logs. Additionally, Semantica supports exporting provenance data to W3C PROV-O format through modules in semantica/provenance/, allowing integration with external governance and compliance tools.

What is the maximum depth limit for causal chain tracing?

The default limits are configurable through the max_depth and max_chains parameters of trace_decision_causality. While the source code does not enforce a hard global maximum, practical implementations should set these bounds based on graph density. When the algorithm encounters the limit, it includes the truncation flag in the returned chain data, indicating that additional causal relationships may exist beyond the explored boundary.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →