From ae23635149f0ef8ba60f59384c87366c7f980d14 Mon Sep 17 00:00:00 2001
From: Waleed Qureshi
Date: Wed, 25 Nov 2026 13:06:14 +0500
Subject: [PATCH] Emit APE v0.2 and release 0.7.0
Validation accepts v0.1 and v0.2 (agent.reported included) and refuses v0.2
fields in a 0.1 event; the signature header follows the event version. Events
use 0.2 only when they carry a v0.2 field. Unknown owners are sent as type
unknown (the owner_type label stopgap is gone). The x402 server side sets
perspective payee and attribution_gaps; the client side sets payer. Stripe
sends unknown for a missing owner type. New emit_report and instruction
normalise. Version 0.7.0.
Refs halvorAI/halvorai-app#99, #100, #109.
Co-Authored-By: Claude Sonnet 5.5
---
CHANGELOG.md | 17 +-
README.md | 5 +-
halvorai_ingest/client.py | 76 +++++---
halvorai_ingest/hash.py | 11 ++
halvorai_ingest/sign.py | 12 +-
halvorai_ingest/stripe/map.py | 19 +-
halvorai_ingest/validate.py | 170 +++++++++++++++++-
halvorai_ingest/x402/map.py | 38 ++--
pyproject.toml | 2 +-
.../ape-v0.2/agent-reported.v0.2.json | 36 ++++
.../stablecoin-settled-payer-side.v0.2.json | 114 ++++++++++++
.../x402-settled-payee-observed.v0.2.json | 107 +++++++++++
tests/fixtures/stripe/expected.json | 16 +-
tests/test_ape_v02.py | 80 +++++++++
tests/test_client.py | 62 +++++--
tests/test_stripe.py | 5 +-
tests/test_x402.py | 33 ++++
uv.lock | 2 +-
18 files changed, 720 insertions(+), 85 deletions(-)
create mode 100644 tests/fixtures/ape-v0.2/agent-reported.v0.2.json
create mode 100644 tests/fixtures/ape-v0.2/stablecoin-settled-payer-side.v0.2.json
create mode 100644 tests/fixtures/ape-v0.2/x402-settled-payee-observed.v0.2.json
create mode 100644 tests/test_ape_v02.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11122e5..8f341f9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,12 +1,25 @@
# Changelog
-## Unreleased
+## 0.7.0 (2026-11-25)
+
+Needs a HalvorAI API that accepts APE v0.2. Events that use no v0.2 field are still sent as v0.1.
+
+### Added
+
+- APE v0.2 support. An event is sent as `0.2` only when it uses a v0.2 field, and the signature header follows. Validation accepts v0.1 and v0.2 and refuses v0.2 fields in a `0.1` event.
+- `halvor.emit_report(instruction=..., report=...)` records what the agent told its owner about an instruction (`agent.reported`). The message is hashed locally and never sent. HalvorAI compares the report with the payments made under that instruction.
+- v0.2 fields pass through `emit`: `payment.payer_amount`, `payment.fees`, `payment.checkout_digest`, `payment.intermediary`, `delivery`, `attribution_gaps`, `source.perspective` and `payee.receipt_key`.
+- `"normalise": True` on an instruction given as `text` adds a `ws-lower-v1` hash, so two runs of one task that differ only in a local port or spacing match.
+- x402: the server side sets `source.perspective: "payee"`, and without an agent context lists what it could not see (agent, owner, instruction, mandate) in `attribution_gaps`. The client side sets `"payer"`.
+
+### Changed
+
+- An owner nobody named is sent as `{"id": "unattributed", "type": "unknown"}` (APE v0.2). The `labels.owner_type: "unknown"` stopgap is gone. A Stripe event with an owner id but no `halvor_owner_type` sends `type: "unknown"`.
### Fixed
- x402: the payer wallet is no longer used as `agent.id`. Without an agent context the agent is `unattributed`, and the wallet stays in `instrument.wallet`. Before, a seller-side payment looked attributed when nothing was known about the agent.
- x402: payments without a nonce no longer share the id `x402::unknown`. The id falls back to `x402::tx:`, then to `x402::event:`. A `tx:` id cannot join a payer-side record that has the nonce.
-- An event whose owner is `unattributed` now carries `labels.owner_type: "unknown"`, because APE v0.1 forces a placeholder type. A Stripe event with an owner id but no `halvor_owner_type` is labelled the same way, instead of silently becoming a business. A label you set yourself is kept.
## 0.6.0
diff --git a/README.md b/README.md
index 19d8616..ff2143f 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@
-
+
Signed, attributed payment events for AI agents. Each event records which agent paid, for which owner, on which instruction, with the network proof that came with the payment.
@@ -195,7 +195,8 @@ MPP and MCP adapters are in the Node.js SDK, [`@halvorai/ingest`](https://github
| I want to | Read |
| --- | --- |
| Send my first event to the sandbox | [Quickstart](https://docs.halvorai.com/get-started/quickstart/) |
-| Look up an event field | [APE v0.1 fields](https://github.com/halvorAI/ape-schema/blob/main/docs/FIELDS.md) |
+| Look up an event field | [APE fields](https://github.com/halvorAI/ape-schema/blob/main/docs/FIELDS.md) |
+| Record what the agent told its owner | [`emit_report`](https://docs.halvorai.com/sdks/python/#agent-reports) |
| Record MPP or MCP payments, or verify an evidence pack | [`@halvorai/ingest`](https://github.com/halvorAI/ingest-js) for Node.js |
| Read all the guides | [docs.halvorai.com](https://docs.halvorai.com) |
diff --git a/halvorai_ingest/client.py b/halvorai_ingest/client.py
index 622b669..8fb37eb 100644
--- a/halvorai_ingest/client.py
+++ b/halvorai_ingest/client.py
@@ -22,12 +22,12 @@
import httpx
from .context import current_context
-from .hash import evidence_sha256, hash_instruction
+from .hash import evidence_sha256, hash_instruction, normalise_instruction_text
from .ids import new_event_id, now_utc
from .redact import redact_deep, redact_text
from .sign import sign_event
from .spool import DEFAULT_MAX_AGE_S, DEFAULT_MAX_BYTES, Spool
-from .validate import validate_event
+from .validate import v02_fields_used, validate_event
def _package_version() -> str:
@@ -51,7 +51,23 @@ def _package_version() -> str:
RETRY_STATUSES = frozenset({408, 425, 429, 500, 502, 503, 504})
#: Statuses that fail the same way however often the batch is sent.
FATAL_STATUSES = frozenset({400, 401, 403, 404, 405, 409, 410, 415, 422})
-INSTRUCTION_FIELDS = ("id", "hash", "summary", "channel", "issued_at", "tool_call_id")
+INSTRUCTION_FIELDS = (
+ "id",
+ "hash",
+ "summary",
+ "channel",
+ "issued_at",
+ "tool_call_id",
+ "normalised_hash",
+ "normalisation",
+)
+
+# The owner when the caller names none. APE v0.2 says so with `type: "unknown"` instead of the v0.1
+# placeholder `business` plus an `owner_type` label (halvorAI/halvorai-app#99).
+UNKNOWN_OWNER = {"id": "unattributed", "type": "unknown", "unknown_reason": "not_provided"}
+
+# Top-level APE v0.2 fields an `emit()` input may carry as they are.
+V02_PASS_THROUGH = ("attribution_gaps", "delivery", "report")
def default_endpoint(api_key: str | None, environment: str) -> str:
@@ -268,6 +284,23 @@ def emit(self, input_event: Any) -> str:
self.notify({"code": "invalid_event", "message": str(exc) or "emit failed", "eventId": event_id})
return event_id
+ def emit_report(
+ self,
+ *,
+ instruction: Mapping[str, Any],
+ report: Mapping[str, Any],
+ **rest: Any,
+ ) -> str:
+ """APE v0.2 `agent.reported`: what the agent told its owner about an instruction.
+
+ HalvorAI lines it up with the payments made for that instruction. Pass `body` in `report`
+ to have the message hashed here; the text itself is never sent.
+ """
+ out = {k: v for k, v in report.items() if k != "body"}
+ if "body_sha256" not in out and isinstance(report.get("body"), str):
+ out["body_sha256"] = hash_instruction(report["body"])
+ return self.emit({**rest, "type": "agent.reported", "instruction": instruction, "report": out})
+
def stripe(self, event: Any) -> str | None:
"""
Map a Stripe webhook event (after your own signature check) and queue it. Returns the
@@ -358,7 +391,7 @@ def _build_event(
owner = (
input_event.get("owner")
or (ctx.get("owner") if ctx else None)
- or {"id": "unattributed", "type": "business"}
+ or dict(UNKNOWN_OWNER)
)
event: dict[str, Any] = {
"ape_version": "0.1",
@@ -371,33 +404,20 @@ def _build_event(
"source": source,
"agent": deepcopy(agent),
"owner": deepcopy(owner),
- "payment": input_event.get("payment"),
- "payee": input_event.get("payee"),
}
+ # An agent report (APE v0.2) is not a payment: it has no payment or payee.
+ if input_event.get("type") != "agent.reported":
+ event["payment"] = input_event.get("payment")
+ event["payee"] = input_event.get("payee")
if instruction is not None:
event["instruction"] = instruction
- for key in ("instrument", "evidence", "related", "labels"):
+ for key in ("instrument", "evidence", "related", "labels", *V02_PASS_THROUGH):
if input_event.get(key) is not None:
event[key] = input_event[key]
- self._label_unknown_owner(event)
+ # v0.1 unless the event uses a v0.2 field, so plain events stay readable by v0.1 receivers.
+ event["ape_version"] = "0.2" if v02_fields_used(event) else "0.1"
return event
- @staticmethod
- def _label_unknown_owner(event: dict[str, Any]) -> None:
- """APE v0.1 requires `owner.type`, so an unknown owner still carries a placeholder type.
-
- The label tells a reader the type is not a fact. A caller's own `owner_type` label wins.
- (halvorAI/halvorai-app#99; APE v0.2 is expected to allow `owner.type: "unknown"`.)
- """
- owner = event.get("owner")
- if not isinstance(owner, dict) or owner.get("id") != "unattributed":
- return
- labels = event.get("labels")
- if labels is None:
- event["labels"] = {"owner_type": "unknown"}
- elif isinstance(labels, dict) and "owner_type" not in labels and len(labels) < 20:
- event["labels"] = {**labels, "owner_type": "unknown"}
-
@staticmethod
def _build_instruction(
input_instruction: Any,
@@ -422,6 +442,12 @@ def _build_instruction(
value = hash_value if key == "hash" else raw.get(key)
if isinstance(value, str):
out[key] = value
+ # APE v0.2: `normalise=True` adds a hash of the ws-lower-v1 form, so two runs of one task match.
+ if "normalised_hash" in out:
+ out.setdefault("normalisation", "ws-lower-v1")
+ elif raw.get("normalise") is True and isinstance(raw.get("text"), str):
+ out["normalised_hash"] = hash_instruction(normalise_instruction_text(raw["text"]))
+ out["normalisation"] = "ws-lower-v1"
return out
def _redact_event(self, event: dict[str, Any]) -> None:
@@ -437,6 +463,8 @@ def _redact_event(self, event: dict[str, Any]) -> None:
("payee", "website"),
("payee", "resource_url"),
("instruction", "summary"),
+ ("report", "summary"),
+ ("delivery", "summary"),
):
parent = event.get(path[0])
if isinstance(parent, dict) and isinstance(parent.get(path[1]), str):
diff --git a/halvorai_ingest/hash.py b/halvorai_ingest/hash.py
index a3359a4..4d2588b 100644
--- a/halvorai_ingest/hash.py
+++ b/halvorai_ingest/hash.py
@@ -16,3 +16,14 @@ def evidence_sha256(value: str | object) -> str:
raw = value if isinstance(value, str) else canonicalize(value)
digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()
return f"sha256:{digest}"
+
+
+def normalise_instruction_text(text: str) -> str:
+ """`ws-lower-v1` (APE v0.2): NFC, lowercase, URL scheme, host and port removed (path kept),
+ whitespace collapsed to one space, trimmed. Matches the TypeScript SDK."""
+ import re
+ import unicodedata
+
+ out = unicodedata.normalize("NFC", text).lower()
+ out = re.sub(r"[a-z][a-z0-9+.-]*://[^\s/?#]+", "", out)
+ return re.sub(r"\s+", " ", out).strip()
diff --git a/halvorai_ingest/sign.py b/halvorai_ingest/sign.py
index 8ddb087..5b758b9 100644
--- a/halvorai_ingest/sign.py
+++ b/halvorai_ingest/sign.py
@@ -11,7 +11,13 @@
from .canonical import canonicalize
HEADER_TYP = "ape+jws"
-APE_VERSION = "0.1"
+APE_VERSIONS = ("0.1", "0.2")
+
+
+def _ape_version(event: Mapping[str, Any]) -> str:
+ """The event's `ape_version`; the JWS header `ape` must match it. Defaults to 0.1."""
+ version = event.get("ape_version")
+ return version if isinstance(version, str) and version in APE_VERSIONS else "0.1"
def _b64url_encode(data: bytes) -> str:
@@ -53,7 +59,7 @@ def sign_event(event: Mapping[str, Any], private_jwk: Mapping[str, Any]) -> str:
"alg": "EdDSA",
"kid": _source_id(event),
"typ": HEADER_TYP,
- "ape": APE_VERSION,
+ "ape": _ape_version(event),
}
# Compact JSON without spaces; key order matches sign.ts setProtectedHeader.
header_b64 = _b64url_encode(json.dumps(header, separators=(",", ":")).encode("utf-8"))
@@ -76,7 +82,7 @@ def verify_event(event: Mapping[str, Any], sig: str, public_jwk: Mapping[str, An
if (
header.get("alg") != "EdDSA"
or header.get("typ") != HEADER_TYP
- or header.get("ape") != APE_VERSION
+ or header.get("ape") != _ape_version(event)
or header.get("kid") != _source_id(event)
):
return False
diff --git a/halvorai_ingest/stripe/map.py b/halvorai_ingest/stripe/map.py
index 73d0b54..0ec63a7 100644
--- a/halvorai_ingest/stripe/map.py
+++ b/halvorai_ingest/stripe/map.py
@@ -103,14 +103,17 @@ def _attribution(meta: Mapping[str, str]) -> dict[str, Any]:
declared = meta.get("halvor_owner_type")
out: dict[str, Any] = {
"agent": agent,
- "owner": {
- "id": meta.get("halvor_owner_id", "unattributed"),
- "type": "person" if declared == "person" else "business",
- },
+ "owner": (
+ {"id": meta.get("halvor_owner_id", "unattributed"), "type": declared}
+ if declared in ("person", "business")
+ # APE v0.2 says the type is unknown instead of guessing (halvorAI/halvorai-app#99).
+ else {
+ "id": meta.get("halvor_owner_id", "unattributed"),
+ "type": "unknown",
+ "unknown_reason": "not_provided",
+ }
+ ),
}
- if declared not in ("person", "business"):
- # The type is a placeholder, so say so (halvorAI/halvorai-app#99).
- out["labels"] = {"owner_type": "unknown"}
instruction_id = meta.get("halvor_instruction_id")
if instruction_id is not None:
# Webhooks carry only the id; hash a stable local stand-in so APE validation passes.
@@ -190,8 +193,6 @@ def _finish(
mapped["occurred_at"] = at
if "instruction" in attr:
mapped["instruction"] = attr["instruction"]
- if "labels" in attr:
- mapped["labels"] = attr["labels"]
return mapped
diff --git a/halvorai_ingest/validate.py b/halvorai_ingest/validate.py
index ae0d5c5..1be1407 100644
--- a/halvorai_ingest/validate.py
+++ b/halvorai_ingest/validate.py
@@ -1,7 +1,8 @@
-"""APE v0.1 validation before signing, so a malformed event is dropped and reported, never sent.
+"""APE v0.1 and v0.2 validation before signing, so a malformed event is dropped and reported, never sent.
Mirrors the TypeScript SDK's zod model (`packages/schema/src/ape.ts`), which matches the published
-JSON Schema at https://schema.halvorai.com/ape/v0.1.json, plus the card-number guard.
+JSON Schemas at https://schema.halvorai.com/ape/v0.1.json and /ape/v0.2.json, plus the card-number
+guard. A `0.1` event that uses a v0.2 field is refused, as the v0.1 schema refuses it.
"""
from __future__ import annotations
@@ -64,6 +65,8 @@ def check(value: str) -> str:
Currency = Annotated[str, StringConstraints(strict=True, pattern=r"^[A-Z]{3}$")]
FourDigits = Annotated[str, StringConstraints(strict=True, pattern=r"^[0-9]{4}$")]
RefValue = Union[Annotated[str, StringConstraints(strict=True)], Annotated[int, Field(strict=True)]]
+CheckoutDigest = Annotated[str, StringConstraints(strict=True, pattern=r"^[A-Za-z0-9_-]{43}$")]
+GapReason = Literal["not_visible_to_observer", "not_provided"]
class _Strict(BaseModel):
@@ -87,6 +90,7 @@ class Source(_Strict):
adapter: Literal[
"stripe", "stripe-issuing", "x402-client", "x402-server", "mpp-server", "mcp", "manual", "custom"
]
+ perspective: Literal["payer", "payee", "facilitator", "network"] | None = None
class Kya(_Strict):
@@ -107,11 +111,18 @@ class Agent(_Strict):
class Owner(_Strict):
id: S128
- type: Literal["person", "business"]
+ type: Literal["person", "business", "unknown"]
+ unknown_reason: GapReason | None = None
display_name: S128 | None = None
country: Country | None = None
kyc_ref: S128 | None = None
+ @model_validator(mode="after")
+ def _reason_only_when_unknown(self) -> "Owner":
+ if self.unknown_reason is not None and self.type != "unknown":
+ raise ValueError("unknown_reason only with type unknown")
+ return self
+
class Instruction(_Strict):
id: S128
@@ -120,6 +131,14 @@ class Instruction(_Strict):
channel: Literal["chat", "api", "schedule", "email", "agent", "other"] | None = None
issued_at: DateTime | None = None
tool_call_id: S128 | None = None
+ normalised_hash: Sha256 | None = None
+ normalisation: Literal["ws-lower-v1"] | None = None
+
+ @model_validator(mode="after")
+ def _normalisation_pair(self) -> "Instruction":
+ if (self.normalised_hash is None) != (self.normalisation is None):
+ raise ValueError("normalised_hash and normalisation go together")
+ return self
class Asset(_Strict):
@@ -147,9 +166,24 @@ class AtomicAmount(_Strict):
PaymentStatus = Literal["requested", "authorized", "settled", "failed", "refunded", "disputed"]
+class Fee(_Strict):
+ kind: Literal["bridge", "network", "slippage", "platform", "fx", "other"]
+ amount: Amount
+
+
+class Intermediary(_Strict):
+ name: S128 | None = None
+ id: S128 | None = None
+ ref_tag: S128 | None = None
+
+
class _PaymentBase(_Strict):
payment_id: S256
amount: Amount
+ payer_amount: Amount | None = None
+ fees: Annotated[list[Fee], Field(max_length=8)] | None = None
+ checkout_digest: CheckoutDigest | None = None
+ intermediary: Intermediary | None = None
status: PaymentStatus
failure_reason: S128 | None = None
description: S256 | None = None
@@ -185,6 +219,7 @@ class X402Ref(_Strict):
tx_hash: RefValue | None = None
facilitator: RefValue | None = None
payment_flow: RefValue | None = None
+ submitter: RefValue | None = None
class MppRef(_Strict):
@@ -198,6 +233,7 @@ class StablecoinRef(_Strict):
network: RefValue | None = None
tx_hash: RefValue | None = None
log_index: RefValue | None = None
+ submitter: RefValue | None = None
class BankTransferRef(_Strict):
@@ -247,6 +283,12 @@ class Wallet(_Strict):
address: S128
+class ReceiptKey(_Strict):
+ kid: S128 | None = None
+ jwk: dict[str, Any] | None = None
+ jwks_uri: Url | None = None
+
+
class Payee(_Strict):
type: Literal["merchant", "api_provider", "wallet", "business", "person"]
name: S256 | None = None
@@ -256,6 +298,7 @@ class Payee(_Strict):
mcc: FourDigits | None = None
wallet: Wallet | None = None
resource_url: Url | None = None
+ receipt_key: ReceiptKey | None = None
@model_validator(mode="after")
def _identified(self) -> "Payee":
@@ -286,6 +329,8 @@ class Evidence(_Strict):
"stripe.object",
"agentic_token.metadata",
"kya.attestation",
+ "chain.receipt",
+ "tool.response",
]
format: Literal["sd-jwt", "kb-sd-jwt", "jws", "http-signature", "json"]
value: Union[Annotated[str, StringConstraints(strict=True)], dict[str, Any]] | None = None
@@ -309,6 +354,81 @@ class Related(_Strict):
Labels = Annotated[dict[S64, S256], Field(max_length=20)]
+class Delivery(_Strict):
+ request_sha256: Sha256 | None = None
+ response_sha256: Sha256 | None = None
+ response_bytes: Annotated[int, Field(strict=True, ge=0)] | None = None
+ http_status: Annotated[int, Field(strict=True, ge=100, le=599)] | None = None
+ summary: S256 | None = None
+
+
+class AttributionGap(_Strict):
+ field: Literal["owner", "agent", "instruction", "mandate"]
+ reason: GapReason
+
+
+def _unique_gap_fields(gaps: list[AttributionGap] | None) -> list[AttributionGap] | None:
+ if gaps is not None and len({g.field for g in gaps}) != len(gaps):
+ raise ValueError("each attribution gap field at most once")
+ return gaps
+
+
+AttributionGaps = Annotated[list[AttributionGap], Field(max_length=4), AfterValidator(_unique_gap_fields)]
+
+
+class Report(_Strict):
+ channel: Literal["chat", "api", "email", "other"] | None = None
+ summary: S500 | None = None
+ payments_claimed: Annotated[int, Field(strict=True, ge=0)] | None = None
+ amount_claimed: Amount | None = None
+ body_sha256: Sha256
+
+
+V02_EVIDENCE_KINDS = ("chain.receipt", "tool.response")
+
+
+def v02_fields_used(event: Mapping[str, Any]) -> list[str]:
+ """Paths of APE v0.2 fields in an event, so a `0.1` event that uses one can be refused."""
+
+ def obj(v: Any) -> Mapping[str, Any]:
+ return v if isinstance(v, Mapping) else {}
+
+ out: list[str] = []
+ if event.get("type") == "agent.reported":
+ out.append("type")
+ out += [k for k in ("attribution_gaps", "delivery", "report") if k in event]
+ if "perspective" in obj(event.get("source")):
+ out.append("source.perspective")
+ owner = obj(event.get("owner"))
+ if owner.get("type") == "unknown":
+ out.append("owner.type")
+ if "unknown_reason" in owner:
+ out.append("owner.unknown_reason")
+ instruction = obj(event.get("instruction"))
+ out += [f"instruction.{k}" for k in ("normalised_hash", "normalisation") if k in instruction]
+ payment = obj(event.get("payment"))
+ out += [f"payment.{k}" for k in ("payer_amount", "fees", "checkout_digest", "intermediary") if k in payment]
+ if "submitter" in obj(payment.get("rail_ref")):
+ out.append("payment.rail_ref.submitter")
+ if "receipt_key" in obj(event.get("payee")):
+ out.append("payee.receipt_key")
+ evidence = event.get("evidence")
+ if isinstance(evidence, list):
+ out += [f"evidence.{i}.kind" for i, e in enumerate(evidence) if obj(e).get("kind") in V02_EVIDENCE_KINDS]
+ return out
+
+
+class _Versioned(_Strict):
+ @model_validator(mode="before")
+ @classmethod
+ def _v02_only_in_v02(cls, data: Any) -> Any:
+ if isinstance(data, Mapping) and data.get("ape_version") == "0.1":
+ used = v02_fields_used(data)
+ if used:
+ raise ValueError(f"v0.2 field in a 0.1 event: {', '.join(used)}")
+ return data
+
+
def contains_pan(text: str) -> bool:
"""True when text holds a Luhn-valid run of 13 to 19 digits (spaces or dashes allowed)."""
# Same boundaries as the redaction: digits glued to letters (hex, base64, ids) are not a card.
@@ -331,8 +451,8 @@ def _luhn(digits: str) -> bool:
return total % 10 == 0
-class ApeEvent(_Strict):
- ape_version: Literal["0.1"]
+class ApeEvent(_Versioned):
+ ape_version: Literal["0.1", "0.2"]
id: EventId
type: Literal[
"payment.requested",
@@ -354,6 +474,8 @@ class ApeEvent(_Strict):
evidence: Annotated[list[Evidence], Field(max_length=16)] | None = None
related: Related | None = None
labels: Labels | None = None
+ attribution_gaps: AttributionGaps | None = None
+ delivery: Delivery | None = None
@model_validator(mode="after")
def _no_card_numbers(self) -> "ApeEvent":
@@ -367,6 +489,40 @@ def _no_card_numbers(self) -> "ApeEvent":
self.payee.name,
self.payee.website,
self.payee.resource_url,
+ self.delivery.summary if self.delivery else None,
+ *(self.labels or {}).keys(),
+ *(self.labels or {}).values(),
+ ]
+ if any(t is not None and contains_pan(t) for t in texts):
+ raise ValueError("pan_detected")
+ return self
+
+
+class ApeReportEvent(_Versioned):
+ """APE v0.2 `agent.reported`: what the agent told its owner. Not a payment."""
+
+ ape_version: Literal["0.1", "0.2"]
+ id: EventId
+ type: Literal["agent.reported"]
+ occurred_at: DateTime
+ environment: Literal["test", "live"]
+ source: Source
+ agent: Agent
+ owner: Owner
+ instruction: Instruction
+ report: Report
+ evidence: Annotated[list[Evidence], Field(max_length=16)] | None = None
+ related: Related | None = None
+ labels: Labels | None = None
+ attribution_gaps: AttributionGaps | None = None
+
+ @model_validator(mode="after")
+ def _no_card_numbers(self) -> "ApeReportEvent":
+ texts = [
+ self.report.summary,
+ self.instruction.summary,
+ self.agent.name,
+ self.owner.display_name,
*(self.labels or {}).keys(),
*(self.labels or {}).values(),
]
@@ -376,12 +532,14 @@ def _no_card_numbers(self) -> "ApeEvent":
_EVENT = TypeAdapter(ApeEvent)
+_REPORT = TypeAdapter(ApeReportEvent)
def validate_event(event: Mapping[str, Any]) -> list[str]:
"""Problems with the event, as `path: message` strings. Empty when the event is valid."""
try:
- _EVENT.validate_python(dict(event))
+ adapter = _REPORT if event.get("type") == "agent.reported" else _EVENT
+ adapter.validate_python(dict(event))
return []
except ValidationError as exc:
return [".".join(str(p) for p in err["loc"]) + ": " + err["msg"] for err in exc.errors()]
diff --git a/halvorai_ingest/x402/map.py b/halvorai_ingest/x402/map.py
index 03ba5f0..d7dc11c 100644
--- a/halvorai_ingest/x402/map.py
+++ b/halvorai_ingest/x402/map.py
@@ -39,23 +39,39 @@ def _host(url: str | None) -> str | None:
return None
-def _attribution() -> dict[str, Any]:
- """Agent and owner, but only when `agent_context` did not set them.
+def _attribution(adapter: str) -> dict[str, Any]:
+ """Agent and owner, but only when `agent_context` did not set them, and what is missing.
- When it did, they are left out so the client fills the full context (name, framework,
- country, KYC reference) when the event is emitted.
+ When the context set them, they are left out so the client fills the full context (name,
+ framework, country, KYC reference) when the event is emitted. A seller sees a wallet, not the
+ agent, its owner, the instruction or a mandate, so without a context it says those are not
+ visible to it (APE v0.2 `attribution_gaps`); a buyer without a context did not provide them.
"""
ctx = current_context()
+ reason = "not_visible_to_observer" if adapter == "x402-server" else "not_provided"
out: dict[str, Any] = {}
+ gaps: list[dict[str, str]] = []
if not ctx or not ctx.get("agent"):
# The payer wallet is never the agent id: it does not say which agent paid and would count
# the payment as attributed. It stays in `instrument.wallet`.
out["agent"] = {"id": "unattributed"}
+ gaps.append({"field": "agent", "reason": reason})
if not ctx or not ctx.get("owner"):
- out["owner"] = {"id": "unattributed", "type": "business"}
+ out["owner"] = {"id": "unattributed", "type": "unknown", "unknown_reason": reason}
+ gaps.append({"field": "owner", "reason": reason})
+ if adapter == "x402-server":
+ if not ctx or not ctx.get("instruction"):
+ gaps.append({"field": "instruction", "reason": reason})
+ gaps.append({"field": "mandate", "reason": reason})
+ if gaps:
+ out["attribution_gaps"] = gaps
return out
+def _source(adapter: str) -> dict[str, str]:
+ return {"adapter": adapter, "perspective": "payee" if adapter == "x402-server" else "payer"}
+
+
def _payment_id(network: str, *, nonce: str | None, tx_hash: str | None, event_id: str) -> str:
"""`x402::` joins authorization, settlement and failure.
@@ -158,8 +174,8 @@ def map_payment_required(
return {
"id": event_id,
"type": "payment.requested",
- "source": {"adapter": adapter},
- **_attribution(),
+ "source": _source(adapter),
+ **_attribution(adapter),
"payment": payment,
"payee": _payee(accept, resource, payee_override),
"evidence": [],
@@ -194,8 +210,8 @@ def map_payment_payload(
mapped: dict[str, Any] = {
"id": event_id,
"type": "payment.authorized",
- "source": {"adapter": adapter},
- **_attribution(),
+ "source": _source(adapter),
+ **_attribution(adapter),
"payment": payment,
"payee": _payee(accepted, resource, payee_override),
"evidence": [
@@ -250,8 +266,8 @@ def map_settlement_response(
mapped: dict[str, Any] = {
"id": event_id,
"type": "payment.settled" if success else "payment.failed",
- "source": {"adapter": adapter},
- **_attribution(),
+ "source": _source(adapter),
+ **_attribution(adapter),
"payment": payment,
"payee": _payee(merged, resource, payee_override),
"evidence": [
diff --git a/pyproject.toml b/pyproject.toml
index 5aead97..30c5a10 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "halvorai-ingest"
-version = "0.6.0"
+version = "0.7.0"
description = "Signed, attributed payment events for AI agents. Never in the payment path."
readme = "README.md"
requires-python = ">=3.10"
diff --git a/tests/fixtures/ape-v0.2/agent-reported.v0.2.json b/tests/fixtures/ape-v0.2/agent-reported.v0.2.json
new file mode 100644
index 0000000..fde84ae
--- /dev/null
+++ b/tests/fixtures/ape-v0.2/agent-reported.v0.2.json
@@ -0,0 +1,36 @@
+{
+ "ape_version": "0.2",
+ "id": "evt_01JD3C9Z8Y7X6W5V4T3S2R1Q0P",
+ "type": "agent.reported",
+ "occurred_at": "2026-11-24T12:00:09.020Z",
+ "environment": "test",
+ "source": {
+ "id": "src_01JD3B0A1B2C3D4E5F6G7H8J9K",
+ "sdk": "@halvorai/ingest@0.5.0",
+ "adapter": "custom",
+ "perspective": "payer"
+ },
+ "agent": {
+ "id": "agt_research_buyer",
+ "name": "Research buyer"
+ },
+ "owner": {
+ "id": "own_sample_person",
+ "type": "person"
+ },
+ "instruction": {
+ "id": "ins_buy_dataset",
+ "hash": "sha256:3333333333333333333333333333333333333333333333333333333333333333"
+ },
+ "report": {
+ "channel": "chat",
+ "summary": "Bought the Tidewater Data export for $0.25.",
+ "payments_claimed": 1,
+ "amount_claimed": {
+ "value": "25",
+ "unit": "minor",
+ "currency": "USD"
+ },
+ "body_sha256": "sha256:6666666666666666666666666666666666666666666666666666666666666666"
+ }
+}
diff --git a/tests/fixtures/ape-v0.2/stablecoin-settled-payer-side.v0.2.json b/tests/fixtures/ape-v0.2/stablecoin-settled-payer-side.v0.2.json
new file mode 100644
index 0000000..3443e01
--- /dev/null
+++ b/tests/fixtures/ape-v0.2/stablecoin-settled-payer-side.v0.2.json
@@ -0,0 +1,114 @@
+{
+ "ape_version": "0.2",
+ "id": "evt_01JD3C1A2B3C4D5E6F7G8H9J0K",
+ "type": "payment.settled",
+ "occurred_at": "2026-11-24T12:00:06.312Z",
+ "environment": "test",
+ "source": {
+ "id": "src_01JD3B0A1B2C3D4E5F6G7H8J9K",
+ "sdk": "@halvorai/ingest@0.5.0",
+ "adapter": "custom",
+ "perspective": "payer"
+ },
+ "agent": {
+ "id": "agt_research_buyer",
+ "name": "Research buyer"
+ },
+ "owner": {
+ "id": "own_sample_person",
+ "type": "person"
+ },
+ "instruction": {
+ "id": "ins_buy_dataset",
+ "hash": "sha256:3333333333333333333333333333333333333333333333333333333333333333",
+ "normalised_hash": "sha256:4444444444444444444444444444444444444444444444444444444444444444",
+ "normalisation": "ws-lower-v1",
+ "summary": "Buy one Tidewater Data export.",
+ "channel": "chat",
+ "tool_call_id": "call_pay_2"
+ },
+ "payment": {
+ "payment_id": "pay_second_attempt",
+ "rail": "stablecoin",
+ "amount": {
+ "value": "250000",
+ "unit": "atomic",
+ "asset": {
+ "network": "eip155:8453",
+ "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
+ "symbol": "USDC",
+ "decimals": 6
+ }
+ },
+ "payer_amount": {
+ "value": "253636",
+ "unit": "atomic",
+ "asset": {
+ "network": "eip155:8453",
+ "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
+ "symbol": "USDC",
+ "decimals": 6
+ }
+ },
+ "fees": [
+ {
+ "kind": "bridge",
+ "amount": {
+ "value": "1125",
+ "unit": "atomic",
+ "asset": {
+ "network": "eip155:8453",
+ "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
+ "symbol": "USDC",
+ "decimals": 6
+ }
+ }
+ },
+ {
+ "kind": "slippage",
+ "amount": {
+ "value": "2511",
+ "unit": "atomic",
+ "asset": {
+ "network": "eip155:8453",
+ "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
+ "symbol": "USDC",
+ "decimals": 6
+ }
+ }
+ }
+ ],
+ "checkout_digest": "Xk3h2m8QpL0vN7rT4yW1zA6bC9dE5fG2hJ8kM3nP0qR",
+ "status": "settled",
+ "description": "Dataset export",
+ "rail_ref": {
+ "network": "eip155:8453",
+ "tx_hash": "0x3c5e7a9b1d3f5a7c9e1b3d5f7a9c1e3b5d7f9a1c3e5b7d9f1a3c5e7b9d1f3a5c",
+ "log_index": 4
+ }
+ },
+ "payee": {
+ "type": "business",
+ "name": "Tidewater Data",
+ "id": "tidewater-data",
+ "receipt_key": {
+ "kid": "tidewater-receipts-1",
+ "jwks_uri": "https://tidewater.example.com/.well-known/jwks.json"
+ }
+ },
+ "evidence": [
+ {
+ "kind": "tool.response",
+ "format": "json",
+ "value": {
+ "tool": "pay_invoice",
+ "call_id": "call_pay_1",
+ "at": "2026-11-24T12:00:01.204Z",
+ "content_type": "application/json",
+ "body_sha256": "sha256:5555555555555555555555555555555555555555555555555555555555555555",
+ "body": "{\"status\":\"failed\",\"reason\":\"timeout\"}"
+ },
+ "sha256": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
+ }
+ ]
+}
diff --git a/tests/fixtures/ape-v0.2/x402-settled-payee-observed.v0.2.json b/tests/fixtures/ape-v0.2/x402-settled-payee-observed.v0.2.json
new file mode 100644
index 0000000..30bc803
--- /dev/null
+++ b/tests/fixtures/ape-v0.2/x402-settled-payee-observed.v0.2.json
@@ -0,0 +1,107 @@
+{
+ "ape_version": "0.2",
+ "id": "evt_01JD2S8E5K7M9P1R3T5V7X9Z0B",
+ "type": "payment.settled",
+ "occurred_at": "2026-11-20T15:02:11.481Z",
+ "environment": "test",
+ "source": {
+ "id": "src_01JD2S0A1B2C3D4E5F6G7H8J9K",
+ "sdk": "@halvorai/ingest@0.5.0",
+ "adapter": "x402-server",
+ "perspective": "payee"
+ },
+ "agent": {
+ "id": "unattributed"
+ },
+ "owner": {
+ "id": "unattributed",
+ "type": "unknown",
+ "unknown_reason": "not_visible_to_observer"
+ },
+ "attribution_gaps": [
+ {
+ "field": "agent",
+ "reason": "not_visible_to_observer"
+ },
+ {
+ "field": "owner",
+ "reason": "not_visible_to_observer"
+ },
+ {
+ "field": "instruction",
+ "reason": "not_visible_to_observer"
+ },
+ {
+ "field": "mandate",
+ "reason": "not_visible_to_observer"
+ }
+ ],
+ "payment": {
+ "payment_id": "x402:eip155:8453:0x5c0f3c1a9e2b7d4f6a8c0e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a4c6e8b0d2f",
+ "rail": "x402",
+ "amount": {
+ "value": "10000",
+ "unit": "atomic",
+ "asset": {
+ "network": "eip155:8453",
+ "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
+ "symbol": "USDC",
+ "decimals": 6
+ }
+ },
+ "status": "settled",
+ "description": "Company lookup, 1 request",
+ "intermediary": {
+ "name": "Example API Marketplace",
+ "id": "mkt_example",
+ "ref_tag": "ref_7f3a"
+ },
+ "rail_ref": {
+ "scheme": "exact",
+ "network": "eip155:8453",
+ "nonce": "0x5c0f3c1a9e2b7d4f6a8c0e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a4c6e8b0d2f",
+ "tx_hash": "0x9a7b5c3d1e0f2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c2d4e6f8a0b2c4d6e8f0a2b",
+ "facilitator": "https://x402.org/facilitator",
+ "submitter": "0x4Fd1A0b6c2E8f3d7B9a5C1e6F0d2B8a4C7e9F3d1",
+ "payment_flow": "authorization"
+ }
+ },
+ "payee": {
+ "type": "api_provider",
+ "name": "Example Company Data",
+ "wallet": {
+ "network": "eip155:8453",
+ "address": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C"
+ },
+ "resource_url": "https://api.example.com/lookup"
+ },
+ "instrument": {
+ "type": "wallet",
+ "wallet": {
+ "network": "eip155:8453",
+ "address": "0x857b06519E91e3A54538791bDbb0E22373e36b66"
+ }
+ },
+ "delivery": {
+ "request_sha256": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
+ "response_sha256": "sha256:2222222222222222222222222222222222222222222222222222222222222222",
+ "response_bytes": 4812,
+ "http_status": 200,
+ "summary": "10 of 12 matches returned (result limit)"
+ },
+ "evidence": [
+ {
+ "kind": "chain.receipt",
+ "format": "json",
+ "value": {
+ "network": "eip155:8453",
+ "tx_hash": "0x9a7b5c3d1e0f2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c2d4e6f8a0b2c4d6e8f0a2b",
+ "block_number": 22918844,
+ "log_index": 117,
+ "submitter": "0x4Fd1A0b6c2E8f3d7B9a5C1e6F0d2B8a4C7e9F3d1",
+ "status": "success"
+ },
+ "sha256": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
+ }
+ ]
+}
diff --git a/tests/fixtures/stripe/expected.json b/tests/fixtures/stripe/expected.json
index fcdab27..f0c7774 100644
--- a/tests/fixtures/stripe/expected.json
+++ b/tests/fixtures/stripe/expected.json
@@ -460,7 +460,8 @@
},
"owner": {
"id": "own_acme_ltd",
- "type": "business"
+ "type": "unknown",
+ "unknown_reason": "not_provided"
},
"payment": {
"payment_id": "pi_3QxFailCardDeclined",
@@ -506,10 +507,7 @@
"sha256": "sha256:aff5e0397ad01568cffe874a076f690cc767c7d49b98c6489f27dc98335c2d10"
}
],
- "occurred_at": "2024-10-17T12:00:12.000Z",
- "labels": {
- "owner_type": "unknown"
- }
+ "occurred_at": "2024-10-17T12:00:12.000Z"
},
"payment_intent.succeeded.json": {
"type": "payment.settled",
@@ -588,7 +586,8 @@
},
"owner": {
"id": "unattributed",
- "type": "business"
+ "type": "unknown",
+ "unknown_reason": "not_provided"
},
"payment": {
"payment_id": "pi_3QxNoMeta",
@@ -622,10 +621,7 @@
"sha256": "sha256:ad600225b2e8e350da3b094a9aca984c39a920e08aa2298916be848f89f0e374"
}
],
- "occurred_at": "2024-10-17T12:43:20.000Z",
- "labels": {
- "owner_type": "unknown"
- }
+ "occurred_at": "2024-10-17T12:43:20.000Z"
},
"case:named-card": {
"input": {
diff --git a/tests/test_ape_v02.py b/tests/test_ape_v02.py
new file mode 100644
index 0000000..4585963
--- /dev/null
+++ b/tests/test_ape_v02.py
@@ -0,0 +1,80 @@
+"""APE v0.2 (halvorAI/halvorai-app#100, #109): validation and signing match the TypeScript SDK."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from halvorai_ingest import generate_source_key, verify_event
+from halvorai_ingest.hash import normalise_instruction_text
+from halvorai_ingest.sign import sign_event
+from halvorai_ingest.validate import v02_fields_used, validate_event
+
+V02 = Path(__file__).parent / "fixtures" / "ape-v0.2"
+
+
+def load(name: str) -> dict[str, Any]:
+ data: dict[str, Any] = json.loads((V02 / name).read_text(encoding="utf-8"))
+ return data
+
+
+@pytest.mark.parametrize("name", sorted(p.name for p in V02.glob("*.json")))
+def test_the_published_v02_examples_are_valid(name: str) -> None:
+ assert validate_event(load(name)) == []
+
+
+def test_a_v01_event_cannot_use_a_v02_field() -> None:
+ event = load("stablecoin-settled-payer-side.v0.2.json")
+ event["ape_version"] = "0.1"
+ assert v02_fields_used(event)
+ assert validate_event(event)
+
+
+@pytest.mark.parametrize(
+ "mutate",
+ [
+ lambda e: e["owner"].update(type="person"), # unknown_reason with a known type
+ lambda e: e["attribution_gaps"].append({"field": "agent", "reason": "not_provided"}),
+ lambda e: e.update(delivery={"http_status": 99}),
+ ],
+)
+def test_bad_v02_payment_events_are_refused(mutate: Any) -> None:
+ event = load("x402-settled-payee-observed.v0.2.json")
+ mutate(event)
+ assert validate_event(event)
+
+
+def test_a_report_needs_a_report_and_no_payment() -> None:
+ report = load("agent-reported.v0.2.json")
+ assert validate_event({k: v for k, v in report.items() if k != "report"})
+ with_payment = {**report, "payment": load("stablecoin-settled-payer-side.v0.2.json")["payment"]}
+ assert validate_event(with_payment)
+
+
+def test_the_signature_header_names_the_event_version() -> None:
+ key = generate_source_key()
+ for name, version in (("agent-reported.v0.2.json", "0.2"),):
+ event = load(name)
+ event["source"]["id"] = key["kid"]
+ sig = sign_event(event, key)
+ header = json.loads(_b64(sig.split(".")[0]))
+ assert header["ape"] == version
+ assert verify_event(event, sig, key)
+ assert not verify_event({**event, "ape_version": "0.1"}, sig, key)
+
+
+def test_ws_lower_v1_matches_the_typescript_sdk() -> None:
+ a = "Buy the Tidewater export from http://localhost:8123/pay?item=1 now"
+ b = "buy the tidewater export from http://127.0.0.1:9000/pay?item=1 now"
+ assert normalise_instruction_text(a) == normalise_instruction_text(b)
+ assert normalise_instruction_text(a) == "buy the tidewater export from /pay?item=1 now"
+ assert normalise_instruction_text("Café") == normalise_instruction_text("Café")
+
+
+def _b64(segment: str) -> bytes:
+ import base64
+
+ return base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))
diff --git a/tests/test_client.py b/tests/test_client.py
index b936acf..bdfca6d 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -5,6 +5,7 @@
from pathlib import Path
from halvorai_ingest import HalvorClient, agent_context, verify_event
+from halvorai_ingest.hash import hash_instruction
VECTOR = Path(__file__).resolve().parent / "fixtures" / "sign-vector.json"
@@ -89,23 +90,58 @@ def _emit_one(**overrides: Any) -> dict[str, Any]:
return event
-def test_unknown_owner_is_labelled_because_the_type_is_only_a_placeholder() -> None:
- """halvorAI/halvorai-app#99: v0.1 forces a type, so the label says it is not a fact."""
+def test_unknown_owner_is_unknown_with_no_label_stopgap() -> None:
+ """halvorAI/halvorai-app#99: APE v0.2 says the owner type is unknown."""
event = _emit_one()
- assert event["owner"] == {"id": "unattributed", "type": "business"}
- assert event["labels"] == {"owner_type": "unknown"}
+ assert event["owner"] == {"id": "unattributed", "type": "unknown", "unknown_reason": "not_provided"}
+ assert "labels" not in event
+ assert event["ape_version"] == "0.2"
-def test_an_adapter_supplied_unattributed_owner_is_labelled_too() -> None:
- event = _emit_one(owner={"id": "unattributed", "type": "business"})
- assert event["labels"] == {"owner_type": "unknown"}
+def test_a_fully_attributed_event_stays_v01() -> None:
+ event = _emit_one(agent={"id": "agt_1"}, owner={"id": "own_real", "type": "person"})
+ assert event["ape_version"] == "0.1"
+ assert "labels" not in event
-def test_a_real_owner_is_not_labelled() -> None:
- event = _emit_one(owner={"id": "own_real", "type": "person"})
- assert "labels" not in event
+def test_v02_fields_pass_through() -> None:
+ event = _emit_one(
+ agent={"id": "agt_1"},
+ owner={"id": "own_1", "type": "person"},
+ source={"perspective": "payer"},
+ delivery={"http_status": 200, "summary": "10 of 12 results"},
+ attribution_gaps=[{"field": "mandate", "reason": "not_provided"}],
+ )
+ assert event["ape_version"] == "0.2"
+ assert event["source"]["perspective"] == "payer"
+ assert event["delivery"] == {"http_status": 200, "summary": "10 of 12 results"}
+
+
+def test_normalise_adds_a_ws_lower_v1_hash() -> None:
+ event = _emit_one(instruction={"id": "ins_1", "text": "Buy it from http://localhost:8123/pay", "normalise": True})
+ assert event["instruction"]["normalisation"] == "ws-lower-v1"
+ assert event["instruction"]["normalised_hash"] == hash_instruction("buy it from /pay")
+ assert event["instruction"]["hash"] == hash_instruction("Buy it from http://localhost:8123/pay")
+
+
+def test_emit_report_hashes_the_message_and_has_no_payment() -> None:
+ data = json.loads(VECTOR.read_text(encoding="utf-8"))
+ envelopes: list[dict[str, Any]] = []
+ errors: list[dict[str, Any]] = []
+ client = HalvorClient(source_key=data["private_jwk"], environment="test", sink=envelopes.extend, on_error=errors.append, exit_hook=False)
+ client.emit_report(
+ instruction={"id": "ins_1", "text": "Buy one export"},
+ report={"body": "Done, paid once.", "payments_claimed": 1, "summary": "Paid once."},
+ )
+ client.flush(timeout=5)
+ client.close()
+ assert errors == []
+ (envelope,) = envelopes
+ event = envelope["event"]
+ assert event["type"] == "agent.reported"
+ assert event["ape_version"] == "0.2"
+ assert event["report"]["body_sha256"] == hash_instruction("Done, paid once.")
+ assert "payment" not in event
+ assert "Done, paid once." not in json.dumps(event)
-def test_caller_labels_are_kept_and_owner_type_is_not_overwritten() -> None:
- assert _emit_one(labels={"team": "growth"})["labels"] == {"team": "growth", "owner_type": "unknown"}
- assert _emit_one(labels={"owner_type": "person"})["labels"] == {"owner_type": "person"}
diff --git a/tests/test_stripe.py b/tests/test_stripe.py
index 05736d5..332547f 100644
--- a/tests/test_stripe.py
+++ b/tests/test_stripe.py
@@ -227,7 +227,7 @@ def test_emoji_names_fit_the_api_limit_and_sign() -> None:
assert sent[0]["event"]["agent"]["name"] == "a" * 127
-def test_owner_type_is_labelled_unknown_when_the_metadata_has_an_owner_id_but_no_type() -> None:
+def test_owner_type_is_unknown_when_the_metadata_has_an_owner_id_but_no_type() -> None:
"""halvorAI/halvorai-app#99: a person-owned card must not be reported as a business."""
event = load("payment_intent.succeeded.json")
metadata = event["data"]["object"].setdefault("metadata", {})
@@ -235,8 +235,7 @@ def test_owner_type_is_labelled_unknown_when_the_metadata_has_an_owner_id_but_no
metadata.pop("halvor_owner_type", None)
mapped = map_stripe_event(event)
assert mapped is not None
- assert mapped["owner"] == {"id": "own_known", "type": "business"}
- assert mapped["labels"] == {"owner_type": "unknown"}
+ assert mapped["owner"] == {"id": "own_known", "type": "unknown", "unknown_reason": "not_provided"}
metadata["halvor_owner_type"] = "person"
typed = map_stripe_event(event)
diff --git a/tests/test_x402.py b/tests/test_x402.py
index fda0316..30db79e 100644
--- a/tests/test_x402.py
+++ b/tests/test_x402.py
@@ -236,3 +236,36 @@ async def test_async_transport_and_wrapper() -> None:
await http.post(url, headers={"PAYMENT-SIGNATURE": encode_payment_header(PAYLOAD)})
await http.aclose()
check_round_trip(halvor, sent)
+
+
+def test_a_seller_without_context_says_what_it_cannot_see() -> None:
+ """APE v0.2 (halvorAI/halvorai-app#100): perspective payee, unknown owner, attribution gaps."""
+ mapped = map_payment_payload(PAYLOAD, "x402-server")
+ assert mapped is not None
+ assert mapped["source"] == {"adapter": "x402-server", "perspective": "payee"}
+ assert mapped["owner"] == {"id": "unattributed", "type": "unknown", "unknown_reason": "not_visible_to_observer"}
+ assert mapped["attribution_gaps"] == [
+ {"field": "agent", "reason": "not_visible_to_observer"},
+ {"field": "owner", "reason": "not_visible_to_observer"},
+ {"field": "instruction", "reason": "not_visible_to_observer"},
+ {"field": "mandate", "reason": "not_visible_to_observer"},
+ ]
+ (event,) = emit_all(mapped)
+ assert event["ape_version"] == "0.2"
+ assert validate_event(event) == []
+
+
+def test_a_buyer_without_context_did_not_provide_them() -> None:
+ mapped = map_payment_payload(PAYLOAD)
+ assert mapped is not None
+ assert mapped["source"] == {"adapter": "x402-client", "perspective": "payer"}
+ assert mapped["attribution_gaps"] == [
+ {"field": "agent", "reason": "not_provided"},
+ {"field": "owner", "reason": "not_provided"},
+ ]
+
+
+def test_a_buyer_with_context_has_no_gaps() -> None:
+ with agent_context(agent={"id": "agt_1"}, owner={"id": "own_1", "type": "person"}):
+ mapped = map_payment_payload(PAYLOAD)
+ assert mapped is not None and "attribution_gaps" not in mapped
diff --git a/uv.lock b/uv.lock
index 0d012d4..ae5f057 100644
--- a/uv.lock
+++ b/uv.lock
@@ -323,7 +323,7 @@ wheels = [
[[package]]
name = "halvorai-ingest"
-version = "0.6.0"
+version = "0.7.0"
source = { editable = "." }
dependencies = [
{ name = "cryptography" },