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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ graphify-out/
.test-tmp*/
.test-python*/
.venv*/
.claude-flow/
.pytest-live-assessment*/
19 changes: 17 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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

## Unreleased
## 0.3.1 — 2026-11-22

### Fixed

Expand All @@ -11,13 +11,28 @@ All notable changes to `agent-readback`. Dates are UTC.
read as if it were complete, so a duplicate booking or a double refund on an
unread page could pass. Both are now `unverified`.
- A timestamp with no UTC form (for example year 1 at `+01:00`) raised
`OverflowError`; it is now left as is and shows as a mismatch.
`OverflowError`; it is now compared as written, so it matches only an identical
string; the same instant written another way is a `wrong_value`.
- A malformed FHIR or Stripe response (for example a list where an object is
expected, a string entry, or a non-string id or reference) made the verifier
raise `AttributeError` or `TypeError` out of `watch()`, breaking the agent's
call. Responses are now shape-checked where they are parsed and anything
malformed is `unverified`. A Stripe refund page that repeats now stops after
the second request instead of after `MAX_PAGES`.
- A broken read could still be a false `failed`:
- A Stripe 200 response with no `data` list or no `has_more` (an error body,
a proxy page, `{}`) was read as "no refunds", so a real refund was
`failed`. Both fields are now required; otherwise the result is `unverified`.
- A FHIR 200 response that is not a Bundle (for example an
OperationOutcome) was read as an empty search. A search entry that is not
an Appointment, or a read by id that returns another resource type, was
counted as an appointment. These are now `unverified`. Entries with
`search.mode` `include` or `outcome` are skipped instead of counted.
- An Appointment with no id was keyed by its position in the read, so an
unchanged one could look new (a false `extra_effect`) or hide a new
duplicate. A missing or empty id is now `unverified`.
- A participant `actor` that was `[]`, `""` or another falsy non-object was
treated as absent, giving a `wrong_value` `failed`. It is now `unverified`.

### Documentation

Expand Down
6 changes: 3 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.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`.
Readback (`agent-readback`, v0.3.1): 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 @@ -29,7 +29,7 @@ python -m pip install -e ".[security]" && python -m bandit -r agent_readback exa
## 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/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; zoneless times and instants with no UTC form are left unnormalized and compared as written (only identical text matches). 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.
Expand All @@ -42,5 +42,5 @@ python -m pip install -e ".[security]" && python -m bandit -r agent_readback exa
- 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 184) 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 199, of which 1 skips on Windows without symlink privileges) 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.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ flowchart LR
Install (Python 3.10+; the only runtime dependency is `httpx`):

```bash
pip install "agent-readback @ git+https://github.com/dhonitheja/agent-readback@v0.3.0"
pip install "agent-readback @ git+https://github.com/dhonitheja/agent-readback@v0.3.1"
```

Wrap the call your agent makes. Readback snapshots before it, reads back after
Expand Down Expand Up @@ -307,7 +307,7 @@ restricted key with `refunds: read`, a database role with `SELECT` only).
| Server-supplied paging link sends the verifier's token elsewhere | Each FHIR next link is resolved the way httpx will send it (so `//host/x` and similar forms count) and must stay on the client's scheme, host and port; anything else is `unverified` and is never requested |
| Evidence log overwritten by the dashboard | `readback dashboard` refuses an output path that is the log itself or any existing `.jsonl` |
| Hostile or broken server pages forever | FHIR and Stripe reads are page-capped; the result is `unverified`, not a hang |
| Malformed or incomplete server response | The FHIR and Stripe fields the verifiers read are shape-checked where they are parsed (objects, lists, string ids, references and next links); a wrong shape is `unverified`. A read that cannot be completed, such as a FHIR next link with no usable URL or a Stripe page that promises more but is empty, is `unverified`, never `verified`. A Stripe page that repeats stops after the second request; a timestamp with no UTC form shows as a mismatch |
| Malformed or incomplete server response | The FHIR and Stripe fields the verifiers read are shape-checked where they are parsed (objects, lists, string ids, references and next links); a wrong shape is `unverified`. A read that cannot be completed, such as a FHIR next link with no usable URL or a Stripe page that promises more but is empty, is `unverified`, never `verified`. A Stripe page that repeats stops after the second request. A FHIR search must be a `Bundle` of Appointments that each have an id (`include` and `outcome` entries are skipped), and a Stripe page must carry `data` and `has_more`; anything else is `unverified`. A timestamp with no UTC form is compared as written |
| SQL injection via claim or config | Table and column names come from your code and are pattern-checked; the `placeholder` must be a DB-API paramstyle (`?`, `%s`, `:name`, `:1`, `$1`); values are always bound parameters |
| Verifier overloading the system of record | Opt-in `limit_reads(..., RateLimit(...))` caps every read; it only delays reads, and with `max_wait` an over-long wait is `unverified`, never `failed` (see [Rate limiting the verifier's reads](#rate-limiting-the-verifiers-reads)) |
| Unreadable system of record | `unverified`, never `verified` and never `failed` |
Expand Down Expand Up @@ -344,8 +344,8 @@ external security or compliance review has been done.

## What is tested and what is not

Version 0.3.0 plus unreleased fixes. All 184 offline tests pass with the optional test dependencies
installed. A separate public HAPI FHIR R4 sandbox run verified 10 scripted
Version 0.3.1. The suite has 199 offline tests; with the optional test dependencies
installed, 198 pass on Windows and the symlink test is skipped there without symlink privileges; elsewhere it runs too. A separate public HAPI FHIR R4 sandbox run verified 10 scripted
operations (6 bookings, 1 reschedule, 3 cancellations); this is a
compatibility smoke test, not production validation. A Stripe test-mode run
produced the expected verdict for all four refund scenarios, using a separate
Expand Down
2 changes: 1 addition & 1 deletion agent_readback/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .evidence import EvidenceLog, FileAnchor
from .ratelimit import RateLimit, RateLimitTimeout, limit_reads

__version__ = "0.3.0"
__version__ = "0.3.1"
__all__ = [
"Claim",
"EvidenceLog",
Expand Down
23 changes: 16 additions & 7 deletions agent_readback/verifiers/fhir.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ def normalize_instant(value: Any) -> Any:
except ValueError:
return value
if parsed.tzinfo is None:
return value # a time with no zone is ambiguous; leave it so it shows as a mismatch
return value # a time with no zone is ambiguous; compared as written: it matches only identical text
try:
return parsed.astimezone(timezone.utc).isoformat()
except OverflowError:
return value # e.g. year 1 at +01:00 has no UTC form; leave it so it shows as a mismatch
return value # e.g. year 1 at +01:00 has no UTC form; compared as written: it matches only identical text


def _object(value: Any, what: str) -> dict[str, Any]:
Expand All @@ -56,8 +56,11 @@ def _array(value: Any, what: str) -> list[Any]:
def flatten_appointment(resource: dict[str, Any]) -> dict[str, Any]:
"""Reduce a FHIR Appointment to the flat fields a claim can assert on."""
resource = _object(resource, "Appointment")
if not isinstance(resource.get("id"), (str, type(None))):
raise ValueError("malformed FHIR response: Appointment.id is not a string")
if resource.get("resourceType") != "Appointment": # e.g. an OperationOutcome sent with HTTP 200
raise ValueError("malformed FHIR response: resource is not an Appointment")
if not isinstance(resource.get("id"), str) or not resource["id"].strip():
# A stored resource always has an id; keying by position would let an old entry look new.
raise ValueError("malformed FHIR response: Appointment.id is missing or not a string")
flat: dict[str, Any] = {
"id": resource.get("id"),
"status": resource.get("status"),
Expand All @@ -67,7 +70,8 @@ def flatten_appointment(resource: dict[str, Any]) -> dict[str, Any]:
"practitioner": None,
}
for participant in _array(resource.get("participant", []), "Appointment.participant"):
actor = _object(_object(participant, "participant").get("actor") or {}, "participant.actor")
actor = _object(participant, "participant").get("actor")
actor = _object({} if actor is None else actor, "participant.actor") # [] or "" is malformed, not absent
reference = actor.get("reference", "")
if not isinstance(reference, str):
raise ValueError("malformed FHIR response: actor.reference is not a string")
Expand Down Expand Up @@ -97,9 +101,14 @@ def _appointments(self, patient: str) -> dict[str, dict[str, Any]]:
response = self.client.get(url, params=params, headers={"Cache-Control": "no-cache"})
response.raise_for_status()
bundle = _object(response.json(), "search Bundle")
if bundle.get("resourceType") != "Bundle": # e.g. an OperationOutcome sent with HTTP 200
raise ValueError("malformed FHIR response: search result is not a Bundle")
for entry in _array(bundle.get("entry", []), "Bundle.entry"):
flat = flatten_appointment(_object(entry, "Bundle.entry item")["resource"])
found[flat["id"] or f"<no-id>#{len(found)}"] = flat # keep id-less entries distinct
entry = _object(entry, "Bundle.entry item")
if _object(entry.get("search", {}), "Bundle.entry.search").get("mode") in ("include", "outcome"):
continue # _include'd resources and server warnings are not search matches
flat = flatten_appointment(entry["resource"])
found[flat["id"]] = flat
links = [_object(link, "Bundle.link item") for link in _array(bundle.get("link", []), "Bundle.link")]
nexts = [link for link in links if link.get("relation") == "next"]
url = nexts[0].get("url") if nexts else None
Expand Down
3 changes: 2 additions & 1 deletion agent_readback/verifiers/stripe.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ def _refunds(self, payment_intent: str) -> dict[str, dict[str, Any]]:
page = response.json()
if not isinstance(page, dict):
raise ValueError("malformed Stripe response: refund page is not an object")
items, has_more = page.get("data", []), page.get("has_more", False)
# No default for data or has_more: an error body or {} must not read as "no refunds" (a false FAILED).
items, has_more = page.get("data"), page.get("has_more")
if not isinstance(items, list) or not isinstance(has_more, bool):
raise ValueError("malformed Stripe response: data is not a list or has_more is not a boolean")
for item in items:
Expand Down
2 changes: 2 additions & 0 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,5 @@ infrastructure from the maintainer. Step 12 needs outside reviewers.
OpenAI models, `tzdata` on Windows.
- Verified locally (2026-11-22, 0.3.0 plus unreleased fixes): 184 tests pass on MCP 1.30 and on MCP 2.3, both with
LangGraph 1.2 (1 symlink test skips on Windows without symlink privileges).
- Verified locally (2026-11-22, 0.3.1): 198 tests pass, 1 symlink test skips, on Windows with MCP 1.30 and LangGraph 1.2.
The 0.3.0 line above predates the 0.3.1 fixes; MCP 2.3 has not been re-run on 0.3.1 locally (CI covers both).
41 changes: 41 additions & 0 deletions examples/healthcare/mock_booking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Run one synthetic booking for a local agent and report the readback verdict."""

import argparse

from agent_readback import Claim, Status, watch
from agent_readback.verifiers import FhirAppointmentVerifier

from .mock_fhir import FAULTS, MockFhirServer
from .tasks import VISIT, seed_people, slot, utc
from .tools import make_tools


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--scenario", choices=(*FAULTS, "unavailable"), default="ok")
args = parser.parse_args()
server = MockFhirServer()
with server.client() as writer, server.client() as reader:
patients, practitioners = seed_people(writer, patients=1, practitioners=1)
start = slot(0)
booking = {
"patient": patients[0], "practitioner": practitioners[0],
"start": utc(start), "end": utc(start + VISIT),
}
claim = Claim("fhir.appointment.create", "", {**booking, "status": "booked"})
server.fault = "ok" if args.scenario == "unavailable" else args.scenario
with watch(FhirAppointmentVerifier(reader), claim) as check:
make_tools(writer)["book_appointment"](**booking)
server.down = args.scenario == "unavailable"
if check.verdict is None: # not assert: python -O strips it
raise SystemExit("unverified: no verdict was produced. Review required.")
messages = {
Status.VERIFIED: f"Synthetic appointment booked for {booking['start']}.",
Status.FAILED: "The appointment record differs from the request. Review required.",
Status.UNVERIFIED: "The appointment could not be verified. Review required.",
}
print(f"{check.verdict.status.value}: {messages[check.verdict.status]}")


if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "agent-readback"
version = "0.3.0"
version = "0.3.1"
description = "Readback: check what an AI agent says it did against the system of record."
readme = "README.md"
requires-python = ">=3.10"
Expand Down
Loading
Loading