Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
232b833
QA: agent-middleware gateway/migrations/
PetrefiedThunder Oct 8, 2026
b22fd2a
Merge main into metacode/qa5-am-gateway-migrations
PetrefiedThunder Oct 24, 2026
7a8b331
Fix legacy SQLite boolean defaults
PetrefiedThunder Oct 24, 2026
206364d
Test legacy SQLite boolean row repair
PetrefiedThunder Oct 24, 2026
d3726fc
Merge remote-tracking branch 'origin/main' into metacode/qa5-am-gatew…
PetrefiedThunder Oct 24, 2026
f992032
Chain SQLite boolean repair after API key usage migration
PetrefiedThunder Oct 24, 2026
5919ba1
Merge remote-tracking branch 'origin/main' into metacode/qa5-am-gatew…
PetrefiedThunder Oct 25, 2026
036356b
Merge remote-tracking branch 'origin/main' into metacode/qa5-am-gatew…
PetrefiedThunder Oct 25, 2026
89a5956
Chain SQLite boolean repair after approval gate migration
PetrefiedThunder Oct 25, 2026
89428ce
Merge remote-tracking branch 'origin/main' into metacode/qa5-am-gatew…
PetrefiedThunder Oct 25, 2026
874515d
Rechain SQLite boolean migration after API key usage events
PetrefiedThunder Oct 25, 2026
6b4c2f2
Merge remote-tracking branch 'origin/main' into hermes-tmp-61
PetrefiedThunder Oct 25, 2026
9020bf6
Merge remote-tracking branch 'origin/main' into hermes-tmp-61
PetrefiedThunder Oct 25, 2026
c96958b
feat(migrations): port agent-middleware-api 047-050 with the same rev…
PetrefiedThunder Oct 25, 2026
22fdca0
Merge port of api migrations 047-050; renumber SQLite boolean default…
PetrefiedThunder Oct 25, 2026
02ad942
Sign enforcement mode and gateway build into receipts (migration 052)
PetrefiedThunder Oct 25, 2026
f563483
fix(migrations): rls_bypass in env.py, boot check for reconcile columns
PetrefiedThunder Oct 25, 2026
e3bf41b
Merge #234 head f5634837 (review fixes)
PetrefiedThunder Oct 25, 2026
e705953
Merge #61 head e3bf41bc6ddbb245b8205b1329be6497a0462074
PetrefiedThunder Oct 25, 2026
29d6363
test: cover receipt 052 columns in migration proof
PetrefiedThunder Oct 26, 2026
830cf4d
docs: regenerate receipt provenance OpenAPI schema
PetrefiedThunder Oct 26, 2026
e6d5f99
fix(migrations): port TENANT_RLS_MODE setting; RLS for resolution tables
PetrefiedThunder Oct 26, 2026
40615d3
Merge #234 head e6d5f997 (TENANT_RLS_MODE, resolution-table RLS)
PetrefiedThunder Oct 26, 2026
8bc350a
Merge #61 (carries #234 e6d5f997)
PetrefiedThunder Oct 26, 2026
6d977e2
feat(migrations): add opt-in TENANT_RLS_MODE=enable and PG RLS proof
PetrefiedThunder Oct 26, 2026
6ea1f92
Merge remote-tracking branch 'origin/main' into fix/234-v2
PetrefiedThunder Oct 26, 2026
e62d99e
Revert "feat(migrations): add opt-in TENANT_RLS_MODE=enable and PG RL…
PetrefiedThunder Oct 26, 2026
ae9a810
Merge e62d99e2a into metacode/qa5-am-gateway-migrations
PetrefiedThunder Oct 26, 2026
2b820df
Merge ae9a81050 into hermes/receipt-mode-build
PetrefiedThunder Oct 26, 2026
c6124e4
Merge origin/main into hermes/receipt-mode-build
PetrefiedThunder Oct 26, 2026
63be05b
test(receipts): pin populated enforcement_mode and gateway_build vectors
PetrefiedThunder Oct 26, 2026
bf5c634
docs(spec): document enforcement_mode and gateway_build receipt members
PetrefiedThunder Oct 26, 2026
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ This repository starts with a fresh history. Releases are listed here once tagge
loading the calls file raises `ReplayError` naming the record.
- Replay: new `amw-replay --require-verified` flag exits 2 unless every
recorded receipt verified against `--recorded-keys`.
- Receipts: new optional signed fields `enforcement_mode` ("enforce" or
"permissive") and `gateway_build` (build commit). Each is signed only when set,
so older receipts still verify. Migration 052 adds the columns.
- Replay: whitespace-only recorded `approval_id` now raises `ReplayError` like the
empty string, and `amw-replay` writes `receipts.jsonl`, `summary.json`, and
`keys.json` atomically (temp file in the output dir, then rename), leaving no
Expand Down
4 changes: 4 additions & 0 deletions gateway/app/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,10 @@ class ReceiptModel(SQLModel, table=True):
# Signed only when present so receipts created before migration 032 keep
# verifying byte-for-byte.
reason_code: Optional[str] = Field(default=None, max_length=128)
# Provenance signed into receipts issued from 052 onward. NULL on legacy
# receipts, whose signatures do not cover these fields.
enforcement_mode: Optional[str] = Field(default=None, max_length=16)
gateway_build: Optional[str] = Field(default=None, max_length=64)
audit_event_id: Optional[str] = Field(
default=None,
max_length=50,
Expand Down
4 changes: 4 additions & 0 deletions gateway/app/schemas/trust.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,10 @@ class ReceiptResponse(ActionPermitFields):
credits_charged: Decimal
outcome: str
reason_code: str | None = None
# "enforce" when trust mode refuses unpermitted calls, else "permissive".
enforcement_mode: str | None = None
# Commit SHA of the gateway image that signed the receipt, when known.
gateway_build: str | None = None
audit_event_id: str | None
# Human approval that authorized this invoke, when the permit required one.
approval_id: str | None = None
Expand Down
24 changes: 24 additions & 0 deletions gateway/app/services/receipts.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.sql.elements import ColumnElement

from app.core.build_metadata import get_build_commit_sha
from app.core.config import DuplicateGuardMode, get_settings
from app.core.resilience import run_with_write_conflict_retry
from app.core.time import utc_now
Expand Down Expand Up @@ -80,6 +81,14 @@ def _action_binding(model: PermitModel | ReceiptModel) -> dict[str, Any]:
return ActionPermitFields.model_validate(values).model_dump(exclude_none=True)


def receipt_enforcement_mode() -> str | None:
"""The trust posture this process enforces, as signed into receipts."""
settings = get_settings()
if settings.TRUST_MODE_ENABLED and not settings.ALLOW_LEGACY_UNPERMITTED_MCP:
return "enforce"
return "permissive"


def receipt_model_to_response(model: ReceiptModel) -> ReceiptResponse:
return ReceiptResponse(
**_action_binding(model),
Expand All @@ -97,6 +106,8 @@ def receipt_model_to_response(model: ReceiptModel) -> ReceiptResponse:
credits_charged=model.credits_charged,
outcome=model.outcome,
reason_code=model.reason_code,
enforcement_mode=model.enforcement_mode,
gateway_build=model.gateway_build,
audit_event_id=model.audit_event_id,
approval_id=model.approval_id,
constraints_evaluated=_loads_dict(model.constraints_evaluated_json),
Expand Down Expand Up @@ -132,6 +143,11 @@ def _verification_payload(
}
if model.reason_code is not None:
payload["reason_code"] = model.reason_code
# Signed only when set, so receipts issued before 052 keep verifying.
if model.enforcement_mode is not None:
payload["enforcement_mode"] = model.enforcement_mode
if model.gateway_build is not None:
payload["gateway_build"] = model.gateway_build
if include_linkage and model.idempotency_record_id is not None:
payload["idempotency_record_id"] = model.idempotency_record_id
if include_linkage and model.dispatch_attempt_id is not None:
Expand Down Expand Up @@ -458,6 +474,12 @@ async def existing_response(
}
if reason_code is not None:
payload["reason_code"] = reason_code
enforcement_mode = receipt_enforcement_mode()
gateway_build = get_build_commit_sha()
if enforcement_mode is not None:
payload["enforcement_mode"] = enforcement_mode
if gateway_build is not None:
payload["gateway_build"] = gateway_build
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
# Keep historical receipt signatures valid: these additive fields are
# signed only on receipts that actually carry the new linkage.
if idempotency_record_id is not None:
Expand Down Expand Up @@ -512,6 +534,8 @@ def build_model() -> ReceiptModel:
credits_charged=credits_charged,
outcome=outcome,
reason_code=reason_code,
enforcement_mode=enforcement_mode,
gateway_build=gateway_build,
audit_event_id=audit_event_id,
approval_id=approval_id,
constraints_evaluated_json=json.dumps(constraints_evaluated)
Expand Down
22 changes: 22 additions & 0 deletions gateway/docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -10133,6 +10133,28 @@
],
"title": "Reason Code"
},
"enforcement_mode": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Enforcement Mode"
},
"gateway_build": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Gateway Build"
},
"audit_event_id": {
"anyOf": [
{
Expand Down
21 changes: 21 additions & 0 deletions gateway/docs/schema-052-rollout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Schema 052: receipt enforcement mode and gateway build

Migration `052_receipt_mode_build` revises `051_sqlite_boolean_defaults`. It
adds nullable `receipts.enforcement_mode` (`enforce` or `permissive`) and
`receipts.gateway_build` (the image commit SHA from
`app.core.build_metadata.get_build_commit_sha`, NULL when unknown). Receipts
issued after 052 sign both fields when set; existing receipts stay NULL and
keep verifying with their original signatures. No row is updated.

## Compatibility release

Production boot requires the database revision to match the packaged head, so
a 051-packaged image cannot restart after 052 is applied. Qualify a
052-capable image against a disposable PostgreSQL upgrade from 051 first.
These release checks have not been run against staging or production.

## Rollback boundary

Downgrade to 051 refuses while any receipt carries either field, because
dropping signed fields would make those receipts fail verification. Recover
with a 052-capable image and the database left at 052.
52 changes: 52 additions & 0 deletions gateway/migrations/versions/052_receipt_mode_build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Record the enforcement mode and gateway build on receipts.

Revision ID: 052_receipt_mode_build
Revises: 051_sqlite_boolean_defaults

Adds nullable ``receipts.enforcement_mode`` and ``receipts.gateway_build``.
Existing receipts stay NULL, and their signatures do not cover these fields,
so they keep verifying. Columns are added only when missing.
"""

import sqlalchemy as sa
from alembic import op

revision: str = "052_receipt_mode_build"
down_revision: str = "051_sqlite_boolean_defaults"
branch_labels = None
depends_on = None

COLUMNS = (("enforcement_mode", 16), ("gateway_build", 64))


def upgrade() -> None:
existing = {c["name"] for c in sa.inspect(op.get_bind()).get_columns("receipts")}
missing = [(name, size) for name, size in COLUMNS if name not in existing]
if not missing:
return
with op.batch_alter_table("receipts") as batch_op:
for name, size in missing:
batch_op.add_column(sa.Column(name, sa.String(length=size), nullable=True))


def downgrade() -> None:
# A receipt signed with these fields cannot verify once they are dropped,
# so refuse rather than silently invalidate signed evidence.
signed = (
op.get_bind()
.execute(
sa.text(
"SELECT COUNT(*) FROM receipts "
"WHERE enforcement_mode IS NOT NULL OR gateway_build IS NOT NULL"
)
)
.scalar_one()
)
if signed:
raise RuntimeError(
f"052 downgrade refused: {signed} receipt(s) carry signed "
"enforcement_mode/gateway_build values that 051 cannot store"
)
with op.batch_alter_table("receipts") as batch_op:
batch_op.drop_column("gateway_build")
batch_op.drop_column("enforcement_mode")
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"signature_b64_over_test_seed": "ij5D5zN7SmVmsdfpNdnRfcqKxefmpBkMaNl3uaQ9kzDVXsHYm8bpCTv4+uILG2nJaLk377ziq/Vgd/+elmY5Bw==",
"signing_input": "{\"alg\":\"Ed25519\",\"audit_event_id\":\"aud_golden_0001\",\"created_at\":\"2026-09-14T17:00:00+00:00\",\"credits_authorized\":\"2.5\",\"credits_charged\":\"2.5\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"enforce\",\"gateway_build\":\"0123456789abcdef0123456789abcdef01234567\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"e3d1cb8f6369020b87a3ba8b48c3108e335312f145b952ca69481e893f7be090\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0005\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}",
"signing_input_sha256": "12bbc80225eede4e0e9912adf5cf9e9639823c3cb7681723ffa3be2ded27567e"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"signature_b64_over_test_seed": "0yzqc74K4pSRk4GTbh84j9oT0p2x1PF5nql2o3nj4uogrUBEukMfd8WDMlBrNsSrsXFbugLlSKWcex5ONB8xCg==",
"signing_input": "{\"alg\":\"Ed25519\",\"audit_event_id\":\"aud_golden_0001\",\"created_at\":\"2026-09-14T17:00:00+00:00\",\"credits_authorized\":\"2.5\",\"credits_charged\":\"2.5\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"permissive\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"cf576b4daa8eb839999dc82d2c11bd21b37d522caefcbcc916d0dfee35947eff\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0006\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}",
"signing_input_sha256": "b6974c6a391007871b52f9b076aac25b8053ada1dadb2c2c8ca81a82b025fd9b"
}
7 changes: 5 additions & 2 deletions gateway/tests/test_action_migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"action_public_tool_id",
"action_upstream_binding_hash",
)
RECEIPT_PROVENANCE_FIELDS = ("enforcement_mode", "gateway_build")
ACTION_REVISION = "042_permit_action_binding"
SCRUB_REVISION = "041_scrub_content_owner_keys"
CONTENT_TABLES = ("content_pipelines", "content_campaigns")
Expand Down Expand Up @@ -230,7 +231,8 @@ def sql(statement):
{"version_num": head_revision}
]
for table, old in before.items():
assert sql(f"SELECT * FROM {table}")[0] == {**old, **dict.fromkeys(FIELDS)}
new_fields = FIELDS + (RECEIPT_PROVENANCE_FIELDS if table == "receipts" else ())
assert sql(f"SELECT * FROM {table}")[0] == {**old, **dict.fromkeys(new_fields)}
for table in CONTENT_TABLES:
assert sql(f"SELECT owner_key FROM {table} ORDER BY owner_key") == [
{"owner_key": ""},
Expand All @@ -247,7 +249,8 @@ def sql(statement):
result = migrate(url, "head")
assert result.returncode == 0, result.stderr
for table, old in before.items():
assert sql(f"SELECT * FROM {table}")[0] == {**old, **dict.fromkeys(FIELDS)}
new_fields = FIELDS + (RECEIPT_PROVENANCE_FIELDS if table == "receipts" else ())
assert sql(f"SELECT * FROM {table}")[0] == {**old, **dict.fromkeys(new_fields)}
assert sql(
"SELECT column_name FROM information_schema.columns "
f"WHERE table_schema='public' AND table_name='{table}' "
Expand Down
30 changes: 18 additions & 12 deletions gateway/tests/test_policy_replay.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,13 @@
#: human-approval rule below.
NO_APPROVAL_SUCCESSES = {
"success_action_v1.json",
"success_enforcement_build.json",
"success_legacy.json",
"success_linked.json",
"success_permissive.json",
}
# The corpus is every golden receipt; counts follow the fixture set.
GOLDEN_COUNT = len(list(GOLDEN_DIR.glob("*.json")))


def _recorded_keys():
Expand Down Expand Up @@ -147,7 +151,7 @@ def _audit(event: str, _args) -> None:

def test_replay_forwards_nothing_library(tmp_path, tripwire):
result = replay_calls(_calls(), load_policy_bundle(_approval_rule(tmp_path)))
assert len(result.receipts) == 6
assert len(result.receipts) == GOLDEN_COUNT
assert tripwire.calls == []
assert tripwire.socket_events == []

Expand All @@ -169,7 +173,7 @@ def test_replay_forwards_nothing_cli(tmp_path, tripwire, capsys):
assert tripwire.calls == []
assert tripwire.socket_events == []
lines = (tmp_path / "out" / "receipts.jsonl").read_text().splitlines()
assert len(lines) == 6
assert len(lines) == GOLDEN_COUNT


def test_network_is_sealed_during_replay():
Expand All @@ -188,7 +192,7 @@ def test_network_is_sealed_during_replay():
def test_one_signed_receipt_per_call_verifies(tmp_path):
calls = _calls()
result = replay_calls(calls, load_policy_bundle(_approval_rule(tmp_path)))
assert len(result.receipts) == len(calls) == 6
assert len(result.receipts) == len(calls) == GOLDEN_COUNT
assert sorted(_claims(r)["call_hash"] for r in result.receipts) == sorted(
c.call_hash for c in calls
)
Expand Down Expand Up @@ -307,8 +311,10 @@ def test_summary_counts_match_receipts(tmp_path):
json.loads(line) for line in (out / "receipts.jsonl").read_text().splitlines()
]
changes = [_claims(r)["change"] for r in receipts]
assert summary["total"] == len(receipts) == 6
assert summary["allow_to_deny"] == changes.count("allow_to_deny") == 5
assert summary["total"] == len(receipts) == GOLDEN_COUNT
assert (
summary["allow_to_deny"] == changes.count("allow_to_deny") == GOLDEN_COUNT - 1
)
assert summary["deny_to_allow"] == changes.count("deny_to_allow") == 0
assert summary["unchanged"] == changes.count("unchanged") == 1
assert (
Expand Down Expand Up @@ -691,7 +697,7 @@ def test_replay_receipt_marks_verified_recordings(tmp_path):
result = replay_calls(calls, load_policy_bundle(_approval_rule(tmp_path)))
assert [_claims(r)["recorded_signature_verified"] for r in result.receipts] == [
True
] * 6
] * GOLDEN_COUNT


def test_replay_receipt_marks_unverified_recordings(tmp_path):
Expand All @@ -700,7 +706,7 @@ def test_replay_receipt_marks_unverified_recordings(tmp_path):
result = replay_calls(calls, load_policy_bundle(_approval_rule(tmp_path)))
assert [_claims(r)["recorded_signature_verified"] for r in result.receipts] == [
False
] * 6
] * GOLDEN_COUNT


def test_recorded_envelope_mismatch_raises(tmp_path):
Expand Down Expand Up @@ -752,7 +758,7 @@ def test_replay_daily_spend_limit_without_usage_denies(tmp_path):
result = replay_calls(
_calls(), load_policy_bundle(_bundle(tmp_path, {"daily_spend_limit": "100.00"}))
)
assert len(result.receipts) == 6
assert len(result.receipts) == GOLDEN_COUNT
for receipt in result.receipts:
claims = _claims(receipt)
if claims["old_decision"] == "deny":
Expand Down Expand Up @@ -1027,7 +1033,7 @@ def _strip_verification(path, **kwargs):
)
assert code == 2
captured = capsys.readouterr()
assert "6 unverified" in captured.err
assert f"{GOLDEN_COUNT} unverified" in captured.err
assert captured.out == ""
assert not (out / "summary.json").exists()
assert not (out / "receipts.jsonl").exists()
Expand All @@ -1050,7 +1056,7 @@ def test_cli_require_verified_passes_when_all_verified(tmp_path, capsys):
)
assert code == 0, capsys.readouterr().err
summary = json.loads((out / "summary.json").read_text())
assert summary["total"] == 6
assert summary["total"] == GOLDEN_COUNT


# --- 24. CLI outputs are written atomically -----------------------------------
Expand Down Expand Up @@ -1195,9 +1201,9 @@ def test_cli_overwrite_prepopulated_out_writes_new_contents(tmp_path, capsys):
for name, content in old.items():
assert (out / name).read_text() != content
summary = json.loads((out / "summary.json").read_text())
assert summary["total"] == 6
assert summary["total"] == GOLDEN_COUNT
receipts = (out / "receipts.jsonl").read_text().splitlines()
assert len(receipts) == 6
assert len(receipts) == GOLDEN_COUNT


def test_cli_backup_link_failure_falls_back_to_copy(tmp_path, capsys, monkeypatch):
Expand Down
Loading
Loading