Metadata-Version: 2.4
Name: agent-causality
Version: 0.3.2
Summary: Causal capture SDK for branching multi-agent systems
License-Expression: AGPL-3.0-only
Project-URL: Homepage, https://github.com/Psionic-labs/Agent-Causality
Project-URL: Repository, https://github.com/Psionic-labs/Agent-Causality
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.2.0; extra == "postgres"
Provides-Extra: explain
Requires-Dist: httpx>=0.27.0; extra == "explain"
Provides-Extra: langgraph
Requires-Dist: langchain-core>=0.3.0; extra == "langgraph"
Provides-Extra: all
Requires-Dist: psycopg[binary]>=3.2.0; extra == "all"
Requires-Dist: httpx>=0.27.0; extra == "all"
Requires-Dist: langchain-core>=0.3.0; extra == "all"
Dynamic: license-file

<h1 align="center">
  <img src="https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/media/agent-causality-logo-dark.png" alt="Agent-Causality" width="640" />
</h1>

[![PyPI version](https://img.shields.io/pypi/v/agent-causality?label=PyPI)](https://pypi.org/project/agent-causality/)
[![npm version](https://img.shields.io/npm/v/@psionic-labs/opencode-agent-causality)](https://www.npmjs.com/package/@psionic-labs/opencode-agent-causality)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/)
[![License: AGPL-3.0-only](https://img.shields.io/badge/license-AGPL--3.0--only-green)](https://github.com/Psionic-labs/Agent-Causality/blob/main/LICENSE)

Agent-Causality records agent runs as event graphs. You can trace a failure
back through its recorded dependencies. If you register a decision evaluator
and baseline inputs, you can replay the decision to see which input changes
would change its outcome.

[Website](https://psionic-labs.github.io/Agent-Causality/) ·
[Video walkthrough](https://www.youtube.com/watch?v=bogmzYe9Hzs) ·
[Getting started](https://github.com/Psionic-labs/Agent-Causality/blob/main/GETTING_STARTED.md)

- [Install](#install)
- [Replay a failed decision](#replay-a-failed-decision)
- [Use the CLI](#use-the-cli)
- [Tour the Explorer](#tour-the-explorer)
- [Capture OpenCode](#capture-an-opencode-session), [LangGraph](#capture-a-langgraph-run), or [your own Python agents](#instrument-your-own-python-agents)
- [Use OpenRouter](#generate-an-openrouter-explanation) or [PostgreSQL](#use-postgresql)
- [Run the benchmarks](#run-the-benchmarks) and [verify the checkout](#develop-and-verify-the-checkout)

## Install

Use Python 3.11 or later. The Python package installs the SDK, the
`causality` CLI (also available as `agent-causality`), the Explorer,
the OpenCode receiver, and the benchmark runner.

```bash
python -m pip install agent-causality
```

In a project managed by uv, use `uv add agent-causality`. To work from source,
clone the repository and run `uv sync` from its root. Prefix commands from the
Python package with `uv run` when using the checkout.

```bash
git clone https://github.com/Psionic-labs/Agent-Causality.git
cd Agent-Causality
uv sync
```

| Optional extra | What it installs |
| --- | --- |
| `agent-causality[explain]` | HTTP client for OpenRouter explanations |
| `agent-causality[langgraph]` | LangChain Core for the LangGraph adapter |
| `agent-causality[postgres]` | PostgreSQL driver |
| `agent-causality[all]` | All three Python extras |

Use the same extra with `uv add` or run `uv sync --extra EXTRA` in the
checkout.

> **Package-only OpenCode setup.** Install both packages for the full live
> OpenCode workflow. The [PyPI package](https://pypi.org/project/agent-causality/)
> (`agent-causality`) provides the receiver, SQLite storage, CLI, and Explorer.
> The [npm package](https://www.npmjs.com/package/@psionic-labs/opencode-agent-causality)
> (`@psionic-labs/opencode-agent-causality`) captures and forwards OpenCode
> events. Follow [Capture an OpenCode session](#capture-an-opencode-session)
> to install and use both.

## Replay a failed decision

Run the offline example after installing the Python package.

```bash
python -m examples.customer_approval
```

From a source checkout, run `uv run python -m examples.customer_approval`.
The example writes to `.causality/example.db` and opens it in a fresh CLI
process. The replay uses local Python code and needs no API key.

```text
Outcome: approved
Evidence:
- Minimal tested chain: customer_status + risk_score -> decision -> terminal failure (4 events).
- Recorded inputs were customer_status='eligible' and risk_score=0.2; their canonical baselines are 'ineligible' and 0.8.
- The structural slice contains 8 events; replay reduced it to the smaller tested subset above.
```

The example marks the approval as a failure. Substituting either baseline
changes the decision to `rejected`. That identifies inputs that matter to
the recorded decision under the tested substitutions. Why the upstream tools
returned those values remains open.
[Example source](https://github.com/Psionic-labs/Agent-Causality/blob/main/examples/customer_approval.py)

For a second example, run `python -m examples.payment_approval --db .causality/payment-example.db`.
It records a USD 2,500 payment approved above a USD 1,000 limit.
Both approval examples accept `--db PATH`.
[Payment example source](https://github.com/Psionic-labs/Agent-Causality/blob/main/examples/payment_approval.py)

## Use the CLI

Set global options before the subcommand. The CLI chooses a JSON fixture
with `--fixture PATH`, then SQLite with `--db PATH`, then PostgreSQL with
`DATABASE_URL`. With none of these set, it uses `.causality/events.db`.
Run `causality --help` or `causality COMMAND --help` for argument help.

From the source checkout, use the same customer fixture to try every
subcommand without a database or model key.

| Task | Command |
| --- | --- |
| List the agents in the JSON fixture | `uv run causality --fixture fixture/fixture.json agents` |
| Find the recorded ancestors of a failure | `uv run causality --fixture fixture/fixture.json slice A4` |
| Inspect the merge decision and its input evidence | `uv run causality --fixture fixture/fixture.json why A3` |
| Rebuild agent B's state at logical sequence 4 | `uv run causality --fixture fixture/fixture.json reconstruct B 4` |
| Trace a field through the recorded transformations | `uv run causality --fixture fixture/fixture.json provenance A3.output.approve` |
| Substitute a value into a decision input | `uv run causality --fixture fixture/fixture.json replay dec_customer_approval_A3 customer_status=ineligible` |
| Compute per-input attribution and pair interaction | `uv run causality --fixture fixture/fixture.json interaction dec_customer_approval_A3 --samples 5` |
| Reduce the slice using a failure predicate and replay budget | `uv run causality --fixture fixture/fixture.json minimize A4 --budget 200` |
| Print the offline evidence summary | `uv run causality --fixture fixture/fixture.json explain A4 --no-llm` |
| Print the evidence JSON followed by the offline summary | `uv run causality --fixture fixture/fixture.json explain A4 --raw-evidence --no-llm` |

The fixture replay changes the outcome from `failure` to `success`.
The recorded inputs have an interaction score of `1.0` under this fixture's
evaluator and baselines. `minimize` returns `B3, C3, A3, A4`.
`agents` is available for the fixture backend.
[CLI reference](https://github.com/Psionic-labs/Agent-Causality/blob/main/docs/reference.md)

To analyze the SQLite run from the approval example, replace
`FAILURE_EVENT_ID` with the ID printed by the example. Import the module so
the new CLI process can register the evaluator. You can repeat
`--load-module` for multiple modules.

```bash
causality --load-module examples.customer_approval --db .causality/example.db explain FAILURE_EVENT_ID --no-llm
```

To minimize a SQLite decision's slice, open the database in the Explorer,
select the merge decision, and copy its event ID. Pass that ID to
`minimize`. The offline explanation above starts from the terminal event.

```bash
causality --load-module examples.customer_approval --db .causality/example.db minimize DECISION_EVENT_ID
```

Use the decision event ID for `replay` and `interaction` on a database.
The bundled fixture also accepts its decision contract ID.
Register a side-effect-free evaluator. Replay calls it with recorded inputs
and your substitutions. The engine rejects contracts marked as side-effecting.
Exact interaction enumeration supports up to four ports.
Bootstrap sign proportions describe the sampled results. A structural slice
shows recorded dependencies. Use replay with a registered evaluator to
measure the effect of a tested input substitution.

## Tour the Explorer

After installing the Python package, start the Visual DAG Explorer.

```bash
causality-explorer
```

Open <http://127.0.0.1:8766>. The bundled trace shows a failing test, an edit,
and a passing retry. To inspect the SQLite run with two branches, stop the
demo server and start the Explorer with the database from the approval
example. Use `--port` to start a second server and `--host` to set its bind
address. The default bind address is `127.0.0.1`.

```bash
causality-explorer --db .causality/example.db
```

The header shows the dataset, event count, and edge count. The Explorer
reads a snapshot when it starts. Restart it to load events written after
startup. Use a desktop window for the graph.

![The Explorer shows a dependency graph and event inspector for a reconstruction of the Replit incident](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/media/explorer-night-desk.gif)

### Switch views and inspect events

| Feature | How to use it |
| --- | --- |
| Night desk and Daylight | Switch the color theme in the header. The browser remembers your choice. |
| Graph | Select **Graph** to follow recorded dependencies. Scroll to zoom, drag to pan, and click **Reset view** to fit the graph. Click a node to select it. |
| Timeline | Select **Timeline** to see events in order. Click a clip, drag the ruler, click the minimap, or press Left and Right while the timeline has focus. Graph and Timeline share the selected event. |
| Filters | Pick a session or **All sessions**. Switch to **Key events** to hide context and model events. Use **All events** or toggle one event-type chip to adjust the view. The counter shows what is visible. |
| Edges | Follow solid arrows for recorded parent links. Hover over a dashed arrow to see how many events the filter hides along that path. |
| Event inspector | Select an event to see its type, sequence, time, and recorded command or result. Copy its event ID, follow a declared parent or observed child, or expand **Raw event**. |
| Why did it fail? | Read the failure summary and select a step in the displayed path. Open **Full technical explanation** for the offline evidence. For a trace without a matching failure selector, the Explorer shows a target based on position. |

<details>
<summary>View screenshots of the Explorer controls</summary>

**Color theme**

![Night desk and Daylight controls](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/theme.png)

**Graph and Timeline**

![Graph, Timeline, and Reset view controls](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/views.png)

![Daylight Timeline with event clips and a sequence ruler](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/timeline.png)

**Session and event filters**

![Session selector, presentation filter, event-type chips, and visible event count](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/filters.png)

**Recorded edges and filter gaps**

![Graph with solid parent links and dashed paths through hidden events](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/arrows.png)

![Tooltip showing how many events a filter hides along a path](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/gaps.png)

**Event inspector and failure summary**

![Selected tool result in the inspector](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/inspector.png)

![Why did it fail, with the technical explanation and AI analysis controls](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/why.png)

</details>

### Open each analysis tab

| Tab | What to try |
| --- | --- |
| Causal chain | Start with the bundled trace. Click a row in the failure's ordered dependency slice to open its event. The chain shows up to 80 events. |
| Provenance | Open the Replit example and follow the recorded file paths and resource chains. Click a chain event to inspect it. Provenance grades and expected edges appear when the capture or benchmark supplies them. |
| Interaction | Open the approval database and select the decision where the two tool branches converge. Open **Benchmark scoring** when evaluating a trace with ground truth. The Explorer shows branch ancestry from the graph. The CLI measures decision interaction through replay. |
| Evidence | Inspect the ordered tool calls and results in the failure slice. Click a row to open its event, or expand **Backend evidence summary**. |
| Metrics | Compare dataset events, slice events, and counts by event type. Open **Benchmark scoring** to inspect the available diagnosis dimensions for a trace with ground truth. |

<details>
<summary>View all five analysis tabs</summary>

**Causal chain**

![The bundled retry trace's two recorded events in the Causal chain tab](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/causal-chain.png)

**Provenance**

![Resource chain with recorded reads and writes in the Replit reconstruction](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/provenance.png)

**Interaction**

![Approval decision with two recorded parents in the Interaction tab](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/interaction.png)

**Evidence**

![Tool calls and results in the Evidence tab](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/evidence.png)

**Metrics**

![Dataset, slice, and event-type counts in the Metrics tab](https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/docs/screenshots/features/metrics.png)

</details>

Select **Generate AI analysis** to request a model interpretation of the
evidence. See [Generate an OpenRouter explanation](#generate-an-openrouter-explanation)
for installation and credentials. A live capture can have structural
evidence while benchmark-only results are unavailable.
[Explorer terminology](https://github.com/Psionic-labs/Agent-Causality/blob/main/docs/explorer.md)

### Read the Explorer HTTP API

The API serves the same startup snapshot as the read-only Explorer.
Run `curl http://127.0.0.1:8766/api/overview` to get the graph and event IDs.

| GET route | Response |
| --- | --- |
| `/api/overview` | Dataset, nodes, edges, and selected failure target |
| `/api/failure` | Failure target and how the Explorer resolved it |
| `/api/event?id=EVENT_ID` | Event record, parents, and children |
| `/api/diagnosis` | Available diagnosis scores and capability limits |
| `/api/evidence` | Evidence package and offline summary |
| `/api/ai-diagnosis` | On-demand model interpretation when OpenRouter is configured |

## Capture an OpenCode session

This is the recommended way to test Agent-Causality on a real coding-agent
session today. The walkthrough exercises live event capture, SQLite
persistence, and inspection in the Explorer. The committed benchmark
records five real sessions using this capture path.
[OpenCode benchmark results](https://github.com/Psionic-labs/Agent-Causality/blob/main/benchmark/results/opencode/opencode.md)

Use OpenCode 1.19.0, the version used for the live benchmark. The capture
plugin uses the OpenCode V1 API. Connect a model provider in OpenCode with
`/connect` and select a model with `/models`, or pass
`--model PROVIDER/MODEL` to `opencode run`.
[OpenCode V1 provider setup](https://opencode.ai/v1/docs/providers/)

```bash
pip install agent-causality
```

Add the npm package to the `plugin` array in your project's `opencode.json`.
Keep any existing entries. OpenCode installs the npm package on startup.
[OpenCode V1 plugin configuration](https://opencode.ai/v1/docs/plugins/#from-npm)

```json
{
  "plugin": ["@psionic-labs/opencode-agent-causality"]
}
```

Start the receiver in one terminal. In another terminal, run OpenCode from
the project you want to capture. Then open the same database in the Explorer.

```bash
# Terminal 1
causality-opencode-ingest --db .causality/opencode.db

# Terminal 2, from the project you want to capture
opencode run "Run git status --short and summarize the result. Do not edit any files."

# Terminal 3, from the same directory as terminal 1
causality-explorer --db .causality/opencode.db
```

The receiver listens on `127.0.0.1:8765` by default. Open the Explorer at
<http://127.0.0.1:8766>. Reusing the database appends runs. Choose a fresh path
when you want one run per file. When developing the local plugin from source,
run `uv run python scripts/sync-opencode-plugin.py` from the checkout and
start OpenCode there. Use one plugin installation per project.

The plugin forwards the event stream and explicit tool, permission, command,
and chat hooks. The receiver links tool calls to results by call ID, keeps
declared parents, and tracks recognized file reads after writes.
Unlinked events can still appear in the timeline.
[OpenCode integration guide](https://github.com/Psionic-labs/Agent-Causality/blob/main/docs/opencode.md)

### Configure and troubleshoot OpenCode capture

Use `--db`, `--host`, and `--port` on `causality-opencode-ingest` to configure
the receiver. If you change its address, set the full URL in the terminal
where you launch OpenCode.

| Plugin environment variable | Default | Behavior |
| --- | --- | --- |
| `CAUSALITY_OPENCODE_INGEST_URL` | `http://127.0.0.1:8765/v1/opencode/events` | Where the plugin posts events |
| `CAUSALITY_OPENCODE_INGEST_TIMEOUT_MS` | `5000` | Timeout per request in milliseconds |
| `CAUSALITY_OPENCODE_BATCH_MAX` | `25` | Maximum envelopes per POST |
| `CAUSALITY_OPENCODE_LOG_TELEMETRY_FAILURES` | Unset | Set to `1` or `true` to see delivery warnings |
| `CAUSALITY_OPENCODE_INGEST_TOKEN` | Unset | Sends a Bearer header to a receiver or proxy that uses it. The bundled receiver is a local, unauthenticated service. |

If a run is missing, check the ingest URL, confirm you opened the same SQLite
file, and enable delivery warnings. The plugin retries a batch up to three
attempts and buffers up to 256 events. Capture may drop events while OpenCode
continues its work. The receiver redacts recognized secrets before storage.

`POST /v1/opencode/events` accepts one telemetry envelope or an array. A
`202` response reports `received`, `normalized`, `persisted`, `rejected`,
and `unpersisted`. `accepted` is an alias for `persisted`. Check these counts
to confirm that data reached SQLite. Invalid JSON returns `400`.

## Capture a LangGraph run

In an existing LangGraph app, install `agent-causality[langgraph]`. Add the
callback handler to the invocation of your compiled graph.

```python
from adapters.langgraph import CausalityCallbackHandler
from storage.sqlite import SQLiteEventStore

store = SQLiteEventStore(".causality/langgraph.db")
handler = CausalityCallbackHandler(store)
try:
    result = app.invoke(inputs, config=handler.config())
finally:
    store.close()
```

Open the capture with `causality-explorer --db .causality/langgraph.db`.
The handler captures chain and node starts and finishes, tool calls and
results, model and retriever callbacks, and errors. It links observed
callbacks and recognized file reads after writes. Capture is best effort
and redacts recognized secrets. Check `handler.errors` for capture errors
and `handler.resources()` for tracked resource versions.

Set `run_id` or `agent_prefix` when creating the handler to label your capture.
Pass a `ResourceRegistry` or `PayloadRedactor` to customize resource tracking
or redaction. Use `handler.reset()` to clear in-memory run bookkeeping.
[LangGraph integration guide](https://github.com/Psionic-labs/Agent-Causality/blob/main/docs/langgraph.md)

To try LangGraph capture without your own app, run the local reconstruction
of the Replit incident. It uses scripted tools. The example reported
22 events and zero graph validation violations on a fresh database.
The `--append` flag preserves any existing demo captures.

```bash
python -m pip install "agent-causality[langgraph]" langgraph
python -m examples.replit_incident --append
causality-explorer --db .causality/replit-incident.db
```

In the Explorer, open **Provenance** and follow the file writes and subsequent
verification reads in the reconstruction.
[Replit case study](https://github.com/Psionic-labs/Agent-Causality/blob/main/docs/case-study-replit.md)

## Instrument your own Python agents

Save this example as `approval_flow.py`. Run `python approval_flow.py`.
The decorators capture both tools, register a decision evaluator, and
persist the decision's inputs and baselines. The terminal event marks the
unexpected approval and declares the decision as its parent.

```python
import causality
from sdk.events import record_event

runtime = causality.init(".causality/custom-approval.db")


@runtime.agent(role="eligibility")
def check_eligibility():
    return "eligible"


@runtime.agent(role="risk")
def check_risk():
    return 0.2


@runtime.merge_decision(
    ports=["status", "risk"],
    baselines={"status": "ineligible", "risk": 0.8},
    decision_type="approval_flow.approve",
)
def approve(status, risk):
    return "approved" if status == "eligible" and risk < 0.5 else "rejected"


if __name__ == "__main__":
    try:
        outcome = approve(check_eligibility(), check_risk())
        decision = runtime.log.events()[-1]
        failure, _ = record_event(
            agent_id=runtime.agent_id,
            clock=runtime.clock,
            log=runtime.log,
            run_id=runtime.run_id,
            event_type="agent_finish",
            payload={"status": "failure", "final_answer": outcome},
            causal_parent_ids=[decision.id],
            causal_parent_seqs=[decision.logical_seq],
        )
        print("Decision event:", decision.id)
        print("Failure event:", failure.id)
    finally:
        runtime.log.close()
```

In the same directory, replace `DECISION_EVENT_ID` and `FAILURE_EVENT_ID`
with the IDs the script printed. Keep the current directory on Python's
import path by starting the CLI as a module.

```bash
python -m cli.main --db .causality/custom-approval.db --load-module approval_flow replay DECISION_EVENT_ID status=ineligible
python -m cli.main --db .causality/custom-approval.db --load-module approval_flow explain FAILURE_EVENT_ID --no-llm
causality-explorer --db .causality/custom-approval.db
```

Use `causality.init()` for the default SQLite path `.causality/events.db`,
or set `CAUSALITY_DB_PATH` before initialization. The module-level
`@causality.agent` and `@causality.merge_decision` use the active runtime.
The decorators associate merge inputs with recent tool results of the same
value in the same run. Use explicit sources when equal values can come
from different tools.

### Record explicit dependencies, state, and provenance

Use the lower-level Python API when your application owns the run graph or
needs a field-level source chain.

| Feature | Python entry point and usage |
| --- | --- |
| Event capture and logical order | Use `sdk.events.AgentClock` and `sdk.events.record_event` with parent IDs and their logical sequences, as in the example above. Pass a stable `idempotency_key` for retries. Use `InMemoryEventLog` for local tests or `SQLiteEventStore` to reopen a log. [Event API](https://github.com/Psionic-labs/Agent-Causality/blob/main/sdk/events.py) |
| Agent lifecycle | Call `sdk.lifecycle.spawn_agent` with a child ID or stable idempotency key. Use the returned child clock for its events and the recorded spawn event as a parent where it applies. [Lifecycle API](https://github.com/Psionic-labs/Agent-Causality/blob/main/sdk/lifecycle.py) |
| Tool capture | Wrap a function with `sdk.tools.capture_tool`. Provide the agent ID, clock, and event log. Supply an invocation ID for retries and `field_sources` with a provenance recorder to link fields. [Tool capture API](https://github.com/Psionic-labs/Agent-Causality/blob/main/sdk/tools.py) |
| Model capture | Wrap an Anthropic-style client with `sdk.client.CapturedClient` and call `client.messages.create(...)`. Pass `stream=True` and iterate the returned stream to capture streamed responses. Supply an existing client or install `anthropic` and pass an API key. [Model capture API](https://github.com/Psionic-labs/Agent-Causality/blob/main/sdk/client.py) |
| Shared memory and resource versions | Share a `sdk.memory.ResourceRegistry` and backing dictionary between `CapturedMemory` instances. Give `set`, `get`, and `delete` a stable resource URI, such as `mem://shared/status`, to record read-after-write dependencies. [Memory API](https://github.com/Psionic-labs/Agent-Causality/blob/main/sdk/memory.py) |
| Field provenance | For tool, model, or memory outputs, use the corresponding `core.provenance.record_*_provenance` helper to record known source fields. Query the resulting chain with `causality provenance`. [Provenance API](https://github.com/Psionic-labs/Agent-Causality/blob/main/core/provenance.py) |
| Explicit decision contracts | Create `core.decision.DecisionPort` objects with source event IDs, field paths, recorded values, and baselines. Register the evaluator with `register_decision_evaluator` and store the contract in the decision event. [Decision API](https://github.com/Psionic-labs/Agent-Causality/blob/main/core/decision.py) |
| Graph validation and state snapshots | Call `core.validator.GraphValidator(log).validate_run(run_id)` to check the run. Use `core.snapshots.SnapshotManager` and `core.reducer.reconstruct` for checkpointed state reconstruction. [Snapshot API](https://github.com/Psionic-labs/Agent-Causality/blob/main/core/snapshots.py) |
| Capture privacy and failure handling | Pass `sdk.privacy.PayloadRedactor(extra_keys={...})` to `record_event` for top-level payload redaction. Wrap the log with `make_fail_open_append` if your application should continue after a storage failure. Check the returned storage status. [Privacy API](https://github.com/Psionic-labs/Agent-Causality/blob/main/sdk/privacy.py) |

## Generate an OpenRouter explanation

Install the explanation extra. Set `OPENROUTER_API_KEY` in the process
environment or in a local `.env` file. The CLI and Explorer read `.env`
at startup. Values already set in the environment take precedence.

```bash
python -m pip install "agent-causality[explain]"
```

```dotenv
OPENROUTER_API_KEY=your-key
OPENROUTER_MODEL=your-provider/your-model
```

`OPENROUTER_MODEL` is optional. Use `explain --model MODEL` for a one-off
override, or `explain --api-key KEY` to supply the key explicitly.
Keep `.env` outside version control.

```bash
causality --db .causality/example.db --load-module examples.customer_approval explain FAILURE_EVENT_ID
```

For the browser, restart the Explorer with the key set and select
**Generate AI analysis**. This sends the evidence package to OpenRouter.
The UI labels the result as model interpretation. The offline evidence is
available through **Full technical explanation** or `explain --no-llm`.
The CLI falls back to the offline summary if the model call fails or the
answer fails the explanation format check.

## Use PostgreSQL

Use the PostgreSQL extra to store event graphs from the lower-level SDK
or query an existing PostgreSQL capture with the CLI.

```bash
python -m pip install "agent-causality[postgres]"
```

Set `DATABASE_URL` in the shell that will run your application and the CLI.
For CLI use, you can also set it in a local `.env` file.

```dotenv
DATABASE_URL=postgresql://user:password@host/database?sslmode=require
```

Run this script against a new database you control. It initializes the schema,
registers a run and root agent, and records one event. Use a role with
permission to create the schema and enable `pgcrypto`.

```python
import os
from uuid import uuid4

from sdk.events import AgentClock, record_event
from sdk.lifecycle import AgentRecord
from storage._psycopg import load_psycopg
from storage.postgres import PostgresEventStore

dsn = os.environ["DATABASE_URL"]
run_id = str(uuid4())
agent_id = str(uuid4())

with load_psycopg().connect(dsn) as connection:
    store = PostgresEventStore(connection, lock_dsn=dsn)
    store.create_schema()
    with connection.cursor() as cursor:
        cursor.execute(
            "INSERT INTO runs (id, name) VALUES (%s, %s)",
            (run_id, "readme-demo"),
        )
    connection.commit()
    store.create_agent(AgentRecord(id=agent_id, run_id=run_id, role="planner"))
    event, _ = record_event(
        agent_id=agent_id,
        clock=AgentClock(),
        log=store,
        run_id=run_id,
        event_type="run_start",
        payload={"name": "readme-demo"},
    )
    print(event.id)
```

Run `causality slice EVENT_ID` with the printed ID and leave the backend
selectors unset to read from PostgreSQL. Use the same CLI commands for
reconstruction and provenance. `causality.init`, the Explorer, and the
OpenCode receiver use SQLite. To verify PostgreSQL from source, set
`DATABASE_URL` to a dedicated test database. The integration tests create
schema objects and test rows.
[PostgreSQL integration examples](https://github.com/Psionic-labs/Agent-Causality/blob/main/tests/test_postgres_integration.py)

```bash
uv sync --extra postgres
uv run --env-file .env pytest tests/test_postgres_integration.py tests/test_phase2.py -m integration -q
```

## Run the benchmarks

| Evaluation | Result |
| --- | --- |
| Five deterministic scenarios with known dependencies and decision inputs | 5 of 5 passed. All matched the expected structural slice, replay-reduced slice, provenance, and interaction. [Scenario results](https://github.com/Psionic-labs/Agent-Causality/blob/main/benchmark/results/scenarios.md) |
| Five coding sessions on OpenCode 1.19.0, one per task | All five met the benchmark's minimum event counts for the scored classes. Mean cause recall in the recorded dependency slice was 0.30 across five runs. Joint ancestry scored 0.00 across the two applicable runs. [OpenCode results](https://github.com/Psionic-labs/Agent-Causality/blob/main/benchmark/results/opencode/opencode.md) |

The OpenCode capture score counts events against per-class thresholds. Cause
recall measures how many annotated causes appear in the recorded dependency
slice. Joint ancestry tests whether both annotated branches appear upstream
of the failure. The live benchmark measures recorded ancestry. It leaves
counterfactual interaction unscored.
[Benchmark methodology and other results](https://github.com/Psionic-labs/Agent-Causality/blob/main/docs/benchmarks.md)

Run these from the source checkout. The local output folder keeps reruns
separate from the committed JSON and Markdown reports.

```bash
uv run causality-benchmark scenarios --results-dir .causality/readme-benchmark
uv run causality-benchmark failure-injection --results-dir .causality/readme-benchmark
uv run causality-benchmark experiment1 --repetitions 3 --results-dir .causality/readme-benchmark
uv run causality-benchmark experiment2 --dependencies 100 --results-dir .causality/readme-benchmark
uv run causality-benchmark experiment3 --results-dir .causality/readme-benchmark
uv run causality-benchmark baseline --results-dir .causality/readme-benchmark
```

| Mode | What it evaluates |
| --- | --- |
| `scenarios` or `offline` | Five deterministic graphs with known dependencies and decision behavior. |
| `failure-injection` | Three traces with injected errors and known ground truth. |
| `experiment1` | Two-input replay against four direct input combinations. The deterministic committed run reports 12 true positives and 12 true negatives. |
| `experiment2` | Recovery of shared-state dependencies. The committed run recovered 100 out of 100. |
| `experiment3` | Semantic input substitution and raw deletion across 20 parser, schema, and decision cases. The committed report records 20 successful semantic substitutions and 70% failure under raw deletion. |
| `baseline` | Comparison status and capability coverage for the external baseline. |
| `all` | All offline suites with the default provider. |
| `opencode` | Live coding-agent sessions scored against known task expectations. |

For a live benchmark, use OpenCode V1 and an available provider model.
Export provider credentials in the launching shell or configure the
provider in OpenCode. Replace `PROVIDER/MODEL` with your model ID.

```bash
uv run causality-benchmark opencode --task failed_test_retry --model PROVIDER/MODEL --timeout 300 --output-dir .causality/readme-opencode
```

Omit `--task` to run all five tasks or repeat it to select several.
Use `--runs` for repetitions, `--opencode-bin` for a specific binary, or
`--ingest-url` for an existing receiver. Open a resulting
`runs/RUN_ID/trace.db` in the Explorer. `opencode.json` records its path
and the run metadata.

Experiment 1 also accepts `--provider fastino`. Set `FASTINO_API_KEY`
and `FASTINO_MODEL` in your shell for a model with structured output.
The external run in the committed report is provider-blocked. Use
`--dry-run` to inspect the request plan before making provider calls.

```bash
uv run causality-benchmark experiment1 --provider fastino --dry-run --repetitions 1 --max-requests 8 --results-dir .causality/readme-fastino --cache .causality/readme-fastino/model-cache.jsonl
```

[Benchmark commands and methodology](https://github.com/Psionic-labs/Agent-Causality/blob/main/benchmark/README.md)

## Develop and verify the checkout

For development, use Node.js 20 or later and install the Python and
Node dependencies from the repository root. Install Chromium for Explorer
browser tests.

```bash
uv sync
npm ci --prefix frontend
npm ci --prefix packages/opencode-agent-causality
npx --prefix frontend playwright install chromium
uv run pre-commit install
```

Run the quick verifier during development and the full verifier before
submitting a change. The full run builds the frontend and checks the
Explorer through its API and Playwright. Logs are in
`tools/verify/artifacts/`.

```bash
uv run python tools/verify/verify.py --quick
uv run python tools/verify/verify.py
```

After changing the Explorer frontend, rebuild and sync its packaged files.
After changing the OpenCode plugin source, regenerate the local plugin copy.

```bash
npm run build --prefix frontend
uv run python scripts/sync-explorer-static.py
uv run python scripts/sync-opencode-plugin.py
```

Use `npm run dev --prefix frontend` for the frontend development server.
For full API-backed testing, start `causality-explorer` and use the bundled
frontend at port 8766. [Contributing guide](https://github.com/Psionic-labs/Agent-Causality/blob/main/CONTRIBUTING.md)

## Further reading

- [Research paper](https://github.com/Psionic-labs/Agent-Causality/blob/main/research_paper/agentic_causality_paper.pdf) by Vasant Kumar Mogia. It describes declared dependencies, field provenance, and counterfactual replay.
- [Replit incident case study](https://github.com/Psionic-labs/Agent-Causality/blob/main/docs/case-study-replit.md). The example reconstructs the reported incident as a local LangGraph run.
- [Contributing](https://github.com/Psionic-labs/Agent-Causality/blob/main/CONTRIBUTING.md), [verification](https://github.com/Psionic-labs/Agent-Causality/blob/main/TEST.md), and [release notes](https://github.com/Psionic-labs/Agent-Causality/blob/main/CHANGELOG.md).
- [AGPL-3.0-only and commercial licensing](https://github.com/Psionic-labs/Agent-Causality/blob/main/LICENSING.md).

<p align="center">
  <img src="https://raw.githubusercontent.com/Psionic-labs/Agent-Causality/main/mascot.png" alt="A detective robot examining a causal graph" width="180" />
</p>
