Metadata-Version: 2.4
Name: segurai
Version: 0.4.0
Summary: Provenance and authority for AI agent chains - who authorized what your agents did
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/Yaxomiller/segurai
Project-URL: Repository, https://github.com/Yaxomiller/segurai
Project-URL: Changelog, https://github.com/Yaxomiller/segurai/blob/master/CHANGELOG.md
Project-URL: Documentation, https://github.com/Yaxomiller/segurai/blob/master/docs/ARCHITECTURE.md
Project-URL: Issues, https://github.com/Yaxomiller/segurai/issues
Keywords: ai-agents,authorization,provenance,audit,opentelemetry,langgraph,mcp
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=42.0
Requires-Dist: pyjwt[crypto]>=2.8
Requires-Dist: tomli>=2.0; python_version < "3.11"
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.30; extra == "otel"
Requires-Dist: opentelemetry-sdk>=1.30; extra == "otel"
Provides-Extra: langgraph
Requires-Dist: langgraph>=1.0; extra == "langgraph"
Provides-Extra: mcp
Requires-Dist: mcp>=2.0; extra == "mcp"
Provides-Extra: openai-agents
Requires-Dist: openai-agents>=0.24; extra == "openai-agents"
Provides-Extra: claude-agent
Requires-Dist: claude-agent-sdk>=0.2; extra == "claude-agent"
Provides-Extra: crewai
Requires-Dist: crewai>=1.15; extra == "crewai"
Provides-Extra: collector
Requires-Dist: opentelemetry-proto>=1.30; extra == "collector"
Provides-Extra: identity
Requires-Dist: pyjwt[crypto]>=2.8; extra == "identity"
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
Provides-Extra: server
Requires-Dist: segurai[collector,identity]; extra == "server"
Provides-Extra: intent
Requires-Dist: anthropic>=1.5; extra == "intent"
Provides-Extra: judge
Requires-Dist: anthropic>=1.5; extra == "judge"
Provides-Extra: all
Requires-Dist: segurai[claude-agent,collector,identity,intent,judge,langgraph,mcp,openai-agents,otel,postgres]; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.30; extra == "dev"
Requires-Dist: segurai[all]; extra == "dev"
Dynamic: license-file

# Segurai

[![CI](https://github.com/Yaxomiller/segurai/actions/workflows/ci.yml/badge.svg)](https://github.com/Yaxomiller/segurai/actions/workflows/ci.yml)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/downloads/)
[![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)

**Provenance and authority for AI agent chains.** Records what a human asked for, records what the agents actually did, and links the two — so "who authorized this?" has an answer.

> A manager types *"clean up our old sales records."* An assistant passes the job to a CRM agent, which deletes 400 customer records. A month later an auditor asks who authorized it. Every log says: *the service account did it.*
>
> The trail from the action back to the human is broken. That is what this fixes.

**See it in one minute:** `pip install segurai`, then `segurai demo`. That builds a made-up company from real records and opens the dashboard, including the scene where an insider rewrites the evidence and gets caught. Talk tracks for investors and engineers: [docs/DEMO.md](docs/DEMO.md).

Install it and import it as `segurai`. The signed grant that each agent hop carries is called a **warrant** — a narrow, written-down, traceable permission, like a search warrant — and that word is used throughout the code and the docs.

New here? [docs/WHY.md](docs/WHY.md) is the engineering write-up — the problem, the designs that don't work, and the parts that were hard. [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) explains how everything fits together in plain language.

---

## Status

**0.4 — deployable: one command runs the whole thing, and agents can't go around it.**

- **A gateway agents can't go around.** Agents reach real systems only through the gateway, which holds the systems' credentials. It checks every request against the agent's warrant and the company's rules before forwarding it. Each request is signed with the agent's own key, so a stolen chain token isn't enough.
- **Who asked, proven.** The issuer accepts an ID token from the company's login system (OIDC), checks it, and grants no more than the person's group may ever have. Requests started this way say "identity verified" on every page. Others say "claimed".
- **Company rules.** Deny and limit rules that no request can override, versioned and written into the tamper-evident log.
- **Alerts** to Slack, a webhook (HMAC-signed) or email, for violations, blocked actions and tampering.
- **Outside witnesses** for checkpoints, and **evidence packs**: a zip about one request that an auditor can verify with nothing but the public key.
- **Dashboard sign-in** with roles (viewer, auditor, admin), company login via OIDC, an access log, and search and filters.
- **`segurai serve`** runs it all from one checked `segurai.toml`. **Docker** and **PostgreSQL** are supported, and CI tests both end to end.
- **More frameworks:** the OpenAI Agents SDK, the Claude Agent SDK and CrewAI, alongside LangGraph, MCP and OpenTelemetry.
- **The judge asks twice** and hands disagreements to a person, and two people can label its test cases blind.

**M0 — chain capture: complete.**

- Signed, attenuation-only delegation (Ed25519), with keys that persist so old chains can be re-verified
- Tier 1 admission checks on every action, in about a microsecond
- Observe mode (record and flag) and enforce mode (stop before it happens)
- Integrations: **LangGraph** (nodes, subgraphs, ToolNode), **MCP** (client and server), **OpenTelemetry** (GenAI semantic conventions)
- SQLite storage, chain reconstruction, CLI
- A collector that receives spans from many processes and re-checks every signature

**M1 — intent compiler: target met (91.4%, measured 5 Nov 2026).**

- One Claude call turns a request into a scope contract (structured output, cached instructions, refusal fallbacks)
- Contracts are checked against the organisation's catalog and clamped to the person's real permissions
- Conditions that the catalog's evidence can test are written as Checks automatically
- A read-only web view: the request and contract beside the chain, findings inline, signatures re-verified on every load
- 50 labeled eval cases: **32/35 held-out contracts acceptable (91.4%)** against an 80% target; all three misses were label problems, now fixed ([results](evals/results/2026-11-05/README.md))

**M2 — Tier 1 check suite: complete.**

- Every rule an action breaks is reported: operation, target, per-action scale, session total, irreversibility, and conditions
- Conditions become testable Checks (e.g. `days_since_activity >= 180`), evaluated against evidence the agent reports; missing evidence is "unverifiable", never a false alarm
- 20 seeded scenarios: 10/10 violations caught for the right reason, 0/10 false positives, 0.15 ms per checked action (p99)

**M3 — public release: in progress.**

- Zero-integration path: existing OpenTelemetry GenAI spans become an observed chain with no code changes
- CI on Linux, Windows and macOS across Python 3.10–3.13, plus packaging checks
- Public repository, CI green on Linux, macOS and Windows across Python 3.10–3.13
- PyPI release wired up and waiting on one PyPI setting ([docs/RELEASING.md](docs/RELEASING.md)); distribution is the remaining work

**M4 — Tier 2 semantic judge: target not met yet (48% on ambiguous cases, measured 5 Nov 2026).**

- Reviews only the actions Tier 1 flagged, one narrow question each: within intent, outside intent, or needs a human
- Verdicts sit beside Tier 1's record — advice, never authority — and agent-written text is treated as untrusted data
- 50 labeled cases (29 ambiguous, 3 with planted prompt injection); approving a bad action counts as a dangerous miss
- The first run found a design gap, not a weak model: the judge was shown size limits without being told whether a person set them or the compiler estimated them, which explains every disagreement in that cluster. `judge-v2` fixed that cluster and had zero dangerous misses on re-run, but the judge disagrees with itself on half the hard cases between versions, so the hard-case labels now need independent human review ([5 Nov](evals/results/2026-11-05/README.md), [10 Nov](evals/results/2026-11-10/README.md))
- `--votes 2` asks twice and turns disagreement into "a person must decide"; `segurai label` and `segurai label-agreement` let two people label the cases blind and measure how far they agree. The score will be re-measured against their labels

**M6 — scope-creep report: built.**

- Per agent and per person, over any window: operations never used, targets never touched, wildcards that could shrink, size limits against the largest real change
- A proposed tightened scope built only from observed use, with the evidence behind it
- Grants from warrants or from an identity-provider export; Markdown, HTML, JSON, and a CSV of every unused permission

**M7 — tamper-evident log: built.**

- Every record appends to a hash chain in the same transaction, so an edited or deleted row no longer passes unnoticed
- `segurai audit` names what changed; `segurai checkpoint` signs the chain's head with a key the database doesn't hold, which catches a full rewrite
- 0.04 ms per checked action (0.4 ms at the 99th percentile), against a 5 ms budget

**M5 — design-partner pilots: kit ready.**

- A hardened container running the whole deployment, with SQLite or PostgreSQL, smoke-tested end to end in CI ([deploy/](deploy/README.md))
- A pilot runbook: day-0 setup, the weekly review, the day-30 wrap-up, data handling ([docs/PILOT_RUNBOOK.md](docs/PILOT_RUNBOOK.md))
- The pilots themselves need partners — that part is people, not code

## Install

```bash
pip install segurai                     # core: needs only `cryptography` and `pyjwt`
pip install "segurai[server]"           # + what `segurai serve` needs (dashboard, ingest, company sign-in)
pip install "segurai[postgres]"         # + PostgreSQL instead of a SQLite file
pip install "segurai[langgraph]"        # + LangGraph integration
pip install "segurai[mcp]"              # + MCP integration
pip install "segurai[openai-agents]"    # + OpenAI Agents SDK integration
pip install "segurai[claude-agent]"     # + Claude Agent SDK integration
pip install "segurai[crewai]"           # + CrewAI integration
pip install "segurai[otel]"             # + OpenTelemetry spans
pip install "segurai[intent]"           # + intent compiler (Anthropic SDK)
pip install "segurai[judge]"            # + Tier 2 judge (Anthropic SDK)
```

Working on Segurai itself:

```bash
git clone https://github.com/Yaxomiller/segurai && cd segurai
pip install -e ".[dev]"             # everything, plus pytest and ruff
python -m pytest -q
```

## Quick start

```python
import segurai
from segurai import Scope

segurai.configure(store="segurai.db")      # signing key kept beside it as segurai.key

granted = Scope.of(
    operations=["read", "update", "delete"],
    targets=["crm.*"],
    max_scale=50,
    constraints=["only records with no recent activity"],
)

# An agent says only what it narrows; everything else is inherited.
@segurai.agent("crm_agent", scope=Scope.of(targets=["crm.opportunities"]))
def crm_agent():
    segurai.act("read", "crm.opportunities", scale=412)
    segurai.act("delete", "crm.opportunities", scale=400, irreversible=True)

@segurai.agent("assistant")
def assistant():
    crm_agent()

with segurai.session(
    principal="sarah@company.com",
    request="clean up our old sales records",
    scope=granted,
) as s:
    assistant()

print(segurai.render(s.session_id))
```

```
Delegation chain
  └─ entrypoint  [wrt_7a07522323244bb1]
        ops={delete,read,update} targets={crm.*} max_scale=50
     └─ assistant  [wrt_3f22fd11d57f4d91]
           ops={delete,read,update} targets={crm.*} max_scale=50
        └─ crm_agent  [wrt_ba50b4faee524582]
              ops={delete,read,update} targets={crm.opportunities} max_scale=50
              [ok     ] read crm.opportunities scale=412
              [FAIL   ] delete crm.opportunities scale=400
                        -> scale 400 exceeds limit 50
                        -> irreversible action not permitted by scope

Summary: 3 warrants, 2 actions, 1 violation(s)
  ! crm_agent: delete crm.opportunities (scale=400) - scale 400 exceeds limit 50; irreversible action not permitted by scope [went ahead]
```

`[FAIL   ]` means the action was outside the warrant and went ahead (observe mode). With `segurai.configure(mode="enforce")` it is stopped before it happens and shows as `[BLOCKED]`.

## Guarding tools

Describe a tool once with an `ActionSpec` — what operation it performs, on which resource, at what scale — and every call is checked *before* the tool body runs:

```python
from segurai import ActionSpec, count

@segurai.tool(ActionSpec("delete", "crm.{table}", scale=count("ids"), irreversible=True))
def delete_records(table: str, ids: list[int]) -> int:
    ...
```

## Conditions

A plain-English condition can't be checked by a program; a `Check` can. The agent reports evidence about the records it touches, and every item must satisfy the condition:

```python
from segurai import Check

granted = Scope.of(
    operations=["read", "archive"], targets=["crm.*"], max_scale=50, max_total=50,
    checks=[Check(field="days_since_activity", op=">=", value=180,
                  condition="only records with no recent activity")],
)

segurai.act("archive", "crm.opportunities", scale=3, days_since_activity=[200, 12, 400])
# -> condition not met: only records with no recent activity (days_since_activity = 12, required >= 180)
```

`max_total` caps the records changed across the whole session, so 400 one-record deletions can't slip under a per-action limit of 50. An action that reports no evidence for a check is marked unverifiable (`?` in the tree) rather than treated as a violation. Run the 20-scenario suite with `segurai eval-tier1`.

## LangGraph

```python
from segurai.instrument.langgraph import ToolGuard, agent_node

guard = ToolGuard({
    "delete_records": ActionSpec("delete", "crm.{table}", scale=count("ids"), irreversible=True),
})

crm = StateGraph(MessagesState)
crm.add_node("model", call_model)
crm.add_node("tools", ToolNode(tools, wrap_tool_call=guard.wrap, awrap_tool_call=guard.awrap))
...

app = StateGraph(MessagesState)
app.add_node("crm_agent", agent_node("crm_agent", crm.compile(),
                                     scope=Scope.of(targets=["crm.opportunities"])))

with segurai.session(principal="sarah@company.com", request=request, scope=granted):
    app.invoke({"messages": [HumanMessage(request)]})
```

Works for plain, async and parallel nodes, and for compiled subgraphs. In enforce mode a blocked tool call comes back to the model as an error message saying why, so the agent can change course instead of the graph crashing. Full example: [examples/langgraph_demo.py](examples/langgraph_demo.py).

## MCP

```python
from segurai.instrument.mcp import WarrantedClient, bind_from_meta

# Agent side: calls are checked before they are sent, and carry the warrant.
crm = WarrantedClient(mcp_client, server="crm", rules={...})
await crm.call_tool("delete_records", {"table": "opportunities", "ids": ids})

# Server side: verify the incoming warrant and continue the same chain.
@server.tool()
async def delete_records(table: str, ids: list[int], ctx: Context) -> str:
    with bind_from_meta(ctx, holder="crm_server"):
        segurai.act("delete", f"crm.{table}", scale=len(ids), irreversible=True)
        ...
```

Tools without a rule are described from the server's own `readOnlyHint` / `destructiveHint` annotations. Full example: [examples/mcp_demo.py](examples/mcp_demo.py).

## OpenAI Agents SDK, Claude Agent SDK, CrewAI

Each one is checked at the framework's own "before a tool runs" hook. In enforce mode, a refused call never runs, and the model is told why so it can change course:

```python
# OpenAI Agents SDK: a tool input guardrail on every tool, including handed-off agents'
from segurai.instrument.openai_agents import govern
agent = govern(Agent(name="crm_agent", tools=[delete_records]), rules=RULES)

# Claude Agent SDK: a PreToolUse hook; sub-agents get their own hop
from segurai.instrument.claude_agent import pre_tool_use
options = ClaudeAgentOptions(hooks={"PreToolUse": [HookMatcher(hooks=[pre_tool_use("assistant", RULES)])]})

# CrewAI: one hook for every agent in the process
from segurai.instrument.crewai import govern
govern(rules=RULES)
```

Each agent gets its own hop in the chain, so the record reads person → agent → action whichever framework ran it. The tests drive the real frameworks with a scripted model.

## OpenTelemetry

```python
from segurai.instrument import otel
otel.enable()
```

Sessions, agent hops and tool calls become spans named per the OpenTelemetry GenAI conventions (`invoke_workflow`, `invoke_agent`, `execute_tool`), carrying the full signed warrant as `warrant.*` attributes. The chain shows up in whatever tracing backend a team already uses. Full example: [examples/otel_demo.py](examples/otel_demo.py).

## Scopes from requests

Instead of writing the scope by hand, let the intent compiler read the request. One Claude call produces a structured contract, which is checked against your catalog of real operations and resources and clamped to the person's actual permissions — so a request can never grant more than the person already has.

```python
from segurai.intent import Catalog, IntentCompiler

segurai.configure(store="segurai.db", intent=IntentCompiler(Catalog.load("catalog.json")))

with segurai.session(principal="sarah@company.com",
                     request="clean up our old sales records",
                     ceiling=sarahs_permissions) as s:
    ...
```

Needs `pip install -e ".[intent]"` and `ANTHROPIC_API_KEY`. Try one request with `segurai intent "clean up our old sales records" --catalog evals/intent/catalog.json`; measure the compiler on 50 labeled cases with `segurai eval-intent` (see [evals/intent/](evals/intent/README.md)).

## Collector

Agents on many machines send spans to one place with the standard OpenTelemetry OTLP exporter:

```bash
segurai collect --db central.db --key org.pub --port 4318
```

The collector rebuilds every chain and re-checks every signature with the organisation's public key, refusing anything forged.

**Already using OpenTelemetry? Try it with no code changes.** Point your existing exporter at the collector. Standard GenAI spans (`invoke_agent`, `execute_tool`) from any framework are rebuilt into an *observed* chain: which agent called which tool, and for whom. Observed chains are clearly labeled — nothing in them was authorized, signed or checked — so they show where warrants would go before you adopt them.

## Audit: proving the record wasn't touched

Signatures already make a warrant impossible to alter unnoticed. The record of what agents *did* used to be ordinary rows — editable by anyone with database access. Now every record also appends to a hash chain:

```bash
segurai audit          # exits non-zero if anything was edited, deleted or reordered
segurai checkpoint     # sign the chain's head; keep the line outside the database
```

```
TAMPERING DETECTED - 1 problem(s):
  ! row at entry 5 (act_038feb5d0f8648cd): this action no longer matches what was logged; the row was edited
```

A hash chain alone can be rebuilt by someone patient with database access, so the audit says so plainly when no checkpoint exists. A checkpoint closes it: the head hash signed with a key the database never contains, so a cover-up would need a forged signature too.

## Scope-creep report

Which permissions did we give agents that they never used?

```bash
segurai report --days 30                                   # Markdown to the terminal
segurai report --days 30 --format csv --out unused.csv     # one row per unused permission
segurai report --grants okta-export.json --format html --out report.html
```

For every agent, and for each person's sessions as a whole, it lists operations never used, targets never touched, wildcards that were only used for a few resources, and size limits against the largest change actually made. It then proposes a tightened scope built only from observed use (it never adds anything), with the evidence behind it. Pass `--grants` with standing permissions exported from an identity provider ([format](examples/grants.example.json)) to compare those too, including against observed chains from plain OpenTelemetry. Rarely-run work may need permissions a short window doesn't show, so every report says so and rates its confidence by how much activity it saw.

## Semantic judge (Tier 2)

Tier 1 is exact but can only compare. For the actions it flags, the judge asks Claude one narrow question: given what this person asked for, is this action within intent, outside it, or does a person need to decide?

```bash
segurai judge <session_id> --yes      # judge the session's flagged actions
```

Verdicts are stored beside Tier 1's findings and shown in `segurai show` and the web view; they never change Tier 1's record. Everything the judge reads from agents and tools is treated as untrusted data, so "this was pre-approved" written by an agent grants nothing. Measure it with `segurai eval-judge` on 50 labeled cases (see [evals/tier2/](evals/tier2/README.md)).

`--votes 2` asks the model twice. When the two answers disagree, the verdict becomes "a person must decide" rather than a coin toss. `segurai label` lets a person label the test cases without seeing the existing answers, and `segurai label-agreement` measures how far two people agree.

## Web view

One page per request:

- the request and its contract, beside the delegation chain;
- whether the person was proven or only claimed;
- every action's findings inline, with the AI review where there is one;
- the signatures, re-checked each time the page loads.

Other pages cover record integrity, unused permissions, people, and who opened what. Requests can be searched and filtered by person, agent and outcome.

The pages are plain HTML with no scripts. Everything that came from a request is escaped, and every page carries a strict Content-Security-Policy.

Under `segurai serve`, people sign in with an account or the company login (OIDC), and get one of three roles:

- **viewer** sees requests;
- **auditor** also sees integrity and access, and can download evidence packs;
- **admin** also manages people.

Sign-in failures are throttled, sessions are kept only as hashes, forms carry CSRF tokens, and every page view is written to the tamper-evident log. `segurai ui --db segurai.db` still opens a local, single-user view.

## Running Segurai

```bash
pip install "segurai[server]"
segurai init                                                 # a commented segurai.toml and the organisation's key
segurai users add --email you@acme.example --role admin
segurai serve                                                # dashboard on http://127.0.0.1:8700/
```

`segurai serve` runs everything from one configuration file:

- the dashboard;
- span ingest;
- the issuer;
- the gateway;
- the alert worker;
- the checkpoint worker.

The file is checked strictly. A typo is an error, and so is a secret written in it: secrets come only from environment variables the file names (`..._env`). `segurai config check` validates it, and works while the server is running.

**Docker:** see [deploy/README.md](deploy/README.md). Three commands start it with SQLite, three more with PostgreSQL. CI builds the image and runs a deployment end to end with each, on every push.

**PostgreSQL:** set `database_env = "SEGURAI_DATABASE_URL"` in `segurai.toml`. Records, hashes and audits are identical on SQLite and PostgreSQL, and the whole test suite runs on both. Several servers can share one database without ever forking the log.

## The gateway: agents can't go around it

Agents are given the gateway's address instead of the CRM's (or the billing system's, or any HTTP API's). The gateway holds the real credentials, so an agent has no way to call the system directly. Each request:

1. carries the agent's chain and a fresh signature from that agent's own key (so a copied chain alone is useless), with a 60-second window and a one-time nonce;
2. is matched to a route that says what it does, for example `DELETE /opportunities/{id}` → *delete one crm.opportunities record, irreversibly*;
3. is checked against the warrant and the company's rules, recorded before it is sent, and forwarded only if allowed.

```python
from segurai.gateway import GatewayClient

with segurai.resume(chain_token, holder="crm_agent"):
    crm = GatewayClient("https://segurai-gateway.internal")
    crm.request("POST", "/crm/opportunities/4471/archive")    # allowed: forwarded
    crm.request("DELETE", "/crm/opportunities/4502")          # 403: never reaches the CRM
```

## Who asked, proven

An app that starts agent work for a person sends that person's ID token from the company's login system to the issuer:

```bash
POST /v1/sessions        Authorization: Bearer <ID token>        {"request": "Archive the deals that went quiet"}
```

The issuer checks the token's signature against the login system's published keys, its issuer, audience, expiry and email domain. It then mints a root warrant inside the first **ceiling** that matches the person's groups. A ceiling is the most anyone in that group can ever be granted, so no request can ask for more. The response is a chain token that the agent continues with `segurai.resume`.

## Company rules

```toml
[[policy.rules]]
name = "nobody deletes payroll"
targets = ["hr.payroll"]
operations = ["delete"]
effect = "deny"
```

Rules are either **deny** or **limit** (a maximum size, or no irreversible actions), and can be scoped to people, agents, operations or targets. No request or grant can override them. Every version of the rules is written into the tamper-evident log, and each finding names the version in force.

## Alerts, witnesses and evidence packs

- **Alerts** go to Slack, a webhook (signed with HMAC) or email when an action breaks a rule, is blocked, or the log fails its audit. Delivery is retried with backoff. Each alert is queued once and sent by exactly one server, however many share the database.
- **Witnesses**: checkpoints are also published outside the database, to an append-only file or a webhook. `segurai audit --witness FILE` then catches a rewrite even by someone holding the signing key.
- **Evidence packs**: `segurai evidence <session>` writes a zip for one request. It contains the records, their log entries, a signed checkpoint, the public key and a readable report. `segurai evidence-verify pack.zip --key org.pub` checks it with nothing else. An auditor needs neither access to the system nor trust in whoever sent it.

## CLI

```bash
segurai demo                  # the sample company, in the browser (demo tamper / demo cover-up)
segurai init                  # a commented segurai.toml and the organisation's key (--for-docker, --postgres)
segurai config check          # validate segurai.toml, even while the server runs
segurai serve                 # run the deployment segurai.toml describes
segurai users add|list|set    # people who can sign in to the dashboard
segurai sessions              # list recent sessions
segurai show <session_id>     # render the delegation tree (--json, --ascii)
segurai verify <session_id>   # re-check every signature, link and narrowing
segurai creep <session_id>    # granted vs exercised scope
segurai report --days 30      # scope-creep report across sessions
segurai audit                 # check the tamper-evident log (--witness FILE)
segurai checkpoint            # sign the log's current state (--witness FILE)
segurai evidence <session_id> # an evidence pack an auditor can check alone
segurai evidence-verify pack.zip --key org.pub
segurai backup --out copy.db  # consistent copy of a SQLite database, safe while running
segurai keygen                # create a signing key
segurai collect / ui          # the older single-purpose collector and local web view
segurai intent "<request>"    # compile a request into a scope contract
segurai eval-intent ...       # grade the intent compiler on labeled cases
segurai eval-tier1            # run the Tier 1 scenario suite (no API calls)
segurai judge <session_id>    # Tier 2: judge a session's flagged actions (--votes 2)
segurai eval-judge            # grade the judge on labeled cases
segurai label / label-agreement   # human labels for the judge's cases, and agreement between people
```

`--db` picks the database (default `segurai.db`, or a `postgresql://` URL); the key is found beside it.

## Design

**Warrants attenuate, never widen.** Each hop derives a child warrant from its parent. A child may narrow operations, targets, scale, or reversibility — never broaden them. Attempting to widen raises rather than silently clamping, because a caller trying to widen has a bug worth seeing. The signature covers the parent link and depth, so a chain cannot be re-parented or reordered after the fact.

If that invariant held at every hop, then whatever happened at the leaf was inside what the root principal granted. That is the whole claim.

**Patterns are compared as patterns.** A child asking for `crm.*` under a parent limited to `crm.?` must be refused, even though plain glob matching would read the child's `*` as an ordinary character and say yes. Containment is checked token by token and errs toward refusing: it may reject a scope that was technically safe, but never accepts one that isn't. Matching is case-sensitive on every platform.

**Unspecified fields inherit.** A declared child scope says what it *narrows*; anything it doesn't mention comes from the parent. Without this, narrowing one field would mean retyping every other — which trains people to paste a wide scope everywhere just to silence the error, producing exactly the over-permissioning this is meant to expose. Leaving a field out (`targets=None`) inherits it; an explicit empty list (`targets=[]`) means *none*.

**Scale bounds mutations, not reads.** An agent scanning 412 rows to find deletion candidates is doing its job; deleting 400 of them is the concern. Conflating them makes every table scan a violation and teaches people to ignore alerts.

**Unverifiable is not a violation.** When an action doesn't report the evidence a condition needs, the finding says so plainly. Treating it as a violation would bury real alerts in noise; treating it as a pass would be untrue.

**An action nobody can describe is not one anybody authorized.** A tool call whose arguments don't fit its `ActionSpec`, or a tool nobody wrote a spec for, is recorded as a violation rather than waved through.

**The record is evidence, or it isn't.** A log an engineer can quietly edit proves nothing, so every record is hashed into a chain and the audit says exactly what changed. Where the guarantee ends is stated rather than glossed: without a checkpoint signed outside the database, a determined editor could rebuild the chain.

**Observe by default.** Violations are recorded, nothing is blocked. Nobody lets an unproven library block production traffic — but they will let it watch, and watching produces the evidence that earns the right to enforce later.

**Observability never breaks the agent.** A failing listener or exporter is logged and ignored.

## What's next

| Milestone | |
|---|---|
| M1 | Intent compiler — target met: 91.4% |
| M2 | Tier 1 check suite — complete: 10/10 caught, 0 false positives |
| M3 | Public release; ingest existing OpenTelemetry spans with no code changes |
| M4 | Tier 2 semantic judge — 0 dangerous misses; 47% on ambiguous cases. Next: two people label the hard cases (`segurai label`), then re-measure with `--votes 2` |
| M5 | Design-partner pilots — deployment, Docker and PostgreSQL ready; next is the partners themselves |
| M6 | Scope-creep report — built |
| M7 | Tamper-evident log — built |

Known limits are listed honestly at the end of [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#honest-limits-what-is-not-done-yet).

## Tests

```bash
python -m pytest -q
```

## License

Apache-2.0
