Metadata-Version: 2.5
Name: actiongraph-ai
Version: 0.1.0
Summary: The open decision record for AI agents: playbook, evidence, rules, earned autonomy, approvals, outcomes, flows and MCP.
Project-URL: Homepage, https://github.com/actiongraphai/actiongraph
Project-URL: Source, https://github.com/actiongraphai/actiongraph
Project-URL: Issues, https://github.com/actiongraphai/actiongraph/issues
Project-URL: Changelog, https://github.com/actiongraphai/actiongraph/blob/main/CHANGELOG.md
Author: ActionGraph contributors
License: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: agentops,ai-agents,approvals,audit,decision-record,governance,human-in-the-loop,mcp
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.11
Requires-Dist: fastapi>=0.110
Requires-Dist: numpy>=1.26
Requires-Dist: pydantic>=2.5
Requires-Dist: pyyaml>=6.0
Requires-Dist: sqlalchemy>=2.0
Requires-Dist: uvicorn>=0.27
Provides-Extra: llm
Requires-Dist: anthropic>=1.0; extra == 'llm'
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
Provides-Extra: test
Requires-Dist: httpx>=0.27; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

<p align="center">
  <img src="docs/banner.svg" width="800" alt="ActionGraph: the authority layer for AI agents. Ask, record why, a person approves, outcome, earned autonomy.">
</p>

# ActionGraph

[![ci](https://github.com/actiongraphai/actiongraph/actions/workflows/ci.yml/badge.svg)](https://github.com/actiongraphai/actiongraph/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/actiongraph-ai)](https://pypi.org/project/actiongraph-ai/)
![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12-blue)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)

**The open-source authority layer for enterprise autonomy.**

AI agents can already decide. Before an enterprise lets them *act*, it needs authority: which actions an agent may
take alone, which need a person, and a record of how each call was made and whether it worked. ActionGraph is
that layer.

Before an agent acts, it asks ActionGraph. It gets back the options your playbook allows, ranked by what worked on
similar cases, the rule checks, and whether a person has to approve. The agent records what it chose and why. When
the result is known, ActionGraph grades it, and each agent earns autonomy from its own track record.

```
agent ── ask ──▶ ActionGraph ── options · rules · evidence · who decides ──▶ record ──▶ approve? ──▶ outcome ──▶ earned autonomy
```

It works with any agent (Claude, GPT, Grok, LangGraph, CrewAI or your own code) in-process in Python, over HTTP or
over MCP.

It isn't tied to one kind of work. The same loop governs a refund, a deploy rollback, a production-access request or
a delayed shipment: ready-made packs for support, software, security and freight ship with it, and the setup wizard
starts from templates for other domains.

> **Beta (0.1), a research prototype.** Use it today with a person approving, and as the record of what your agents
> decided. Before you let an agent act alone on anything costly or irreversible, read
> [What it protects, and what it doesn't](#what-it-protects-and-what-it-doesnt). It is provided as is, without
> warranty of any kind ([Apache-2.0](LICENSE)); you remain responsible for what your agents do and for your own
> controls and oversight.


## Quickstart

```python
# Step 1 — Install ActionGraph. Run this in your terminal (not in Python):
#
#     pip install actiongraph-ai
#
# Step 2 — Save this file as actiongraph_quickstart.py and run: python actiongraph_quickstart.py
from actiongraph import ActionGraph, ApprovalRequired

DB = "sqlite:///actiongraph_quickstart.db"          # local file; no server, no API key
agent = ActionGraph(DB, agent="support_bot")         # the agent: it can ask, never approve
person = ActionGraph(DB)                             # a person: approves, and their name goes on the record


# Guard a risky action: a person approves each call until the agent has earned it
@agent.guard(subject="Order:{order_id}", autonomy_after=3)
def issue_refund(order_id: str, amount: float):
    print(f"  refunded ${amount} on {order_id}")


for order_id in ["A-1001", "A-1002", "A-1003", "A-1004"]:
    try:
        issue_refund(order_id, 40.0)
        print(f"{order_id}: ran on its own — the agent earned it")
    except ApprovalRequired as e:
        print(f"{order_id}: waiting for a person ({e.decision_id})")
        person.approve(e.decision_id, by="dana")
        issue_refund(order_id, 40.0)                  # the same call now runs what was approved

# Every call is on the record: who asked, who approved, whether it worked
for d in reversed(person.decisions(limit=4)):
    trail = [e["kind"] + " by " + e["actor"].split(":")[-1] for e in person.decision(d["decision_id"])["timeline"]]
    print(d["subject"], "→", ", ".join(trail))
```

```text
A-1001: waiting for a person (dec_748a1f4a41b94df2)
  refunded $40.0 on A-1001
A-1002: waiting for a person (dec_02f395eac7c444fe)
  refunded $40.0 on A-1002
A-1003: waiting for a person (dec_8f04b26ead584e1d)
  refunded $40.0 on A-1003
  refunded $40.0 on A-1004
A-1004: ran on its own — the agent earned it
Order:A-1001 → approval_requested by support_bot, approved by dana, executed by support_bot, outcome by support_bot
Order:A-1002 → approval_requested by support_bot, approved by dana, executed by support_bot, outcome by support_bot
Order:A-1003 → approval_requested by support_bot, approved by dana, executed by support_bot, outcome by support_bot
Order:A-1004 → decided by support_bot, executed by support_bot, outcome by support_bot
```

Three approved runs that worked, and the fourth runs on its own. One failure or rejection and it asks again. The same
file is [examples/quickstart.py](examples/quickstart.py).

## Explore in five examples

Five short scripts in [examples/get_started](examples/get_started), each runnable on its own with nothing but
`pip install actiongraph-ai`, walk through what ActionGraph does:

| Example | Shows |
|---|---|
| [1. Your first approval](examples/get_started/01_first_approval.py) | A guard, approve and reject, the record |
| [2. A playbook: rules and evidence](examples/get_started/02_playbook_rules_evidence.py) | Options ranked by what worked, a rule that blocks, a rule that routes to a person |
| [3. Earning autonomy, and losing it](examples/get_started/03_earn_and_lose_autonomy.py) | recommend → approve → auto, and auto taken back when results turn |
| [4. Who grades the agent?](examples/get_started/04_who_grades_the_agent.py) | Its own word earns nothing; hidden random audits; the honesty test |
| [5. Safety rails](examples/get_started/05_safety_rails.py) | No self-approval, approvals bound to the request, outcomes only a person can change, one approval, one run |

Each is explained, with its real output, in the docs under *Explore in five examples*.

## Start here

| You have | Start with | |
|---|---|---|
| A Python function with a risky side effect | `@ag.guard`, two lines | [Guard one action](#guard-one-action) |
| An MCP server your agent already uses | `actiongraph mcp-gate`, one line | [Gate any MCP server](#gate-any-mcp-server) |
| Several agents making the same kinds of decisions | a playbook, evidence and flows | [Playbooks and evidence](#playbooks-and-evidence) |

```bash
pip install actiongraph-ai
```

### Guard one action

```python
from actiongraph import ActionGraph, ApprovalRequired

ag = ActionGraph(agent="support_bot")

@ag.guard(subject="Order:{order_id}", autonomy_after=5)
def issue_refund(order_id: str, amount: float):
    ...  # the real side effect

try:
    issue_refund("A-1001", 250.0)
except ApprovalRequired as e:
    print(e)          # Waiting for a person to approve issue_refund (dec_…). Call it again once it's approved.
```

Approve it on the dashboard (`actiongraph init`, then `actiongraph serve`, and open http://localhost:8080) or in code
with `ActionGraph().approve("dec_…", by="dana")`. Calling `issue_refund("A-1001", 250.0)` again then runs it, and
ActionGraph records whether it worked.

- **The same call is the same request.** Retrying never opens a second one, and one approval runs the call once.
- **A rejection is reported once,** as `ActionRejected` with the reason.
- **`autonomy_after=5`** means that after 5 approved runs in a row that worked, it stops asking. One failure or
  rejection and it asks again.
- **`approve=lambda a: a["amount"] > 100`** asks a person only for large refunds and just records the rest.
- **`wait=60`** holds the call until someone decides.
- **Async functions work too.**

No playbook is needed. When the same kinds of decisions keep coming up, grow them into playbook decision types with
evidence and rules ([below](#playbooks-and-evidence)).

### Get a tap on your phone

Point ActionGraph at Slack, a phone push or any webhook, and people hear about each request the moment an agent makes
it:

```bash
export ACTIONGRAPH_NOTIFY="ntfy=https://ntfy.sh/your-private-topic slack=https://hooks.slack.com/services/…"
export ACTIONGRAPH_PUBLIC_URL=http://localhost:8080        # where actiongraph serve runs; turns on one-tap links
```

- **On your phone:** install the free [ntfy](https://ntfy.sh) app and subscribe to your topic. Each request arrives
  as a push with **Approve** and **Reject**.
- **In Slack:** a message with the same buttons.
- **Webhook:** gets JSON with `approve_url` and `reject_url`.

A tap opens a short confirm page showing what the agent wants. Opening the link never approves anything, so apps
that preview links in chat can't approve by accident; the confirm page's button decides. Links are signed, expire
after 24 hours and stop working once the decision is made. Anyone holding a link can approve with it, so send
notifications to private channels. With `ACTIONGRAPH_NOTIFY_LINKS=0`, notifications point people to the dashboard
instead.

### Gate any MCP server

`actiongraph mcp-gate` sits between your MCP client and any MCP server. Tools the server marks read-only run at once.
Anything else waits for a person. Everything is recorded.

```bash
# Claude Code
claude mcp add github -- actiongraph mcp-gate -- npx -y @modelcontextprotocol/server-github
```

```json
{
  "mcpServers": {
    "github": {
      "command": "actiongraph",
      "args": ["mcp-gate", "--approve", "*merge*", "--", "npx", "-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "…" }
    }
  }
}
```

Remote MCP servers work the same way: give the gate the server's URL instead of a command. Pass any token through
an environment variable, so it never sits in your client's config:

```bash
claude mcp add github -- actiongraph mcp-gate \
  --upstream-url https://api.githubcopilot.com/mcp/ --header "Authorization: Bearer ${GITHUB_TOKEN}"
```

When the agent calls a risky tool, it's told the call needs approval and where to approve it. After a person
approves on the dashboard, the agent's retry goes through.


| Option | What it does |
|---|---|
| `--approve PATTERN` | These tools always need a person |
| `--allow PATTERN` | These tools never do |
| `--autonomy-after N` | Stop asking for a tool after N approved runs that worked |
| `--wait SECONDS` | Hold the call while someone decides |
| `--upstream-url URL` | Gate a remote MCP server (Streamable HTTP) instead of starting a command |
| `--header "Name: value"` | A header for the remote server, such as `Authorization: Bearer ${TOKEN}` (repeatable) |
| `--url`, `--key` | Record to an ActionGraph server instead of `~/.actiongraph` |

## Why ActionGraph

Agents are good at deciding and bad at being accountable. ActionGraph gives every decision:

- **A playbook.** Decision types, the options allowed, rules (block · ask a person · warn) and what "worked" means.
  It's versioned YAML, and a person activates each version.
- **Evidence.** Options are ranked by outcomes on similar past cases. When exact history is thin, the match widens,
  and ActionGraph says so.
- **A person where it matters.** A new agent asks first. Rules can always require a person. Agents can't approve
  their own decisions (on a server with separate keys: see [below](#what-it-protects-and-what-it-doesnt)). An approval
  lands only on the request the person was shown: if the agent changes its ask, the approval is refused.
- **Earned autonomy.** Each agent earns autonomy from its own outcomes (`per_agent: false` pools it across agents).
  An agent moves up only when its record shows, with 90% confidence, that it clears the bar (70% for `approve`, 90%
  for `auto`), and that holds however often it's re-checked, so a lucky streak isn't enough. It moves down as soon as
  its latest outcomes show the rate has fallen below the bar, within a few dozen decisions however long its good record
  is (`recent_outcomes`). Outcomes the agent reports about itself don't count unless the playbook says so
  (`agent_reported_outcomes: true`), and only a person can change an outcome once it's recorded. It's capped by a
  ceiling you set.
  Optionally it depends on the action: risky or named actions earn their own level from their own outcomes
  (`autonomy.by_risk`, `autonomy.by_action`), large parameters cap one decision (`limits: [{param: amount, gt: 5000,
  ceiling: approve}]`), actions marked `reversible: false` stop at `approve` unless configured, and
  `max_pending_auto: N` asks a person once N decisions made alone still wait for outcomes.
- **An audit trail.** The situation, the options, the rule checks, who decided, who approved and why, and the
  outcome, for each decision, under the playbook version it was made under.
- **Flows.** Multi-step processes built from playbook decisions, with gates, parallel specialists and swarms. In a
  swarm agents vote; agreement decides, and a split goes to a person.

## Playbooks and evidence

```python
from actiongraph import ActionGraph

people = ActionGraph()                                  # in-process; SQLite at ~/.actiongraph/actiongraph.db
people.use_pack("freight", confirmed_by="ops-lead")    # a person activates the playbook

agent = ActionGraph(agent="load_recovery")              # an agent can ask and record, never approve
d = agent.ask("Load:L-1", "load_recovery", {
    "carrier_cancelled": True, "hours_to_pickup_band": "under_4",
    "known_carrier_available": True, "equipment": "dry_van"})

for o in d["actions"]:                                 # ranked by what worked on similar loads
    print(o["rank"], o["name"], o["allowed"], o["evidence"]["rate"])

r = agent.record(d["decision_id"], d["actions"][0]["name"], reason="known carrier is free today")
print(r["status"])                                     # "needs_approval": a new agent asks first

people.approve(d["decision_id"], by="marcus")
agent.outcome(d["decision_id"], success=True)          # outcomes are how agents earn autonomy
print(people.decision(d["decision_id"])["timeline"])
```

**Want evidence on day one?** Run `actiongraph demo` first. It fills `~/.actiongraph/actiongraph.db` with the freight
example and four months of fictional history, so `ask` returns options ranked by real rates (skip `use_pack`; the
demo already activated it).

For software teams, run `actiongraph demo --pack software` instead (in a fresh `ACTIONGRAPH_HOME`). It covers
incidents, database migrations and feature rollouts. A bad deploy ranks "roll back" first, and a large locking
migration ranks "run online" first. Three requests wait on the dashboard: a region failover for the incident lead,
an irreversible migration for the DB owner, and a 100% rollout for the product owner.

Also on `ActionGraph`: `pending()`, `reject()`, `decide()` (a person makes the call), `similar()`, `capture()` for
decisions made outside a playbook, `propose_playbook()`, and flows (below). Every method returns plain dicts.

### Several agents, one case

A flow holds the action until every decision it covers is made and every person it needs has said yes. With the
`software` pack, an SRE agent and a comms agent work an incident in parallel:

```python
people = ActionGraph()
people.use_pack("software", confirmed_by="platform-lead")
sre, comms = ActionGraph(agent="sre"), ActionGraph(agent="stakeholder_brief")

run = people.start_flow("incident_remediation", "INC-5521")["run_id"]
fix = sre.ask("Incident:INC-5521", "incident_remediation", {"severity": "sev1", "cause_band": "bad_deploy",
              "recent_deploy": True, "flag_available": False, "rollback_safe": True})
sre.record(fix["decision_id"], "rollback_deploy", reason="bad deploy 12 min ago")
people.attach(run, "remediate", fix["decision_id"])
people.gate(run, "approve")["status"]           # "not_ready": the status update isn't decided yet

post = comms.ask("Incident:INC-5521", "status_update", {"severity": "sev1", "customers_affected": 1200,
                 "customers_affected_band": "many"})
comms.record(post["decision_id"], "post_public_status", reason="customers see checkout errors")
people.attach(run, "comms", post["decision_id"])
people.gate(run, "approve")["status"]           # "waiting_on_person": on call, and the comms lead for a public post

people.approve(fix["decision_id"], by="priya")
people.approve(post["decision_id"], by="dana")
people.gate(run, "approve")["status"]           # "pass": now run the rollback and post the update

sre.outcome(fix["decision_id"], success=True)   # each agent earns trust on its own record
people.flow_outcome(run, metrics={"slo_recovered_15m": True})
```

In a swarm step, each agent calls `vote()`; a majority decides, and a split waits for `people.decide(...)`.
Rejecting a proposal reopens the decision for a different choice. Write your own flows with `propose_flow()` and
`activate_flow()`; `sign_gate()` signs off a `gate: always` step, and `autonomy(flow)` shows who decides each step
today.

### Ready-made playbooks

| Pack | Decision types | Flows |
|---|---|---|
| `software` | incident remediation, status updates, release go/no-go, database migrations, feature rollouts | incident remediation, release go/no-go, schema change, feature rollout |
| `security` | access requests, vulnerability response | access request, vulnerability response |
| `saas_support` | refund requests, customer data deletion | refund request, data deletion |
| `freight` | load tender, load recovery, carrier check, detention disputes, appointments | four logistics flows |

Each pack ships the rules people expect: a locking migration can't run at peak hours, production access needs a
ticket, a known-exploited critical can't be accepted as a risk, deleting data under legal hold is blocked, and large
refunds need the support lead. It also says what "worked" means for each decision. Install one, and a person
activates it:

```python
ActionGraph().use_pack("software", confirmed_by="you")         # or POST /v1/packs/software/install
```

### Write your own playbook

A playbook is YAML: entity types and their states, actions, and decision types with options, rules and what
"worked" means. Start from [examples/freight/playbook.yaml](examples/freight/playbook.yaml) or any pack in
[examples/](examples/), and read [spec/playbook.md](spec/playbook.md). Check it before you propose it:

```bash
actiongraph validate my-playbook.yaml
```

Flows are described in [spec/flows.md](spec/flows.md), with examples in
[examples/freight/flows.yaml](examples/freight/flows.yaml).

Any agent framework can send decision events instead of calling the API (`POST /v1/events`), and
`GET /v1/events` exports the record in the same shape: see [spec/decision-events.md](spec/decision-events.md).

## Run it as a server

| | Library | Self-hosted server | Hosted |
|---|---|---|---|
| **Best for** | Trying it, one app, tests | Teams, many agents, other languages | Zero-ops production |
| **Setup** | `pip install actiongraph-ai` | `docker compose up` or `actiongraph serve` | Hosted (coming soon) |
| **Agents connect by** | Python | HTTP API · MCP | HTTP API · MCP |
| **Keys** | None (in-process) | People's key and agent key | Per-person sign-in, roles |
| **Dashboard** | — | Built in: approvals, decisions, flows, playbook | Full console: orgs, people, Slack, on-call |

The same code runs on all three: `ActionGraph()` is in-process, and `ActionGraph(url=..., api_key=...)` talks to a
server.

```bash
actiongraph init        # creates the tables and prints two keys, once
actiongraph serve       # http://localhost:8080
```

`init` prints two `export` lines. Run them. `ACTIONGRAPH_KEY` is for people (activate, approve), and
`ACTIONGRAPH_AGENT_KEY` is for agents (ask, record, vote). Agents never get the people's key; the agent key gets `403`
on approve, reject and activate whatever headers it sends. With the shared agent key an agent names itself, so the
playbook's `agents` capabilities are advisory. To make them hold, give each agent its own key
(`ACTIONGRAPH_AGENT_KEYS=load_recovery=<key>,billing=<key>`: the key names the agent) and set `agents_only: true`.

```python
agent = ActionGraph(url="http://localhost:8080", api_key=os.environ["ACTIONGRAPH_AGENT_KEY"], agent="load_recovery")
```

<details>
<summary><b>The same loop over plain HTTP</b></summary>

Install the example freight playbook and activate it. This step needs a person, so it uses the people's key:

```bash
P="Authorization: Bearer $ACTIONGRAPH_KEY"
A="Authorization: Bearer $ACTIONGRAPH_AGENT_KEY"
J='content-type: application/json'

curl -s -X POST localhost:8080/v1/packs/freight/install -H "$P" -H "$J" -d '{}'
curl -s -X POST "localhost:8080/v1/playbook/versions/1/activate?confirmed_by=ops-lead" -H "$P"
```

An agent asks. It names itself with `X-ActionGraph-Agent`:

```bash
curl -s -X POST localhost:8080/v1/recommend -H "$A" -H "$J" -H "X-ActionGraph-Agent: load_recovery" -d '{
  "entity": "Load:L-1", "decision_type": "load_recovery",
  "observations": {"carrier_cancelled": true, "hours_to_pickup_band": "under_4",
                   "known_carrier_available": true, "equipment": "dry_van"}}'
# → decision_id, the allowed options ranked by evidence, rule checks, the agent's autonomy level
```

It records its choice. A new agent's decision comes back `needs_approval`:

```bash
curl -s -X POST localhost:8080/v1/record -H "$A" -H "$J" -H "X-ActionGraph-Agent: load_recovery" \
  -d '{"decision_id": "dec_…", "action": "rebook_known_carrier", "reason": "known carrier is free today"}'
```

A person approves. The agent key gets `403` here, whatever headers it sends:

```bash
curl -s -X POST localhost:8080/v1/decisions/dec_…/approve -H "$P" -H "$J" -d '{"approved_by": "marcus"}'
```

Report the outcome when it's known. The agent's record moves toward acting alone:

```bash
curl -s -X POST localhost:8080/v1/decisions/dec_…/outcome -H "$A" -H "$J" -d '{"success": true}'
curl -s localhost:8080/v1/decisions/dec_… -H "$P"     # the full timeline
```

</details>

### Outcomes that never arrive

Each decision type says how long its outcome may take (`window_days` or `window_minutes` in the playbook). When the
window passes with no outcome, the decision is **overdue**: it gets an `overdue` event and stops counting as pending.
If the outcome rule says `if_missing: failure`, it's closed as failed instead. A late outcome is still accepted.

Something has to notice the window passing. Run one pass from cron or any scheduler; it works for the library too,
on the same database (`DATABASE_URL`, or `~/.actiongraph/actiongraph.db`):

```bash
actiongraph sweep       # Marked 2 overdue decisions.
```

Or have the server do it in the background every N minutes. It's off by default:

```bash
ACTIONGRAPH_SWEEP_MINUTES=15 actiongraph serve
```

### Outcomes ActionGraph fetches

Outcomes are graded by the rule of the playbook version the decision was made under. Beyond pushing them
(`…/outcome`, or `POST /v1/outcomes/webhook/{source}`), a rule can ask for them to be pulled, read over time, and
matched without a key (all optional):

```yaml
outcome:
  success: {path: recovered, eq: true}
  horizons: [{name: early, window_minutes: 60}, {name: final, window_days: 30}]   # the last one closes it
  harvest: {source: datadog, at: window_end}
  source: datadog
  webhook: {match: {entity: service.name, within_minutes: 120}, metrics: {recovered: alert.recovered}}
```

Register a harvester in a module, `engine.register_harvester("datadog", fn)` where `fn(decision_view)` returns metrics
(or `None`: not known yet), and run `actiongraph harvest --module mypkg.harvest`, or set
`ACTIONGRAPH_HARVESTERS=mypkg.harvest` so each sweep harvests first. Early readings show on the decision and never
count as evidence. `GET /v1/outcomes/coverage` reports the share of decisions past their window that got an outcome;
`autonomy.min_coverage: 0.8` keeps a decision type off `auto` while that share is lower.

### Dashboard

`actiongraph serve` also serves a dashboard at **http://localhost:8080**. Paste the people's key; it stays in that
browser tab.

- **Organizations** (`/console`): your organization, and the setup wizard. A server runs one organization. On fresh
  data the wizard opens by itself: start from one of 17 domain templates (insurance claims, SRE, retail, …) or from
  scratch, then name the organization, pick its decision types and options, choose who decides, set how options are
  ranked and the track record an agent needs to ask for approval or act alone (**Action Rank**), say what each
  decision is about (**Ontology**: subjects, their fields, each option's risk and who carries it out), add rules and
  what outcomes are worth, and review the playbook before it's proposed. Its **Setup** button edits it later.
- **Organization dashboard** (`/console/org`): decisions, what's waiting, outcomes and their value, agent vs people,
  flows, and two opt-in features: a weekly Slack digest and AI explanations (below).
- **Approvals:** what each agent wants to do, the options ranked by evidence, the situation, and why a person must
  approve. Approve or reject with your name on the record.
- **Overview:** what's waiting, what's decided, and how often each decision type and each agent's choices worked.
- **Decisions:** every decision, filterable, with its options, rule checks and full timeline.
- **Flows:** flows and the cases running through them.
- **Playbook:** decision types, options, rules in plain words, and what "worked" means.

<p align="center"><img src="docs/dashboard.jpg" width="760" alt="The Approvals screen: load L-4102, the agent wants rebook_known_carrier, with options ranked by how often they worked on similar loads, the situation, why a person must approve, and Approve and Reject buttons."></p>

The same views are on the API (`GET /v1/overview`, `/v1/decisions?status=waiting`, `/v1/flow-runs`) and the library
(`overview()`, `decisions(status=...)`, `runs()`).

**AI explanations (opt-in, off by default).** Claude can explain in plain words why a decision's options rank as they
do; it never changes a ranking. Install the extra (`pip install 'actiongraph-ai[llm]'`), set `ANTHROPIC_API_KEY` where the
server runs, and turn it on from the organization dashboard. **Slack digest (opt-in).** Add
`slack=<incoming webhook URL>` to `ACTIONGRAPH_NOTIFY` and turn the weekly digest on from the same page.

### Run from source

From a clone, `run.sh` does everything inside the folder: a virtualenv in `.venv`, data in `.data/actiongraph.db`,
keys in `.env` (gitignored). It needs Python 3.11+.

```bash
./run.sh
```

That sets up the first time, loads a demo (the freight pack) and starts the server at http://localhost:8080, printing a
sign-in link that holds your people's key (keep it private). Other commands:

| Command | What it does |
|---|---|
| `./run.sh serve` | start on the data already there; on fresh data, the setup wizard opens |
| `./run.sh demo software` | load another pack's demo (`freight` by default) and start |
| `./run.sh --org "Acme"` | name your organization (asked once otherwise) |
| `./run.sh autonomy` | watch an agent earn autonomy step by step (`--fail-at 20` injects a failure) |
| `./run.sh mcp-demo` | a risky MCP tool call waits for a person; read-only calls go straight through |
| `./run.sh link` | print the sign-in link again |
| `./run.sh eval` | score ranking, calibration, autonomy and safety on worlds with known truth |
| `./run.sh docker` | the same server on Postgres, with docker compose |
| `./run.sh reset` | delete the local data (keys in `.env` are kept) |

`PORT=9000 ./run.sh` changes the port; `PYTHON=/path/to/python` picks the interpreter. To start clean with your own
organization instead of the demo: `./run.sh reset`, then `./run.sh serve`.

### Connect any agent over MCP

The server speaks MCP over HTTP at `/mcp`. Point your client at it with the agent key:

```json
{
  "mcpServers": {
    "actiongraph": {
      "type": "http",
      "url": "http://localhost:8080/mcp",
      "headers": { "Authorization": "Bearer pxa_…", "X-ActionGraph-Agent": "load_recovery" }
    }
  }
}
```

| Tool | |
|---|---|
| `actiongraph_get_playbook` | the decisions this organization governs |
| `actiongraph_get_context` | everything around a case in one read: fields and who set them, related things, past and waiting decisions, unexplained changes, what may be decided, similar cases |
| `actiongraph_get_evidence` | open a decision and get its options ranked by evidence |
| `actiongraph_record_decision` | record the choice and why |
| `actiongraph_record_outcome` | record whether it worked |
| `actiongraph_pending_approvals` · `actiongraph_get_decision` | what's waiting, and one decision's full record |
| `actiongraph_find_similar` | past cases like this one |
| `actiongraph_capture_decision` | record a decision made outside a playbook, so it can become one |
| `actiongraph_flow_start` · `_flow_step` · `_flow_vote` · `_flow_gate` · `_flow_report` | run a flow; how runs ended per step choice |

### Self-host in production

SQLite is fine for trying it. Use Postgres for anything shared:

```bash
export DATABASE_URL=postgresql+psycopg://actiongraph:…@db:5432/actiongraph
pip install "actiongraph-ai[postgres]"
```

Or run it with Docker Compose (Postgres included):

```bash
docker compose run --rm core actiongraph init     # prints the keys
ACTIONGRAPH_KEY=pxc_… ACTIONGRAPH_AGENT_KEY=pxa_… docker compose up -d
```

Add `ACTIONGRAPH_SWEEP_MINUTES=15` to that command to mark overdue outcomes from the server, or schedule
`docker compose run --rm core actiongraph sweep` (see [Outcomes that never arrive](#outcomes-that-never-arrive)).

Put it behind TLS and keep both keys in a secret manager. See [SECURITY.md](SECURITY.md).

### API

| | |
|---|---|
| Playbook | `GET /v1/playbook` · `POST /v1/playbook/validate` · `POST /v1/playbook/versions` · `POST …/{v}/activate` |
| Decisions | `POST /v1/recommend` · `POST /v1/record` · `GET /v1/decisions/{id}` · `POST …/approve` · `…/reject` · `…/outcome` · `POST /v1/decision-types/{name}/autonomy` |
| Flows | `GET /v1/flows` · `POST /v1/flows/{name}/versions` · `…/activate` · `POST /v1/flows/{name}/runs` · `GET /v1/flow-runs/{id}` · `POST …/steps/{step}` · `GET …/gates/{step}` · `POST …/gates/{step}/sign` · `POST …/swarm/{step}/votes` · `POST /v1/flow-runs/{id}/outcome` · `GET /v1/flows/{name}/autonomy` · `GET /v1/flows/{name}/report` |
| Packs | `GET /v1/packs` · `POST /v1/packs/{pack}/install` |
| Agents | `POST /mcp` |

Interactive docs are at `http://localhost:8080/docs` while the server runs.

## See it run

Fourteen short scenarios show what ActionGraph is for, from one guarded refund to agents voting on a release. Each
runs in seconds on a throwaway database and ends with why it matters.

```bash
python examples/scenarios/08_parallel_specialists.py   # two agents, one incident, one gate
python examples/scenarios/live.py                      # all 14 as an animated page, calling a live server
```

| | Single agent | Multi-agent |
|---|---|---|
| Approvals | [01 guard a risky action](examples/scenarios/01_guard_one_risky_action.py) · [05 a person says no](examples/scenarios/05_reject_and_choose_again.py) | [08 two specialists, one gate](examples/scenarios/08_parallel_specialists.py) · [11 a board that always signs](examples/scenarios/11_custom_flow_signoff.py) |
| Rules and evidence | [03 ask, record, approve](examples/scenarios/03_ask_record_approve.py) · [04 rules](examples/scenarios/04_rules_block_and_route.py) · [06 evidence](examples/scenarios/06_evidence_ranking.py) | [09 a swarm votes](examples/scenarios/09_swarm_vote.py) · [10 the swarm splits](examples/scenarios/10_swarm_split.py) |
| Earned autonomy | [02 a guard earns autonomy](examples/scenarios/02_guard_earns_autonomy.py) | [07 trust per agent](examples/scenarios/07_trust_per_agent.py) · [12 agents can't approve](examples/scenarios/12_agents_cannot_approve.py) |
| Memory and setup | [13 capture before a playbook](examples/scenarios/13_capture_and_precedent.py) | [14 two keys, one server](examples/scenarios/14_same_answers_over_http.py) |

All of them, and the animated page ([`scenarios.html`](examples/scenarios/scenarios.html)), are described in
[examples/scenarios](examples/scenarios/README.md).


## How good is the evidence?

`actiongraph eval` runs the real engine against simulated worlds where the true success rate of every action in every
situation is known, and scores what ActionGraph recommended against that truth: regret against random, the team's
habit and a context-free oracle, calibration, interval coverage, how often the autonomy gate can be lucky, and
safety invariants under random use. Seeded, with 95% intervals.

```bash
actiongraph eval --quick
```

Where the situation decides the best action, ActionGraph cuts regret by 82% against random and beats "do what usually
works" by more than half. Where one action is best everywhere, it learns that the situation doesn't matter and
matches "do what usually works" by the last third. Where the world changes halfway, it adapts slowly unless the
decision type turns on exploration (`explore: 0.1`), which cuts late regret there by about a quarter. An
agent that succeeds half the time never earns `approve`; one right at the 70% bar earns it about 10% of the time,
and one at 90% always does within 60 decisions. Methods, full results and
what to do about them are in [docs/evals.md](docs/evals.md). Synthetic worlds measure the engine, not lift on your
data.

## What it protects, and what it doesn't

ActionGraph is a beta. Here is what holds, and under which conditions.

**It holds against the agent when it runs as a server with two keys.** The agent key can never approve, reject,
activate a playbook or sign a gate, whatever it sends. Give each agent its own key (`ACTIONGRAPH_AGENT_KEYS`) so it
can't claim another agent's name or record.

**On one machine, with no server, it is a record, not a lock.** The quickstart and `mcp-gate` without `--url` write to
a local SQLite file. Anything running as you, including an agent with a shell, can open that file or call `approve`.
That is fine for trying it and for an agent that can only call the functions you guard. For an agent that can run
commands, run `actiongraph serve` and give the agent only the agent key (`mcp-gate --url … --key …`).

**Guards trust the caller's settings unless the server sets them.** In your own code that's what you want. When an
agent calls `/v1/guards/{name}/check` itself, set `ACTIONGRAPH_GUARD_POLICY="deploy=always, read_*=never,
refund=always:20"` so the server decides which guards need a person; a name no pattern matches always does.

**Earned autonomy is only as honest as the outcomes.** Outcomes reported by an agent about its own actions are kept
but don't earn it autonomy. Report outcomes from the system that sees them (a webhook, a harvester, a person), set
`if_missing: failure` or `min_coverage` so outcomes that never arrive can't flatter the record, and start every
decision type at the `approve` ceiling.

**What isn't there yet:** retention and redaction of situation data (notifications send it to Slack or ntfy); tamper
evidence on the record (it is an ordinary database: protect it like one); a single switch to pause all autonomy (set
each ceiling to `approve`); per-person sign-in, which the hosted version adds. Use Postgres for anything shared: on
Postgres each decision is locked while it is decided, approved or graded.

## Works with your tools

- **Agent frameworks:** examples for **Claude** (Claude API tool runner) and **CrewAI**, plus MCP for any MCP client
  and plain HTTP for any language. Each one gates the real action on a `decided` record. See
  [integrations/](integrations/).
- **Coding assistants:** [skills/actiongraph](skills/actiongraph/SKILL.md) teaches Claude Code, Codex, Cursor and
  other assistants that support agent skills to wire ActionGraph into a codebase and write playbooks:

  ```bash
  npx skills add https://github.com/actiongraphai/actiongraph --skill actiongraph
  ```

  For Claude Code, you can instead copy `skills/actiongraph` into your project's `.claude/skills/`.

## What ActionGraph is, and isn't

ActionGraph is a complete decision record and authority layer for **one organization**, with two keys: one for people,
one for agents. It trusts whoever holds the people's key to say who approved. It never runs your agents or their
steps; your code, framework or orchestrator does, and asks ActionGraph at each decision and gate.

A hosted version of ActionGraph is planned. It adds:
- many organizations, with per-person sign-in and roles;
- a console, Slack approvals and on-call routing;
- outcome connectors for your systems;
- discovery and backtesting from your history;
- industry packs and audit exports.

## Licence

[Apache-2.0](LICENSE). Use it, change it, self-host it, build products on it, commercially too.

## Contributing

Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md). Report security problems privately,
as [SECURITY.md](SECURITY.md) explains.
