From 7339faa83f6411d638e91eaa9515d2415b640b8b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:40:14 -0500 Subject: [PATCH 01/10] feat(types): counterparty confirmations in record/run/v1, with a committed reason --- packages/flow/docs/RECEIPTS.md | 12 ++ packages/types/openadapt_types/receipt.py | 163 +++++++++++++++++- packages/types/tests/test_receipt_vectors.py | 39 +++++ .../tests/vectors/record-run-v1/README.md | 26 +++ .../confirmation-acknowledged.json | 52 ++++++ .../confirmation-public-not-allowed.json | 31 ++++ .../confirmation-public-redaction.json | 35 ++++ .../confirmation-reason-inconsistent.json | 43 +++++ .../confirmation-reason-no-answer.json | 57 ++++++ .../confirmation-recorded-as-intended.json | 52 ++++++ .../confirmation-recorded-differently.json | 52 ++++++ .../record-run-v1/confirmation-sent.json | 52 ++++++ .../record-run-v1/confirmation-tampered.json | 21 +++ .../tests/vectors/record-run-v1/generate.py | 128 ++++++++++++++ 14 files changed, 761 insertions(+), 2 deletions(-) create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-acknowledged.json create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-public-not-allowed.json create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-public-redaction.json create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-reason-inconsistent.json create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-reason-no-answer.json create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-recorded-as-intended.json create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-recorded-differently.json create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-sent.json create mode 100644 packages/types/tests/vectors/record-run-v1/confirmation-tampered.json diff --git a/packages/flow/docs/RECEIPTS.md b/packages/flow/docs/RECEIPTS.md index 69a498094b..21607b5d65 100644 --- a/packages/flow/docs/RECEIPTS.md +++ b/packages/flow/docs/RECEIPTS.md @@ -36,6 +36,18 @@ URLs or page text.** Evidence files, screenshots included, appear only by SHA-256 digest. A verifier refuses a receipt or card that carries an image, a base64 blob, a URL or long text (`embedded_content`). +A receipt may also carry **counterparty confirmations**: evidence read from +another party's system about a handoff, such as a referral a portal later +shows as recorded. Each confirmation states the kind of system, how it was +read (a portal read-back, an API, or an acknowledgment message), its state +(`sent`, `acknowledged`, `recorded_as_intended` or `recorded_differently`) and +its own strength. Who the other party is, when it was observed, which fields +it showed and any reason are salted commitments, never shown on a public card. +The verifier prints each one on its own line, for example "Confirmed in the +other party's system at 2026-11-20T23:41:07Z". That line never merges with or +upgrades the signer line: "Signed by this computer" still means only that this +computer signed the statement. + ## Who signed it Each signature names a key id. The verifier's pinned key registry maps that diff --git a/packages/types/openadapt_types/receipt.py b/packages/types/openadapt_types/receipt.py index 9728d29295..9531f90329 100644 --- a/packages/types/openadapt_types/receipt.py +++ b/packages/types/openadapt_types/receipt.py @@ -192,6 +192,60 @@ class Disclosure(_Closed): commitments: dict[StrictStr, StrictStr] = Field(max_length=16) +SystemKind = Literal[ + "ehr", "payer_portal", "bank", "erp", "crm", "government_portal", "email", "other" +] +ReadMethod = Literal["portal_read_back", "api", "acknowledgment_message"] +ConfirmationState = Literal[ + "sent", "acknowledged", "recorded_as_intended", "recorded_differently" +] +ConfirmationStrength = Literal["read_back", "acknowledgment", "none"] +#: Read methods that look at the other party's own system of record. +INDEPENDENT_READS: Final = ("portal_read_back", "api") +_CONFIRMATION_KEY = re.compile(r"counterparty|observed_at|reason|field\.[0-9]{1,2}") +ConfirmationReason = Literal[ + "rejected_by_counterparty", + "conflicting_report", + "ambiguous_key", + "receiver_unreachable", + "not_found", + "no_answer_by_deadline", +] +#: Which reasons each state may carry (no reason is always allowed). The +#: reason is committed, so it shows only where the private openings are read. +REASONS_FOR_STATE: Final[Mapping[str, frozenset[str]]] = { + "sent": frozenset( + { + "rejected_by_counterparty", + "ambiguous_key", + "receiver_unreachable", + "not_found", + "no_answer_by_deadline", + } + ), + "acknowledged": frozenset({"ambiguous_key", "not_found", "no_answer_by_deadline"}), + "recorded_as_intended": frozenset({"conflicting_report"}), + "recorded_differently": frozenset({"conflicting_report"}), +} + + +class Confirmation(_Closed): + """Evidence read from another party's system about one handoff. + + Everything that could identify the other party, the time or the fields + is a salted commitment; the openings stay in the private sidecar. + """ + + kind: Literal["counterparty_confirmation"] + for_step: Optional[Count] = Field(default=None, ge=0, le=10_000) + system_kind: SystemKind + read_method: ReadMethod + state: ConfirmationState + strength: ConfirmationStrength + differing_count: Count = Field(ge=0, le=64) + commitments: dict[StrictStr, StrictStr] = Field(min_length=2, max_length=34) + + class RunPredicateV1(_Closed): program: Program started_hour: StrictStr = Field(pattern=_HOUR) @@ -202,6 +256,9 @@ class RunPredicateV1(_Closed): checks: Checks model_calls: Count = Field(ge=0, le=MAX_COUNT) disclosure: Disclosure + #: Counterparty confirmations; omitted from the payload when empty, so a + #: receipt without one is byte-identical to one made before they existed. + confirmations: list[Confirmation] = Field(default_factory=list, max_length=64) class RunStatementV1(_Closed): @@ -211,7 +268,36 @@ class RunStatementV1(_Closed): predicate: RunPredicateV1 def wire(self) -> dict[str, Any]: - return self.model_dump(mode="json", by_alias=True) + out = self.model_dump(mode="json", by_alias=True) + if not out["predicate"]["confirmations"]: + del out["predicate"]["confirmations"] + return out + + +def _check_confirmation(c: Confirmation, steps: set[int]) -> Optional[str]: + if c.for_step is not None and c.for_step not in steps: + return "a confirmation names a step with no line" + if c.state == "sent" and c.strength != "none": + return "a sent handoff has no confirmation strength" + if c.state == "acknowledged" and c.strength != "acknowledgment": + return "an acknowledgment has acknowledgment strength" + if c.state.startswith("recorded_") and ( + c.read_method not in INDEPENDENT_READS or c.strength != "read_back" + ): + return "only a portal or API read-back can say how the record was recorded" + if (c.state == "recorded_differently") != (c.differing_count > 0): + return "differing_count disagrees with the state" + if not {"counterparty", "observed_at"} <= set(c.commitments): + return "a confirmation commits to its counterparty and observed_at" + for key, value in c.commitments.items(): + if not _CONFIRMATION_KEY.fullmatch(key) or not re.fullmatch( + _SHA256_HEX[1:-1], value + ): + return f"confirmation commitment {key!r} is not a known field" + fields = sum(1 for key in c.commitments if key.startswith("field.")) + if c.differing_count > fields: + return "more differing fields than observed fields" + return None def _check_consistent(statement: RunStatementV1) -> Optional[str]: @@ -247,6 +333,10 @@ def _check_consistent(statement: RunStatementV1) -> Optional[str]: steps = [line.step for line in p.lines] if steps != sorted(set(steps)): return "lines are not in step order, or repeat a step" + for c in p.confirmations: + problem = _check_confirmation(c, set(steps)) + if problem: + return problem return None @@ -321,7 +411,35 @@ def make_openings( return commitments, openings +_CONFIRMATION_PATH = re.compile( + r"confirmations\.([0-9]{1,2})\.(counterparty|observed_at|reason|field\.[0-9]{1,2})" +) +_CONFIRMATION_VALUES: Final[Mapping[str, re.Pattern[str]]] = { + "counterparty": re.compile( + r"(ehr|payer_portal|bank|erp|crm|government_portal|email|other):cp-[a-f0-9]{16}" + ), + "observed_at": _ISO_SECONDS, + "reason": re.compile( + r"rejected_by_counterparty|conflicting_report|ambiguous_key" + r"|receiver_unreachable|not_found|no_answer_by_deadline" + ), + "field": re.compile(r"[a-z][a-z0-9_]{0,31}:[a-f0-9]{64}(:differs)?"), +} + + +def confirmation_path(index: int, key: str) -> str: + return f"confirmations.{index}.{key}" + + def _value_problem(path: str, value: Any) -> Optional[str]: + found = _CONFIRMATION_PATH.fullmatch(path) + if found: + if not isinstance(value, str): + return f"{path!r} is not a string" + kind = found.group(2).split(".")[0] + if not _CONFIRMATION_VALUES[kind].fullmatch(value): + return f"{path!r} does not match its field's pattern" + return None pattern = DISCLOSURE_FIELDS.get(path) if pattern is None: return f"{path!r} is not a disclosure field" @@ -575,6 +693,13 @@ class ReceiptVerification: disclosed: Mapping[str, str] = field(default_factory=dict) #: True when a full private openings file was checked. private: bool = False + #: One line per counterparty confirmation. Never merged with, and never + #: upgrading, ``signer_lines``. + confirmation_lines: tuple[str, ...] = () + #: Per confirmation: read from the other party's own system (portal or + #: API). Decided only from the read method; the signer's role comes + #: from the pinned registry. + independent: tuple[bool, ...] = () _REFUSAL_LINES: Final[Mapping[str, str]] = { @@ -731,7 +856,10 @@ def verify_receipt( problem = _check_consistent(statement) if problem: return _refuse("inconsistent", problem) - commitments = statement.predicate.disclosure.commitments + commitments = dict(statement.predicate.disclosure.commitments) + for index, c in enumerate(statement.predicate.confirmations): + for key, value in c.commitments.items(): + commitments[confirmation_path(index, key)] = value disclosed: dict[str, str] = {} private = False if card_openings is not None: @@ -755,6 +883,12 @@ def verify_receipt( return result disclosed = result private = True + for index, c in enumerate(statement.predicate.confirmations): + reason = disclosed.get(confirmation_path(index, "reason")) + if reason is not None and reason not in REASONS_FOR_STATE[c.state]: + return _refuse( + "inconsistent", f"a {c.state} confirmation can't have reason {reason}" + ) ordered = sorted( checks, key=lambda c: _ROLE_ORDER.index(c.role) if c.role in _ROLE_ORDER else -1, @@ -763,8 +897,14 @@ def verify_receipt( for c in ordered: if c.line not in lines: lines.append(c.line) + confirmations = statement.predicate.confirmations return ReceiptVerification( True, + confirmation_lines=tuple( + confirmation_line(c, disclosed.get(confirmation_path(i, "observed_at"))) + for i, c in enumerate(confirmations) + ), + independent=tuple(c.read_method in INDEPENDENT_READS for c in confirmations), signers=tuple(ordered), signer_lines=tuple(lines), demo=demo, @@ -775,6 +915,22 @@ def verify_receipt( ) +def confirmation_line(c: Confirmation, observed_at: Optional[str] = None) -> str: + """The verifier's line for one confirmation, as every verifier prints it.""" + at = f" at {observed_at}" if observed_at else "" + if c.state == "recorded_as_intended": + return f"Confirmed in the other party's system{at}" + if c.state == "recorded_differently": + noun = "field differs" if c.differing_count == 1 else "fields differ" + return ( + f"Recorded differently in the other party's system{at}: " + f"{c.differing_count} {noun}" + ) + if c.state == "acknowledged": + return f"Acknowledged by the other party{at}" + return f"Sent to the other party{at}, not confirmed" + + def _check_openings( openings: Any, commitments: Mapping[str, str], @@ -846,6 +1002,9 @@ def program_id(name: Any, version_sha256: str) -> str: "add_signature", "canonical_json", "commitment", + "Confirmation", + "confirmation_line", + "confirmation_path", "find_embedded_content", "is_receipt_card", "is_receipt_envelope", diff --git a/packages/types/tests/test_receipt_vectors.py b/packages/types/tests/test_receipt_vectors.py index 2a5a880042..ca74e9d7cd 100644 --- a/packages/types/tests/test_receipt_vectors.py +++ b/packages/types/tests/test_receipt_vectors.py @@ -29,6 +29,13 @@ def test_the_vector_set_is_complete(): "cloud-countersign", "embedded-image-in-card", "embedded-image-in-record", + "confirmation-recorded-as-intended", + "confirmation-recorded-differently", + "confirmation-acknowledged", + "confirmation-sent", + "confirmation-tampered", + "confirmation-public-redaction", + "confirmation-reason-no-answer", ): assert required in NAMES @@ -45,6 +52,10 @@ def test_vector(name): assert result.outcome == expected["outcome"] assert result.demo is expected["demo"] assert dict(result.disclosed) == expected["disclosed"] + assert list(result.confirmation_lines) == expected.get("confirmation_lines", []) + assert list(result.independent) == expected.get("independent", []) + # A confirmation line never joins or upgrades the signer lines. + assert not set(result.confirmation_lines) & set(result.signer_lines) else: assert result.outcome is None @@ -99,3 +110,31 @@ def test_allow_list_fields_are_disclosure_fields(): assert set(allowed) <= set(r.DISCLOSURE_FIELDS) for source in allowed.values(): assert source.split(":")[0] in ("public-card/v1", "public-evidence-receipt/v1") + + +def test_a_statement_without_confirmations_is_byte_identical(): + vector = json.loads((VECTORS / "valid.json").read_text()) + import base64 + + payload = base64.b64decode(vector["document"]["payload"]) + assert b"confirmations" not in payload + assert r.statement_payload(json.loads(payload)) == payload + + +@pytest.mark.parametrize( + "change", + [ + {"state": "recorded_as_intended", "read_method": "acknowledgment_message"}, + {"state": "sent", "strength": "read_back"}, + {"state": "recorded_differently", "differing_count": 0}, + {"for_step": 3}, + ], +) +def test_inconsistent_confirmations_are_refused(change): + vector = json.loads((VECTORS / "confirmation-recorded-as-intended.json").read_text()) + import base64 + + statement = json.loads(base64.b64decode(vector["document"]["payload"])) + statement["predicate"]["confirmations"][0].update(change) + with pytest.raises(ValueError): + r.statement_payload(statement) diff --git a/packages/types/tests/vectors/record-run-v1/README.md b/packages/types/tests/vectors/record-run-v1/README.md index 26b3f2b13d..da02302b68 100644 --- a/packages/types/tests/vectors/record-run-v1/README.md +++ b/packages/types/tests/vectors/record-run-v1/README.md @@ -55,6 +55,32 @@ not secrets. A refusal shows one "Not verified: ..." line; an unknown key shows "Not verified: unknown signer". 7. **Outcome.** Copied from the statement, never upgraded. +8. **Counterparty confirmations.** `predicate.confirmations[]` is optional and + omitted when empty. Each item is closed: `kind` (`counterparty_confirmation`), + `for_step` (null or the step of a line), `system_kind`, `read_method` + (`portal_read_back`, `api`, `acknowledgment_message`), `state` (`sent`, + `acknowledged`, `recorded_as_intended`, `recorded_differently`), `strength` + (`read_back`, `acknowledgment`, `none`), `differing_count` and `commitments` + (keys `counterparty`, `observed_at`, optional `reason`, `field.`). Rules: + `sent` has strength `none`; `acknowledged` has `acknowledgment`; both + `recorded_*` states need a portal or API read and `read_back`; + `differing_count` is at least 1 exactly for `recorded_differently`. Openings + use paths `confirmations..`, live only in the private sidecar, and + are never on the public allow-list. Values: counterparty + `:cp-<16 hex>`; `observed_at` ISO seconds with Z; a field + `:` with `:differs` when it differs; `reason` one of + `rejected_by_counterparty`, `conflicting_report`, `ambiguous_key`, + `receiver_unreachable`, `not_found`, `no_answer_by_deadline`. When the reason + is opened it must suit the state: `sent` takes any but `conflicting_report`; + `acknowledged` takes `ambiguous_key`, `not_found` or + `no_answer_by_deadline`; both `recorded_*` states take only + `conflicting_report` (otherwise `inconsistent`). + Each confirmation prints its own line in `confirmation_lines`, never in + `signer_lines`: "Confirmed in the other party's system[ at