Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,25 @@ jobs:
- name: Test
run: python -m pytest -q -rs

security:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- name: Install with every optional dependency
run: |
python -m pip install --upgrade pip
python -m pip install -e ".[langgraph,security]" mcp
- name: Bandit (source code; fails on any unmarked finding)
run: python -m bandit -r agent_readback examples -q
- name: pip-audit (known vulnerabilities in installed dependencies)
run: python -m pip_audit --skip-editable --progress-spinner off

build:
runs-on: ubuntu-latest
timeout-minutes: 10
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ build/
graphify-out/
.test-tmp*/
.test-python*/
.venv/
.venv*/
73 changes: 67 additions & 6 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,40 @@

All notable changes to `agent-readback`. Dates are UTC.

## Unreleased
## 0.3.0 — 2026-11-21

### Breaking changes

- `StripeRefundVerifier` refuses a client that sends a Stripe secret key
(`sk_live_...` or `sk_test_...`, as Basic auth or a Bearer header) with
`ValueError`. A secret key can also create refunds, which defeats the
independent check; use a restricted read-only `rk_` key.
- `SqlRowVerifier(..., placeholder=...)` raises `ValueError` for anything
other than `?`, `%s`, `:name`, `:1` or `$1`.
- A pending Stripe refund's finding is `pending` (was `unreachable`), and the
verdict keeps the new refunds in `observed` so it can be re-checked.
- The LangGraph example uses the same outcome labels as `run_eval`:
`false_completion` (was `false_completion_caught`), `done_but_unverified`
(was `said_done_unverified`), `said_failed_but_actually_done` (was
`said_failed_but_verified`) and `reported_failure` (was
`said_failed_and_failed` / `said_failed_unverified`).

### Security

- On Windows, where mode `0600` does nothing, a new evidence log is created
empty, has every existing access entry (explicit and inherited) removed with
`icacls` and is granted only to the
SID of the process's own access token (read with `whoami`), all before the
first record is written. `icacls` and `whoami` are run from the directory
`GetSystemDirectoryW` returns; `USERNAME`, `USERDOMAIN`, `SystemRoot` and
`PATH` are never used, so an environment naming another account cannot
lock the writer out of its own log. A failure (including an `icacls` that
prints nothing) warns and the log is still written.
- The `sk_` key check inspects only static keys (exactly httpx `BasicAuth`, not
a subclass, or a
Bearer header); a custom auth flow is never run during construction.
- `SqlRowVerifier` validates `placeholder`: it is spliced into the query
text, so a value such as `? OR 1=1` used to reach the database.

### Added

Expand All @@ -17,16 +50,44 @@ All notable changes to `agent-readback`. Dates are UTC.
failed verdicts are never re-checked. `StripeRefundVerifier.recheck`
judges only the refunds seen at the first check.
- `FindingKind.PENDING`: a Stripe refund that matches but has not settled.

### Changed

- A pending Stripe refund's finding is `pending` (was `unreachable`), and the
verdict keeps the new refunds in `observed` so it can be re-checked.
- Opt-in read limiting: `RateLimit(per_second, burst=1, *, max_wait=None)`
(thread-safe token bucket) and `limit_reads(target, limit)`, which applies it
to a verifier's `httpx.Client` (every request, paging included) or SQL
`connect` callable. A limit only delays reads. With `max_wait`, a read that
would wait longer raises `RateLimitTimeout` (a subclass of
`httpx.TimeoutException`) at once without using a slot, so the verdict is
`unverified` instead of the agent stalling. Limiting the same target twice
is refused.
- Test of `watched()` over MCP Streamable HTTP (local server on 127.0.0.1,
MCP 1.x and 2.x): an honest booking is `verified` and a misdescribed one
`failed`. `tests/mcp_stdio_server.py DATABASE PORT` serves HTTP.
- `security` extra (bandit, pip-audit, pinned) and a `security` CI job that
fails on any unmarked bandit finding or any known dependency vulnerability.

### Fixed

- On Windows, output from `whoami`/`icacls` that cannot be decoded (for
example a non-ASCII account name in another code page) no longer escapes
and stops the first evidence append; it is decoded tolerantly and any
failure warns.
- `RateLimit(..., max_wait=0)` no longer refuses a read inside a fresh burst
because of floating-point rounding. A rounding-sized wait counts as none;
the cutoff scales with the clock value, since `time.monotonic()` counts
from boot and its rounding error grows with uptime.
- The LangGraph example classifies a `FAILED` reply by the task verdict when
there is one, as `run_eval` does: writes that held at the wrong time are
`reported_failure`, not `said_failed_but_actually_done`.
- A pending Stripe refund with a wrong amount, currency or a second refund is
now `failed`; before, being pending hid the mismatch as `unverified`.
- The example `.env` loader warns when the file cannot be read instead of
ignoring the error.

### Documentation

- README: real-model results for the LangGraph agent (claude-sonnet-5-5,
claude-haiku-5-5, gpt-6-luna; 50 runs each, verdicts identical to
`run_eval` run for run), MCP 2.x and HTTP coverage, a "Rate limiting the
verifier's reads" section, and two new Security model rows.

## 0.2.2 — 2026-11-19

Expand Down
8 changes: 5 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co

## What this is

Readback (`agent-readback`, v0.2.2): checks an AI agent's "Done." claim against the system of record. Snapshot before the agent acts, re-read afterward through a read-only path, emit a deterministic verdict (`verified` / `failed` / `unverified`). Verdicts never come from an LLM. Only runtime dependency: `httpx`.
Readback (`agent-readback`, v0.3.0): checks an AI agent's "Done." claim against the system of record. Snapshot before the agent acts, re-read afterward through a read-only path, emit a deterministic verdict (`verified` / `failed` / `unverified`). Verdicts never come from an LLM. Only runtime dependency: `httpx`.

## Commands

Expand All @@ -21,16 +21,18 @@ export READBACK_LOG_KEY=... # key the log was written wit
readback verify-log evidence.jsonl # chain check, prints head hash (0 ok, 1 broken/untrustworthy, 2 bad args, 3 file error; --require-key for audits)
readback report evidence.jsonl # verdict counts / failed rate by action
python -m build # wheel + sdist into dist/
python -m pip install -e ".[security]" && python -m bandit -r agent_readback examples -q && python -m pip_audit --skip-editable # security scans (CI runs the same)
```

`run_eval` refuses an existing `--log` path (default: fresh temp file, path printed at the end). Real-model eval: `--provider anthropic|openai --model <id>` with `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` in the environment; `--fhir-url` targets a real FHIR R4 test server instead of the mock. No lint/format config exists. On Windows the `readback` script lands outside PATH; use `python -m agent_readback`.
`run_eval` refuses an existing `--log` path (default: fresh temp file, path printed at the end). Real-model eval: `--provider anthropic|openai --model <id>` with `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` in the environment; `--fhir-url` targets a real FHIR R4 test server instead of the mock. No lint/format config exists; security scans (bandit + pip-audit, pinned in the `security` extra) run in CI and must stay clean: mark a false positive with a reason and `# nosec <ID>` at the end of the reported line. On Windows the `readback` script lands outside PATH; use `python -m agent_readback`.

## Architecture

- `agent_readback/core.py` — the whole contract. `Claim` (action, agent_said, expected fields, context) → `Verifier` protocol (`snapshot(claim)` before, `check(claim, before)` after) → `Verdict` with `Finding`s of kind `missing` / `wrong_value` / `extra_effect` / `unreachable`. `watch()` context manager orchestrates: snapshot on enter with a `probe` claim, check in a `finally` on exit (runs even if the agent raises) with the final claim set via `w.claims(...)`, optional settle retries (only `FAILED` is retried, never `UNVERIFIED`), then appends to the log and fires `on_verdict` callbacks.
- `agent_readback/verifiers/` — FHIR Appointment (create/update/cancel), Stripe refund, SQL row. Shared pattern: snapshot captures prior state (existing IDs for FHIR/Stripe; row + row count for SQL), or `None` on read error; anything new that wasn't claimed becomes `extra_effect`; read errors yield `UNVERIFIED`, never `FAILED`; a `None` snapshot means `UNVERIFIED`. Field comparison goes through `compare_fields`. FHIR normalizes timestamps to UTC and deliberately leaves zoneless times unnormalized so they mismatch. FHIR and Stripe reads are page-capped (`MAX_PAGES`); overflow → `UNVERIFIED`. A matching `pending` Stripe refund is `UNVERIFIED` with a `PENDING` finding (a pending refund with a wrong field is `FAILED`). `core.recheck(verifier, verdict_or_dict, log)` re-judges only `UNVERIFIED` verdicts via the verifier's optional `recheck(claim, observed)` and tags `context["recheck_of"]`; Stripe judges only the refunds seen at the first check.
- `agent_readback/evidence.py` — append-only JSONL log; each record carries `seq` and hashes the previous (`GENESIS` = 64 zeros). With a key (`key=` or `READBACK_LOG_KEY`) hashes are HMAC-SHA256; `_digest(prev, seq, body, key)` is the single hashing function. File opened `0600` + `O_APPEND`. Optional `anchor=` callable gets `(count, head)` after each append (`FileAnchor` writes it atomically to a separate file; a failing anchor warns and sets `anchor_error`, never raises); `verify-log --anchor FILE` / `--head HASH` uses `check_anchor` to catch truncation. Redacts by default: no observed values, agent text replaced by a keyed digest, expected/finding values replaced unless the field is in `keep_fields` (`"*"` keeps all). Preserve this default when changing the log format. README "Security model" table must stay in sync with these guarantees.
- `agent_readback/adapters.py` — `watched(fn, verifier, to_claim, log, said=...)` wraps a sync/async callable in `watch()`; `to_claim(*args, **kwargs)` → probe or `None` (skip). Used for MCP (`session.call_tool = watched(...)`, `said=mcp_text`) and LangGraph nodes. Imports neither framework; tests use them via `importorskip`.
- `agent_readback/ratelimit.py` — opt-in read limiting. `RateLimit(per_second, burst)` is a thread-safe token bucket (GCRA; slot reserved under the lock, sleep outside it; clock and sleep injectable for tests). `limit_reads(target, limit)` adds an httpx request hook to a sync `httpx.Client` or wraps a SQL `connect` callable; it refuses an `AsyncClient` and a target it already limited (marked with `_readback_rate_limit`). Keyword-only `max_wait`: a wait longer than that raises `RateLimitTimeout` (subclass of `httpx.TimeoutException`) without taking a slot, which every verifier reports as `unverified`. Otherwise it only ever delays a read, so verdict semantics are unchanged.
- `agent_readback/report.py`, `dashboard.py` (one-file HTML page, everything escaped; `readback dashboard`), `cli.py`, `alerts.py` (`WebhookAlert` as an `on_verdict` callback; swallows every exception; signs the body with `X-Readback-Signature` using `READBACK_ALERT_KEY`, never the log key, so a receiver can't forge the log). FHIR paging refuses next links whose httpx-resolved URL leaves the client's origin (token leak). CLI flags keyless OKs as UNKEYED and never lets `dashboard -o` overwrite a log. Evals label replies that start with neither `DONE` nor `FAILED` as `unclear_reply` (not counted as claims); the LangGraph agent labels a DONE whose last write held after an earlier failed one `done_after_failed_write`. Logs are written with LF endings on every OS.
- `graphify-out/` — generated knowledge graph of this repo (`/graphify`), not part of the package. Refresh with `/graphify --update` after doc changes.
- `examples/healthcare/` — demo harness and test fixtures: `mock_fhir.py` (in-memory FHIR via `httpx.MockTransport`; `server.fault` in `ok|drop|wrong_time|wrong_practitioner|duplicate` — faults still return success; `server.down` simulates outage), `tools.py` (agent's write tools — intentionally never read back), `llm.py` (Anthropic / OpenAI-compatible chat completions / OpenAI Responses (reasoning + tools, chained via `previous_response_id`) / Scripted tool loops via raw httpx), `tasks.py` (Central-time requests plus an oracle for the scripted agent), `run_eval.py`, `langgraph_agent.py` (agent + `ToolNode` loop with `watched()` write tools; scripted agent node by default, `--provider anthropic|openai --model <id>` via the `[langgraph]` extra; reschedule/cancel claims look up the patient via the verifier's client).
Expand All @@ -40,5 +42,5 @@ python -m build # wheel + sdist into dist/
- All HTTP goes through an injected `httpx.Client`; tests swap in `httpx.MockTransport`. Keep new verifiers and providers injectable the same way.
- New verifier: implement `snapshot`/`check` per `core.Verifier`, name actions `<system>.<resource>.<verb>`, export from `verifiers/__init__.py`, update the README verifier table.
- The verifier must use credentials the agent doesn't hold; a shared write path makes the check meaningless.
- The README's "What is tested and what is not" and "Security model" tables are kept honest. Update them (and the test count, currently 128) when coverage or guarantees change.
- The README's "What is tested and what is not" and "Security model" tables are kept honest. Update them (and the test count, currently 162) when coverage or guarantees change.
- Security changes need a test that demonstrates the attack failing (see `test_keyed_log_detects_a_chain_forged_without_the_key`), not just the happy path.
Loading
Loading