← Back to Pull requests

feat(spec): propose and prototype interceptor response envelopes #133

Merged
liamcrumm merged 39 files (1797 lines) on Oct 16, 2026 01:57 UTC
View on GitHub
liamcrumm liamcrumm commented on Oct 14, 2026 01:22 UTC
Author

What this proposes

Hosted interceptors often return provider data alongside a control decision. P-006 proposes a separate transport envelope without opening canonical Verdict:

{
  "verdict": { "decision": "allow" },
  "extensions": {
    "provider_name": {
      "receipt": { "receiptVersion": "provider-contract/1.0" }
    }
  }
}

The root is closed to verdict and optional extensions. Receipts belong under extensions.<provider>.receipt; a dedicated root receipt is rejected. All five SDK parsers accept bare Verdicts and envelopes. Only the nested Verdict affects enforcement; in-process signatures, composition and records remain unchanged.

P-006 remains Draft pending the maintainer's formal decision. The October 15 review direction is implemented, but the proposal, spec section and SDK surface remain explicitly proposed/prototype until that decision is recorded.

Review fixes

  • Renumber the proposal from P-005 to P-006, including its filename and every live reference

  • Use namespaced extensions as the only metadata carrier across schema, spec, proposal, examples, five SDKs and shared fixtures

  • Bound canonical extensions at 65536 bytes across all namespaces, independently of the evidence cap

  • Reject unsafe integer literals and duplicates at every object level; retain I-JSON re-serialization and provider-defined signature canonicalization

  • Preserve the shared strict Verdict validator, parsed-value depth bound, bounded error detail and size checks before metadata cloning

  • Pin namespaced receipt round trips, multiple providers, opaque namespace values, legacy-root rejection and exact 65536/65537-byte boundaries across SDKs

  • Retain the Python native stub/public exception and ordinary Go number decoding; update the additive .NET API snapshot introduced on main

  • Merge main at 68826589e3019cf88ea04b3f3b237fbcd8bb6926 without rewriting PR history
  • Normal serialization prefers a bare Verdict when extensions are absent or empty. Rust's explicit to_envelope_value remains the shared FFI normalizer's always-envelope representation.

    Local validation

    At 165a818ac8cbfed1e18c797370be72607341ad93:

  • Rust: 183 tests pass; workspace/all-features format and strict clippy pass

  • Python: 304 pass, six existing skips; format, lint and response-module mypy pass

  • TypeScript: 240 pass; native build, generated bindings and type-check pass

  • .NET: 216 pass, including the additive API snapshot; format and warning-as-error build pass

  • Go: both packages pass, including CTK; vet and format pass

  • Fifteen schemas are well-formed; eleven valid response fixture shapes validate; closed Verdict/root receipt rejection, vendored schema equality and version consistency pass
  • CI must be checked on this head; local results do not imply hosted checks are green. Whole-package mypy also reports two existing errors in unchanged composition.py; the response module passes its focused check. No review replies, reviews or thread resolutions were posted. The existing non-draft state and target branch are unchanged.

    Diff: 1797 lines (+1784 / -13) across 39 files Reviewer: MohammadHaroonAbuomar Review duration: 2915m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.72) × (1 − Review Confidence (0.71)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 1797 lines diff across 39 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.53 · 5 substantive comment(s)
    0.53
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    70%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    23 items
    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    docs/proposals/P-005-interceptor-response-envelope.md:1
    @@ -0,0 +1,360 @@
    +# P-005: A transport response envelope around canonical Verdict
    +
    +**Status:** **Draft** — raised 2026-10-14. A complete prototype implementation is

    The proposal is Draft with five decision boxes open (receipt vs metadata, verdict-only envelope validity, the 64 KiB bound, option A to D), while this PR ships MUST text in §5.5 and public SDK types. docs/proposals/README.md says implementation follows the decision. Either set Status to Decided <date> here, tick or delete the decision list and keep the spec text, or hold §5.5 and the SDK surface until it is decided. Also drop the em dash on this line.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    docs/proposals/P-005-interceptor-response-envelope.md:1
    @@ -0,0 +1,360 @@
    +# P-005: A transport response envelope around canonical Verdict
    +
    +**Status:** **Draft** — raised 2026-10-14. A complete prototype implementation is
    +included on the proposal branch for cross-SDK review; it is not a decided contract.
    +**Raised by:** hosted Agent Hooks integrations that must return a canonical control
    +decision together with provider-specific evaluation receipts.
    +
    +## The gap
    +
    +Agent Hooks defines one closed control result:
    +
    +```text
    +intercept(context: AgentContext) -> Verdict
    +```
    +
    +That is the right in-process contract. A host needs one unambiguous decision and must
    +not allow transport metadata to change `allow`, `deny` or `transform`.
    +
    +Hosted and cross-process integrations often need to return additional data alongside
    +the Verdict:
    +
    +- an evaluation receipt proving which policy revisions were executed;
    +- a request or context binding;
    +- capability/freshness evidence;
    +- billing, correlation or service diagnostics;
    +- a signed proof over the decision and its authority state.
    +
    +Today those APIs have three unsatisfactory choices:
    +
    +1. return a bare Verdict and lose the additional response contract;
    +2. place provider fields inside Verdict, violating its closed schema;
    +3. return an ad hoc wrapper such as `{ "verdict": ..., "receipt": ... }`, requiring
    +   every consumer to know that it must extract `verdict` before using an Agent Hooks
    +   Verdict parser.
    +
    +The third option is safe when implemented carefully, but Agent Hooks does not name or
    +standardize it. A generic Agent Hooks transport client therefore cannot deserialize
    +the whole response even though the control decision itself is canonical.
    +
    +This problem is not specific to one cloud or policy engine. Any remote interceptor may
    +need a receipt while preserving one portable Verdict.
    +
    +## Goals
    +
    +1. Keep canonical `Verdict` closed and unchanged.
    +2. Define one optional transport envelope that can carry a canonical Verdict plus
    +   non-authoritative response data.
    +3. Make the existing `{ verdict, receipt }` shape directly representable.
    +4. Give SDKs one parser that safely accepts both a bare Verdict and the envelope.
    +5. Keep receipts out of host composition and enforcement semantics.
    +6. Preserve strict unknown-member rejection at the envelope boundary.
    +
    +## Non-goals
    +
    +- Standardizing policy-resource IDs, epochs, signatures or receipt contents.
    +- Turning receipts into passive telemetry or adding them to `InterceptionRecord`.
    +- Allowing arbitrary extra members on Verdict.
    +- Changing the in-process `Interceptor` callable or any composition profile.
    +- Requiring every interceptor or transport to emit a receipt.
    +
    +## Options
    +
    +### A. Keep wrappers outside Agent Hooks
    +
    +Every hosted API defines its own envelope and tells callers which property contains the
    +Verdict.
    +
    +**Advantages**
    +
    +- No spec or SDK work.
    +- Agent Hooks stays limited to the in-process control surface.
    +
    +**Costs**
    +
    +- Generic transport clients cannot recognize a common response shape.
    +- SDK documentation can easily claim a method returns Verdict when it actually returns
    +  an envelope.
    +- Each API reinvents unknown-member, metadata and fail-closed parsing rules.
    +
    +### B. Open Verdict to arbitrary additional properties
    +
    +Allow provider metadata directly on Verdict.
    +
    +**Advantages**
    +
    +- Existing Verdict parsers could accept one flat response object.
    +- Minimal wrapper ceremony.
    +
    +**Costs**
    +
    +- Destroys the closed decision boundary.
    +- Creates collisions with future Agent Hooks members.
    +- Makes it unclear whether a member affects enforcement.
    +- Weakens closed discriminated unions in generated SDKs.
    +
    +This option is rejected.
    +
    +### C. Add optional `receipt` and `extensions` members to Verdict
    +
    +Keep known members but expand Verdict itself.
    +
    +**Advantages**
    +
    +- One object crosses every boundary.
    +- Receipt is easy to discover.
    +
    +**Costs**
    +
    +- Still changes the canonical Verdict wire shape and every SDK type.
    +- In-process interceptors pay for transport concerns.
    +- Composition and record code must explicitly strip transport members.
    +
    +### D. Define a separate transport response envelope
    +
    +**Recommended.**
    +
    +Keep `Verdict` unchanged. Define a disjoint `InterceptorResponse` object:
    +
    +```json
    +{
    +  "verdict": {
    +    "decision": "deny",
    +    "reason": "policy_denied"
    +  },
    +  "receipt": {
    +    "receiptVersion": "provider-contract/1.0",
    +    "evaluationId": "evaluation-123"
    +  },
    +  "extensions": {
    +    "provider_name": {
    +      "requestId": "request-456"
    +    }
    +  }
    +}
    +```
    +
    +`verdict` is required. `receipt` and `extensions` are optional. At least one of them
    +SHOULD be present; otherwise a bare Verdict is the simpler representation.
    +
    +The envelope and Verdict are structurally disjoint: Verdict requires `decision`, while
    +the envelope requires `verdict` and forbids `decision` at its root.
    +
    +## Recommended normative semantics
    +
    +### 1. Two distinct parsers
    +
    +SDKs retain the strict Verdict parser:
    +
    +```text
    +parse_verdict(value) -> Verdict
    +```
    +
    +It accepts only the closed §5 Verdict and continues to reject an envelope.
    +
    +SDKs add:
    +
    +```text
    +parse_interceptor_response(value) -> InterceptorResponse
    +```
    +
    +It accepts either:
    +
    +- a bare §5 Verdict, normalized to `{ verdict: value }`; or
    +- the response envelope defined below.
    +
    +This distinction prevents existing code that promises "Verdict only" from silently
    +accepting transport metadata, while giving hosted clients a standard Agent Hooks-aware
    +response parser.
    +
    +### 2. Envelope shape
    +
    +```json
    +{
    +  "verdict": "<required canonical Verdict>",
    +  "receipt": "<optional JSON object>",
    +  "extensions": {
    +    "<namespace>": "<any JSON>"
    +  }
    +}
    +```
    +
    +Rules:
    +
    +- the root is closed: only `verdict`, `receipt` and `extensions` are allowed;
    +- `verdict` MUST pass every §5 validation rule;
    +- `receipt`, when present, MUST be a JSON object;
    +- `extensions`, when present, follows the §4.6 namespace grammar
    +  `^[a-z][a-z0-9_]*$`;
    +- duplicate JSON members at any envelope-owned object level MUST be rejected;
    +- the RFC 8785 canonical JSON size of `receipt` plus `extensions` MUST NOT exceed
    +  65536 bytes;
    +- SDKs MUST preserve receipt and extension JSON values without interpreting,
    +  normalizing or moving them into Verdict.
    +
    +The envelope has no independent version member. Like Verdict, its version is the Agent
    +Hooks spec version selected by the surrounding transport or the `AgentContext.spec`
    +used for the evaluation. A provider receipt can carry its own contract version.
    +
    +### 3. Enforcement boundary
    +
    +Only `response.verdict` participates in §6–§9 enforcement and composition.
    +
    +- A receipt or extension MUST NOT make a deny liftable, alter a transform, add result
    +  labels or change warning unioning.
    +- A host MUST validate/extract the Verdict before composition.
    +- A host that cannot parse the declared response form MUST apply §6.3 as an invalid
    +  interceptor result.
    +- A transport that declares the envelope form MUST fail closed when the envelope,
    +  receipt or extensions violate this contract, even if the nested Verdict alone is
    +  valid.
    +
    +The last rule prevents a caller from receiving a success-shaped decision with a
    +malformed or untrustworthy receipt that the API contract says is authoritative.
    +
    +### 4. In-process and remote boundaries
    +
    +The canonical in-process `Interceptor` callable remains:
    +
    +```text
    +intercept(context) -> Verdict
    +```
    +
    +A remote-backed in-process adapter:
    +
    +1. parses the remote body with `parse_interceptor_response`;
    +2. returns the normalized `.verdict` to the host emitter;
    +3. sends `.receipt` and `.extensions`, if needed, to the adapter's own transport or
    +   audit consumer.
    +
    +Agent Hooks does not require hosts to persist these fields and does not add them to the
    +payload-free `InterceptionRecord`.
    +
    +### 5. Receipt opacity and provider schemas
    +
    +`receipt` means "response data bound by the producer to this evaluation." Agent Hooks
    +does not claim that the receipt is signed, current or trustworthy.
    +
    +Providers SHOULD publish a closed schema for their receipt and SHOULD bind it to the
    +request/context and nested Verdict when it is used as evidence. Those provider rules
    +are outside Agent Hooks conformance.
    +
    +The generic SDK type is therefore an opaque JSON object. Generated service SDKs MAY
    +replace it with a stricter provider-specific type while retaining the same envelope.
    +
    +## Proposed schema
    +
    +Add `spec/schema/interceptor-response.schema.json`:
    +
    +```json
    +{
    +  "$schema": "https://json-schema.org/draft/2020-12/schema",
    +  "$id": "https://responsibleai.github.io/agent-hooks/schema/interceptor-response.schema.json",
    +  "title": "Agent Hooks Interceptor Response",
    +  "oneOf": [
    +    { "$ref": "verdict.schema.json" },
    +    {
    +      "type": "object",
    +      "required": ["verdict"],
    +      "properties": {
    +        "verdict": { "$ref": "verdict.schema.json" },
    +        "receipt": { "type": "object" },
    +        "extensions": {
    +          "type": "object",
    +          "propertyNames": {
    +            "pattern": "^[a-z][a-z0-9_]*$"
    +          },
    +          "additionalProperties": true
    +        }
    +      },
    +      "additionalProperties": false
    +    }
    +  ]
    +}
    +```
    +
    +The 64 KiB combined metadata bound is enforced by SDK parsers because JSON Schema
    +cannot express RFC 8785 byte length.
    +
    +## SDK surface
    +
    +Each SDK gains:
    +
    +- `InterceptorResponse` with `verdict`, optional opaque `receipt`, and optional
    +  namespaced `extensions`;
    +- `parse_interceptor_response` / idiomatic equivalent;
    +- construction from a bare Verdict;
    +- serialization that emits the envelope only when receipt/extensions are present.
    +
    +`Interceptor.intercept` and emitter registration continue to use Verdict.
    +
    +## Conformance and tests
    +
    +This optional artefact does not change host CTK execution. Cross-language fixtures
    +should live alongside schema/golden tests and cover:
    +
    +| Case | Expected result |
    +| --- | --- |
    +| bare allow Verdict | accepted and normalized |
    +| bare deny/transform Verdict | accepted and normalized without mutation |
    +| envelope with Verdict only | accepted; serializer SHOULD prefer bare Verdict |
    +| envelope with typed provider receipt | accepted and preserved byte-semantically |
    +| envelope with namespaced extensions | accepted and preserved |
    +| current Azure-style `{ verdict, receipt }` | accepted |

    Vendor name. Say an existing { verdict, receipt } wrapper. The inline schema earlier in this document also differs from the shipped spec/schema/interceptor-response.schema.json; make them match or point at the file.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    spec/AGENT-HOOKS-0.1.md:1
    @@ -529,6 +529,60 @@ them as `extensions.<interceptor-namespace>.source_labels` on later hooks whose
     `target` derives from that data. A host MUST NOT persist `result_labels` for an
     action that did not proceed (a `deny` that was not lifted).
     
    +### 5.5 Transport response envelope
    +
    +[Optional Transport Artefact]

    Two things. The spec defines only [Pure Specification] and [Default Implementation]; [Optional Transport Artefact] has no legend. Use an existing label or define the new one where the other two are introduced. And because P-005 is Draft, add directly under the heading: > Proposed under P-005 (Draft). Not part of the 0.1 contract until that proposal is decided.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    spec/AGENT-HOOKS-0.1.md:1
    @@ -529,6 +529,60 @@ them as `extensions.<interceptor-namespace>.source_labels` on later hooks whose
     `target` derives from that data. A host MUST NOT persist `result_labels` for an
     action that did not proceed (a `deny` that was not lifted).
     
    +### 5.5 Transport response envelope
    +
    +[Optional Transport Artefact]
    +
    +The canonical in-process interceptor return remains a §5 `Verdict`.
    +A hosted or cross-process interceptor transport MAY return an
    +`InterceptorResponse` envelope when it needs to carry response data
    +alongside the control decision:
    +
    +```jsonc
    +{
    +  "verdict": <canonical Verdict>,
    +  "receipt": { },                       // optional, provider-defined
    +  "extensions": {                       // optional
    +    "<namespace>": <any JSON>
    +  }
    +}
    +```
    +
    +The machine-readable schema is
    +`spec/schema/interceptor-response.schema.json`. The envelope root is
    +closed: only `verdict`, `receipt`, and `extensions` are permitted.
    +`verdict` is REQUIRED and MUST pass every §5 rule. `receipt`, when
    +present, MUST be a JSON object. `extensions`, when present, uses the
    +§4.6 namespace grammar. Duplicate members at any envelope-owned object

    envelope-owned is not defined, and the implemented rule is broader: from_json rejects duplicates at every object level of the text, including inside verdict, receipt and extensions values, while from_wire on a parsed value cannot see them at all. Suggested text: When the response is received as JSON text, a duplicate member at any object level of the text, including inside verdict, receipt and extensions, is invalid. A response received as an already-parsed value cannot carry duplicates; the receiving parser has already collapsed them. §7.7.6 states the same caveat for the declaration loader.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    spec/AGENT-HOOKS-0.1.md:1
    @@ -529,6 +529,60 @@ them as `extensions.<interceptor-namespace>.source_labels` on later hooks whose
     `target` derives from that data. A host MUST NOT persist `result_labels` for an
     action that did not proceed (a `deny` that was not lifted).
     
    +### 5.5 Transport response envelope
    +
    +[Optional Transport Artefact]
    +
    +The canonical in-process interceptor return remains a §5 `Verdict`.
    +A hosted or cross-process interceptor transport MAY return an
    +`InterceptorResponse` envelope when it needs to carry response data
    +alongside the control decision:
    +
    +```jsonc
    +{
    +  "verdict": <canonical Verdict>,
    +  "receipt": { },                       // optional, provider-defined
    +  "extensions": {                       // optional
    +    "<namespace>": <any JSON>
    +  }
    +}
    +```
    +
    +The machine-readable schema is
    +`spec/schema/interceptor-response.schema.json`. The envelope root is
    +closed: only `verdict`, `receipt`, and `extensions` are permitted.
    +`verdict` is REQUIRED and MUST pass every §5 rule. `receipt`, when
    +present, MUST be a JSON object. `extensions`, when present, uses the
    +§4.6 namespace grammar. Duplicate members at any envelope-owned object
    +level are invalid.
    +
    +The combined UTF-8 byte length of the RFC 8785 canonical JSON

    Say the bound is the sum of the two canonical forms, and say how it relates to the §5.3 evidence cap (10,240 bytes) so a reader knows the two are independent. Also state here that the envelope carries no version of its own and rides on the spec wire version; the proposal says it and the spec does not.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    spec/AGENT-HOOKS-0.1.md:1
    @@ -529,6 +529,60 @@ them as `extensions.<interceptor-namespace>.source_labels` on later hooks whose
     `target` derives from that data. A host MUST NOT persist `result_labels` for an
     action that did not proceed (a `deny` that was not lifted).
     
    +### 5.5 Transport response envelope
    +
    +[Optional Transport Artefact]
    +
    +The canonical in-process interceptor return remains a §5 `Verdict`.
    +A hosted or cross-process interceptor transport MAY return an
    +`InterceptorResponse` envelope when it needs to carry response data
    +alongside the control decision:
    +
    +```jsonc
    +{
    +  "verdict": <canonical Verdict>,
    +  "receipt": { },                       // optional, provider-defined
    +  "extensions": {                       // optional
    +    "<namespace>": <any JSON>
    +  }
    +}
    +```
    +
    +The machine-readable schema is
    +`spec/schema/interceptor-response.schema.json`. The envelope root is
    +closed: only `verdict`, `receipt`, and `extensions` are permitted.
    +`verdict` is REQUIRED and MUST pass every §5 rule. `receipt`, when
    +present, MUST be a JSON object. `extensions`, when present, uses the
    +§4.6 namespace grammar. Duplicate members at any envelope-owned object
    +level are invalid.
    +
    +The combined UTF-8 byte length of the RFC 8785 canonical JSON
    +serialization of `receipt` and `extensions` MUST NOT exceed 65536
    +bytes. SDK response parsers enforce this bound; JSON Schema cannot
    +express canonical byte length.
    +
    +Only the nested `verdict` participates in §6–§9 enforcement and
    +composition. A receipt or extension cannot alter the decision,
    +approval, transform, warnings, evidence, or result labels. A transport
    +that declares the envelope form MUST treat a malformed envelope as an

    No reserved reason covers this. §11 defines host_error:verdict_invalid as a §5 failure only, and §6.3 has three rows without saying which applies. The Rust parser already emits VerdictInvalid, so the spec should say so: MUST treat a malformed envelope as {"decision": "deny", "reason": "host_error:verdict_invalid"} per §6.3, and widen the §11 cause to fails §5 validation, or a transport response that fails §5.5 envelope validation. Mirror the text in spec/reserved-reasons.json. A transport that declares the envelope form also needs a definition; nothing says where a transport declares it.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    sdk/rust/core/src/response.rs:1
    @@ -0,0 +1,349 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT License.
    +//! Optional hosted/cross-process interceptor response envelope (§5.5).
    +
    +use crate::types::{HostError, Verdict};
    +use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
    +use serde::Serialize;
    +use serde_json::{Map, Value};
    +use std::collections::BTreeMap;
    +use std::fmt;
    +
    +/// Maximum combined RFC 8785 canonical byte length of `receipt` and
    +/// `extensions` in an interceptor response (§5.5).
    +pub const RESPONSE_METADATA_MAX_BYTES: usize = 65_536;
    +
    +/// A normalized transport response. A bare Verdict parses to this shape with
    +/// no receipt or extensions; serialization emits the bare Verdict when both
    +/// optional members are absent (§5.5).
    +#[derive(Debug, Clone, PartialEq)]
    +pub struct InterceptorResponse {
    +    pub verdict: Verdict,
    +    pub receipt: Option<Map<String, Value>>,
    +    pub extensions: BTreeMap<String, Value>,
    +}
    +
    +impl InterceptorResponse {
    +    /// Parse a JSON value. Use [`from_json`] when duplicate-member rejection
    +    /// must be enforced on raw transport text.
    +    pub fn from_wire(raw: &Value) -> Result<Self, (HostError, String)> {
    +        let Some(obj) = raw.as_object() else {
    +            return Err((
    +                HostError::VerdictInvalid,
    +                "interceptor response must be a JSON object (§5.5)".into(),
    +            ));
    +        };
    +        if !obj.contains_key("verdict") {
    +            validate_verdict_members(obj)?;
    +            return Ok(Self {
    +                verdict: crate::verdict::from_wire(raw)?,
    +                receipt: None,
    +                extensions: BTreeMap::new(),
    +            });
    +        }
    +
    +        for key in obj.keys() {
    +            if !matches!(key.as_str(), "verdict" | "receipt" | "extensions") {
    +                return Err((
    +                    HostError::VerdictInvalid,
    +                    format!("interceptor response contains unknown root member {key:?} (§5.5)"),
    +                ));
    +            }
    +        }
    +        let verdict_obj = obj["verdict"].as_object().ok_or((
    +            HostError::VerdictInvalid,
    +            "interceptor response verdict must be an object (§5.5)".into(),
    +        ))?;
    +        validate_verdict_members(verdict_obj)?;
    +        let verdict = crate::verdict::from_wire(&obj["verdict"])?;
    +        let receipt = match obj.get("receipt") {
    +            None => None,
    +            Some(Value::Object(value)) => Some(value.clone()),
    +            Some(_) => {
    +                return Err((
    +                    HostError::VerdictInvalid,
    +                    "interceptor response receipt must be an object (§5.5)".into(),
    +                ))
    +            }
    +        };
    +        let extensions = match obj.get("extensions") {
    +            None => BTreeMap::new(),
    +            Some(Value::Object(value)) => {
    +                let mut out = BTreeMap::new();
    +                for (namespace, item) in value {
    +                    if !valid_namespace(namespace) {
    +                        return Err((
    +                            HostError::VerdictInvalid,
    +                            format!(
    +                                "interceptor response extension namespace {namespace:?} is invalid (§5.5)"
    +                            ),
    +                        ));
    +                    }
    +                    out.insert(namespace.clone(), item.clone());
    +                }
    +                out
    +            }
    +            Some(_) => {
    +                return Err((
    +                    HostError::VerdictInvalid,
    +                    "interceptor response extensions must be an object (§5.5)".into(),
    +                ))
    +            }
    +        };
    +
    +        let metadata_bytes = receipt
    +            .as_ref()
    +            .map(|value| crate::canonical::canonical_json(&Value::Object(value.clone())).len())
    +            .unwrap_or_default()
    +            + if extensions.is_empty() {
    +                0
    +            } else {
    +                crate::canonical::canonical_json(
    +                    &serde_json::to_value(&extensions).expect("extensions serialize"),
    +                )
    +                .len()
    +            };
    +        if metadata_bytes > RESPONSE_METADATA_MAX_BYTES {
    +            return Err((
    +                HostError::VerdictInvalid,
    +                format!(
    +                    "interceptor response metadata canonical size {metadata_bytes} exceeds {RESPONSE_METADATA_MAX_BYTES} bytes (§5.5)"
    +                ),
    +            ));
    +        }
    +
    +        Ok(Self {
    +            verdict,
    +            receipt,
    +            extensions,
    +        })
    +    }
    +
    +    /// Parse raw JSON with duplicate-member, depth and size checks.
    +    pub fn from_json(text: &str) -> Result<Self, (HostError, String)> {
    +        let raw = parse_checked(text)?;
    +        Self::from_wire(&raw)
    +    }
    +
    +    /// Always serialize the normalized envelope shape.
    +    pub fn to_envelope_value(&self) -> Value {
    +        let mut out = Map::new();
    +        out.insert(
    +            "verdict".into(),
    +            serde_json::to_value(&self.verdict).expect("verdict serialize"),
    +        );
    +        if let Some(receipt) = &self.receipt {
    +            out.insert("receipt".into(), Value::Object(receipt.clone()));
    +        }
    +        if !self.extensions.is_empty() {
    +            out.insert(
    +                "extensions".into(),
    +                serde_json::to_value(&self.extensions).expect("extensions serialize"),
    +            );
    +        }
    +        Value::Object(out)
    +    }
    +
    +    /// Serialize a bare Verdict when no transport metadata is present.
    +    pub fn to_wire_value(&self) -> Value {
    +        if self.receipt.is_none() && self.extensions.is_empty() {
    +            serde_json::to_value(&self.verdict).expect("verdict serialize")
    +        } else {
    +            self.to_envelope_value()
    +        }
    +    }
    +}
    +
    +impl Serialize for InterceptorResponse {
    +    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    +        self.to_wire_value().serialize(serializer)
    +    }
    +}
    +
    +fn validate_verdict_members(value: &Map<String, Value>) -> Result<(), (HostError, String)> {
    +    for key in value.keys() {
    +        if !matches!(
    +            key.as_str(),
    +            "decision"
    +                | "reason"
    +                | "message"
    +                | "warnings"
    +                | "approval"
    +                | "transform"
    +                | "evidence"
    +                | "result_labels"
    +        ) {
    +            return Err((
    +                HostError::VerdictInvalid,
    +                format!("verdict contains unknown member {key:?} (§5)"),
    +            ));
    +        }
    +    }
    +    for (member, allowed) in [
    +        ("transform", &["path", "value"][..]),
    +        ("evidence", &["artefact", "verification_pointers"][..]),
    +    ] {
    +        if let Some(object) = value.get(member).and_then(Value::as_object) {
    +            require_members(object, allowed)?;
    +        }
    +    }
    +    if let Some(warnings) = value.get("warnings").and_then(Value::as_array) {
    +        for warning in warnings {
    +            if let Some(object) = warning.as_object() {
    +                require_members(object, &["reason", "message"])?;
    +            }
    +        }
    +    }
    +    Ok(())
    +}
    +
    +fn require_members(
    +    value: &Map<String, Value>,
    +    allowed: &[&str],
    +) -> Result<(), (HostError, String)> {
    +    if value.keys().any(|key| !allowed.contains(&key.as_str())) {
    +        return Err((
    +            HostError::VerdictInvalid,
    +            "verdict contains an unknown nested member (§5)".into(),
    +        ));
    +    }
    +    Ok(())
    +}
    +
    +fn valid_namespace(value: &str) -> bool {
    +    let mut chars = value.chars();
    +    chars.next().is_some_and(|c| c.is_ascii_lowercase())
    +        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
    +}
    +
    +struct Checked;
    +
    +impl<'de> DeserializeSeed<'de> for Checked {
    +    type Value = Value;
    +    fn deserialize<D: de::Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
    +        d.deserialize_any(self)
    +    }
    +}
    +
    +impl<'de> Visitor<'de> for Checked {
    +    type Value = Value;
    +
    +    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    +        f.write_str("a JSON value")
    +    }
    +    fn visit_bool<E: de::Error>(self, v: bool) -> Result<Value, E> {
    +        Ok(Value::Bool(v))
    +    }
    +    fn visit_i64<E: de::Error>(self, v: i64) -> Result<Value, E> {
    +        Ok(Value::from(v))
    +    }
    +    fn visit_u64<E: de::Error>(self, v: u64) -> Result<Value, E> {
    +        Ok(Value::from(v))
    +    }
    +    fn visit_f64<E: de::Error>(self, v: f64) -> Result<Value, E> {

    Receipts are not passed through byte for byte. serde_json turns integers outside i64/u64 into f64 and the JCS writer casts every integer to f64 before formatting. Repro: {"verdict":{"decision":"allow"},"receipt":{"n":18446744073709551616,"f":1E2}} parses and to_envelope_value emits "receipt":{"f":100.0,"n":1.8446744073709552e+19}. A provider signature over that receipt will not verify, and the host cannot tell. The existing ffi_surface::canonical_json rejects the same literal via canonical::scan_raw_integer_domain. Run that scan in from_json after parse_checked, add a Value walk over receipt and extensions for the from_wire path mirroring check_i_json, and add fixture cases for 18446744073709551616 and 9007199254740993. If byte preservation is not the goal, change the proposal row and §5.5 to say receipts are re-serialised as I-JSON and providers sign a canonical form they define.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    sdk/rust/core/src/response.rs:1
    @@ -0,0 +1,349 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT License.
    +//! Optional hosted/cross-process interceptor response envelope (§5.5).
    +
    +use crate::types::{HostError, Verdict};
    +use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
    +use serde::Serialize;
    +use serde_json::{Map, Value};
    +use std::collections::BTreeMap;
    +use std::fmt;
    +
    +/// Maximum combined RFC 8785 canonical byte length of `receipt` and
    +/// `extensions` in an interceptor response (§5.5).
    +pub const RESPONSE_METADATA_MAX_BYTES: usize = 65_536;
    +
    +/// A normalized transport response. A bare Verdict parses to this shape with
    +/// no receipt or extensions; serialization emits the bare Verdict when both
    +/// optional members are absent (§5.5).
    +#[derive(Debug, Clone, PartialEq)]
    +pub struct InterceptorResponse {
    +    pub verdict: Verdict,
    +    pub receipt: Option<Map<String, Value>>,
    +    pub extensions: BTreeMap<String, Value>,
    +}
    +
    +impl InterceptorResponse {
    +    /// Parse a JSON value. Use [`from_json`] when duplicate-member rejection
    +    /// must be enforced on raw transport text.
    +    pub fn from_wire(raw: &Value) -> Result<Self, (HostError, String)> {
    +        let Some(obj) = raw.as_object() else {
    +            return Err((
    +                HostError::VerdictInvalid,
    +                "interceptor response must be a JSON object (§5.5)".into(),
    +            ));
    +        };
    +        if !obj.contains_key("verdict") {
    +            validate_verdict_members(obj)?;

    This makes the response gate stricter than the strict gate on the same bare Verdict. validate_verdict accepts {"decision":"allow","foo":1} and {"decision":"allow","decision":"deny"}; normalize_interceptor_response rejects both. Every SDK inherits the split through the FFI. §5.5 says both gates apply every §5 rule, and verdict.schema.json is additionalProperties:false, so the strict gate is the lax one. Preferred: move the closed-member checks and the duplicate-key parse into verdict::from_wire / ffi_surface::validate_verdict, add #[serde(deny_unknown_fields)] to Evidence, delete validate_verdict_members, add a CHANGELOG line, and add fixture cases bare_verdict_unknown_member and duplicate_nested_verdict_member.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    sdk/rust/core/src/response.rs:1
    @@ -0,0 +1,349 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT License.
    +//! Optional hosted/cross-process interceptor response envelope (§5.5).
    +
    +use crate::types::{HostError, Verdict};
    +use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
    +use serde::Serialize;
    +use serde_json::{Map, Value};
    +use std::collections::BTreeMap;
    +use std::fmt;
    +
    +/// Maximum combined RFC 8785 canonical byte length of `receipt` and
    +/// `extensions` in an interceptor response (§5.5).
    +pub const RESPONSE_METADATA_MAX_BYTES: usize = 65_536;
    +
    +/// A normalized transport response. A bare Verdict parses to this shape with
    +/// no receipt or extensions; serialization emits the bare Verdict when both
    +/// optional members are absent (§5.5).
    +#[derive(Debug, Clone, PartialEq)]
    +pub struct InterceptorResponse {
    +    pub verdict: Verdict,
    +    pub receipt: Option<Map<String, Value>>,
    +    pub extensions: BTreeMap<String, Value>,
    +}
    +
    +impl InterceptorResponse {
    +    /// Parse a JSON value. Use [`from_json`] when duplicate-member rejection
    +    /// must be enforced on raw transport text.
    +    pub fn from_wire(raw: &Value) -> Result<Self, (HostError, String)> {

    No depth bound on this path. A receipt holding a Value nested 200,000 deep aborts the process with a stack overflow; from_json is only safe because serde_json's default recursion limit of 128 happens to apply. Call crate::canonical::check_depth(raw) first, map to VerdictInvalid, and add a test that a 200-deep receipt returns an error rather than aborting. The from_json doc comment should then say where each check lives.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    sdk/rust/core/src/response.rs:1
    @@ -0,0 +1,349 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT License.
    +//! Optional hosted/cross-process interceptor response envelope (§5.5).
    +
    +use crate::types::{HostError, Verdict};
    +use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
    +use serde::Serialize;
    +use serde_json::{Map, Value};
    +use std::collections::BTreeMap;
    +use std::fmt;
    +
    +/// Maximum combined RFC 8785 canonical byte length of `receipt` and
    +/// `extensions` in an interceptor response (§5.5).
    +pub const RESPONSE_METADATA_MAX_BYTES: usize = 65_536;
    +
    +/// A normalized transport response. A bare Verdict parses to this shape with
    +/// no receipt or extensions; serialization emits the bare Verdict when both
    +/// optional members are absent (§5.5).
    +#[derive(Debug, Clone, PartialEq)]
    +pub struct InterceptorResponse {
    +    pub verdict: Verdict,
    +    pub receipt: Option<Map<String, Value>>,
    +    pub extensions: BTreeMap<String, Value>,
    +}
    +
    +impl InterceptorResponse {
    +    /// Parse a JSON value. Use [`from_json`] when duplicate-member rejection
    +    /// must be enforced on raw transport text.
    +    pub fn from_wire(raw: &Value) -> Result<Self, (HostError, String)> {
    +        let Some(obj) = raw.as_object() else {
    +            return Err((
    +                HostError::VerdictInvalid,
    +                "interceptor response must be a JSON object (§5.5)".into(),
    +            ));
    +        };
    +        if !obj.contains_key("verdict") {
    +            validate_verdict_members(obj)?;
    +            return Ok(Self {
    +                verdict: crate::verdict::from_wire(raw)?,
    +                receipt: None,
    +                extensions: BTreeMap::new(),
    +            });
    +        }
    +
    +        for key in obj.keys() {
    +            if !matches!(key.as_str(), "verdict" | "receipt" | "extensions") {
    +                return Err((
    +                    HostError::VerdictInvalid,
    +                    format!("interceptor response contains unknown root member {key:?} (§5.5)"),

    The offending key is echoed into the error detail unbounded here and at lines 78 and 274, and these checks run before the 64 KiB bound. A 1 MB unknown root member yields a 1 MB host_error detail that hosts log or place on records. Truncate to 64 chars with a marker, or report only the JSON pointer of the enclosing object, as canonical::validate_envelope does.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    sdk/rust/core/src/response.rs:1
    @@ -0,0 +1,349 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT License.
    +//! Optional hosted/cross-process interceptor response envelope (§5.5).
    +
    +use crate::types::{HostError, Verdict};
    +use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
    +use serde::Serialize;
    +use serde_json::{Map, Value};
    +use std::collections::BTreeMap;
    +use std::fmt;
    +
    +/// Maximum combined RFC 8785 canonical byte length of `receipt` and
    +/// `extensions` in an interceptor response (§5.5).
    +pub const RESPONSE_METADATA_MAX_BYTES: usize = 65_536;
    +
    +/// A normalized transport response. A bare Verdict parses to this shape with
    +/// no receipt or extensions; serialization emits the bare Verdict when both
    +/// optional members are absent (§5.5).
    +#[derive(Debug, Clone, PartialEq)]
    +pub struct InterceptorResponse {
    +    pub verdict: Verdict,
    +    pub receipt: Option<Map<String, Value>>,
    +    pub extensions: BTreeMap<String, Value>,
    +}
    +
    +impl InterceptorResponse {
    +    /// Parse a JSON value. Use [`from_json`] when duplicate-member rejection
    +    /// must be enforced on raw transport text.
    +    pub fn from_wire(raw: &Value) -> Result<Self, (HostError, String)> {
    +        let Some(obj) = raw.as_object() else {
    +            return Err((
    +                HostError::VerdictInvalid,
    +                "interceptor response must be a JSON object (§5.5)".into(),
    +            ));
    +        };
    +        if !obj.contains_key("verdict") {
    +            validate_verdict_members(obj)?;
    +            return Ok(Self {
    +                verdict: crate::verdict::from_wire(raw)?,
    +                receipt: None,
    +                extensions: BTreeMap::new(),
    +            });
    +        }
    +
    +        for key in obj.keys() {
    +            if !matches!(key.as_str(), "verdict" | "receipt" | "extensions") {
    +                return Err((
    +                    HostError::VerdictInvalid,
    +                    format!("interceptor response contains unknown root member {key:?} (§5.5)"),
    +                ));
    +            }
    +        }
    +        let verdict_obj = obj["verdict"].as_object().ok_or((
    +            HostError::VerdictInvalid,
    +            "interceptor response verdict must be an object (§5.5)".into(),
    +        ))?;
    +        validate_verdict_members(verdict_obj)?;
    +        let verdict = crate::verdict::from_wire(&obj["verdict"])?;
    +        let receipt = match obj.get("receipt") {
    +            None => None,
    +            Some(Value::Object(value)) => Some(value.clone()),

    The receipt is cloned here, each extension value at line 82, and two more owned copies are built at lines 96 and 102 before the length is compared at line 106. Compute canonical_json on the borrowed values first, return the size error, then clone into the struct.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    conformance/golden/interceptor-response.json:1
    @@ -0,0 +1,75 @@
    +{
    +  "valid": [
    +    {
    +      "name": "empty_receipt",
    +      "input": "{\"verdict\":{\"decision\":\"allow\"},\"receipt\":{}}",
    +      "normalized": "{\"verdict\":{\"decision\":\"allow\"},\"receipt\":{}}"
    +    },
    +    {
    +      "name": "omitted_transform_value",
    +      "input": "{\"verdict\":{\"decision\":\"transform\",\"transform\":{\"path\":\"$target\"}},\"receipt\":{}}",
    +      "normalized": "{\"verdict\":{\"decision\":\"transform\",\"transform\":{\"path\":\"$target\"}},\"receipt\":{}}"
    +    },
    +    {
    +      "name": "bare_allow",
    +      "input": "{\"decision\":\"allow\"}",
    +      "normalized": "{\"verdict\":{\"decision\":\"allow\"}}"
    +    },
    +    {
    +      "name": "azure_style_receipt",

    Vendor name in a shared fixture. Rename to provider_receipt. The content already uses the neutral provider/1.0.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    conformance/golden/interceptor-response.json:1
    @@ -0,0 +1,75 @@
    +{
    +  "valid": [
    +    {
    +      "name": "empty_receipt",
    +      "input": "{\"verdict\":{\"decision\":\"allow\"},\"receipt\":{}}",
    +      "normalized": "{\"verdict\":{\"decision\":\"allow\"},\"receipt\":{}}"
    +    },
    +    {
    +      "name": "omitted_transform_value",
    +      "input": "{\"verdict\":{\"decision\":\"transform\",\"transform\":{\"path\":\"$target\"}},\"receipt\":{}}",
    +      "normalized": "{\"verdict\":{\"decision\":\"transform\",\"transform\":{\"path\":\"$target\"}},\"receipt\":{}}"
    +    },
    +    {
    +      "name": "bare_allow",
    +      "input": "{\"decision\":\"allow\"}",
    +      "normalized": "{\"verdict\":{\"decision\":\"allow\"}}"
    +    },
    +    {
    +      "name": "azure_style_receipt",
    +      "input": "{\"verdict\":{\"decision\":\"deny\",\"reason\":\"policy_denied\"},\"receipt\":{\"receiptVersion\":\"provider/1.0\",\"evaluationId\":\"evaluation-1\"}}",
    +      "normalized": "{\"verdict\":{\"decision\":\"deny\",\"reason\":\"policy_denied\"},\"receipt\":{\"evaluationId\":\"evaluation-1\",\"receiptVersion\":\"provider/1.0\"}}"
    +    },
    +    {
    +      "name": "namespaced_extensions",
    +      "input": "{\"verdict\":{\"decision\":\"allow\"},\"extensions\":{\"provider_name\":{\"requestId\":\"request-1\"}}}",
    +      "normalized": "{\"verdict\":{\"decision\":\"allow\"},\"extensions\":{\"provider_name\":{\"requestId\":\"request-1\"}}}"
    +    }
    +  ],
    +  "invalid": [
    +    {
    +      "name": "unknown_warning_member",
    +      "input": "{\"verdict\":{\"decision\":\"allow\",\"warnings\":[{\"transport\":\"discarded\"}]}}"
    +    },
    +    {
    +      "name": "unknown_transform_member",
    +      "input": "{\"verdict\":{\"decision\":\"transform\",\"transform\":{\"path\":\"$target\",\"value\":1,\"unexpected\":true}}}"
    +    },
    +    {
    +      "name": "unknown_evidence_member",
    +      "input": "{\"verdict\":{\"decision\":\"allow\",\"evidence\":{\"unexpected\":true}}}"
    +    },
    +    {
    +      "name": "unknown_root_member",
    +      "input": "{\"verdict\":{\"decision\":\"allow\"},\"transport\":{}}"
    +    },
    +    {
    +      "name": "root_decision_and_verdict",
    +      "input": "{\"decision\":\"allow\",\"verdict\":{\"decision\":\"allow\"}}"
    +    },
    +    {
    +      "name": "bare_verdict_with_receipt",
    +      "input": "{\"decision\":\"allow\",\"receipt\":{}}"
    +    },
    +    {
    +      "name": "nested_verdict_unknown_member",
    +      "input": "{\"verdict\":{\"decision\":\"allow\",\"transport\":{}}}"
    +    },
    +    {
    +      "name": "missing_verdict",
    +      "input": "{\"receipt\":{}}"
    +    },
    +    {
    +      "name": "non_object_receipt",
    +      "input": "{\"verdict\":{\"decision\":\"allow\"},\"receipt\":\"opaque\"}"
    +    },
    +    {
    +      "name": "invalid_extension_namespace",
    +      "input": "{\"verdict\":{\"decision\":\"allow\"},\"extensions\":{\"Provider-Name\":{}}}"
    +    },
    +    {
    +      "name": "duplicate_root_member",

    Coverage gaps against §5.5. Add: metadata_at_limit (receipt {"p":"x"*65528}, canonical size exactly 65536, valid) and metadata_over_limit (65529, invalid), or build both from the constant in each SDK and correct the CHANGELOG claim; duplicate_receipt_member, duplicate_extension_member, duplicate_nested_verdict_member; non_object_verdict {"verdict":"allow"}; nested_verdict_invalid_decision, nested_verdict_transform_without_body, nested_verdict_host_error_reason. The core rejects each today; nothing pins it across SDKs. Add the fixture to the golden inventory in HARNESS.md and consider pinning error codes so the five SDKs map the same input to the same class.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    README.md:1
    @@ -43,6 +43,17 @@ or whose interceptor raises, times out or returns an invalid verdict,
     denies with a reserved `host_error:*` reason (§6.3, §11). Zero
     registered interceptors in `enforce` mode denies too (§7).
     
    +Hosted transports that need to return provider-specific response data can use the

    This reads as a shipped feature. Say: A proposal (P-005, Draft) adds an optional response envelope for hosted transports ... The SDKs carry a prototype parser ... The shape may change before the proposal is decided. and link the proposal.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    CHANGELOG.md:1
    @@ -5,6 +5,22 @@ User-visible changes to the spec and SDKs. Versioning rules:
     
     ## Unreleased
     
    +- Spec §5.5 adds an optional hosted/cross-process `InterceptorResponse` envelope:

    Say Spec §5.5 (proposed under P-005, Draft) adds .... Further down, kept in drift says the opposite of what is meant, and one bullet describes fixes to code that never shipped; fold those into the feature bullet.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on code on Oct 14, 2026 07:43 UTC
    Code Review
    CHANGELOG.md:1
    @@ -5,6 +5,22 @@ User-visible changes to the spec and SDKs. Versioning rules:
     
     ## Unreleased
     
    +- Spec §5.5 adds an optional hosted/cross-process `InterceptorResponse` envelope:
    +  `{verdict, receipt?, extensions?}`. Canonical `Verdict`, in-process interceptor
    +  signatures, composition and records are unchanged. The envelope root is closed,
    +  receipts are opaque objects, extensions use the existing namespace grammar and
    +  combined transport metadata is bounded at 64 KiB canonical JSON.
    +- Rust, Python, TypeScript, .NET and Go add `InterceptorResponse` plus a normalizing
    +  parser that accepts either a bare Verdict or the envelope. The Rust core remains the
    +  source of truth through PyO3, napi-rs and the C ABI. Shared fixtures pin Azure-style

    Vendor name, and the claim is not true yet: no shared fixture pins the metadata bound. Say Shared fixtures pin the existing { verdict, receipt } response shape, namespaced extensions and duplicate rejection and add the bound cases, or leave the bound out of the sentence.

    MohammadHaroonAbuomar MohammadHaroonAbuomar requested changes on Oct 14, 2026 07:43 UTC
    Changes Requested Reviewer

    Thanks Liam. This is a well built prototype, and the envelope keeps Verdict closed as promised. I ran the spec text, the Rust core, all five bindings, the fixture and the docs through a full review with an adversarial pass on the untrusted path. Request changes for the items below. Inline comments carry the detail and the exact fix.

    Blocking:

    1. Decide the proposal before the spec text lands. P-005 is Draft and still lists receipt vs metadata, the verdict-only envelope and the 64 KiB bound as open, while §5.5 lands MUST text and public SDK types in five languages. Either record the decision in this PR and set P-005 to Decided, or hold the spec section and SDK surface until it is decided. I lean to recording the decision here so the stack ships together. Mohammad has the final say on the shape.
    2. Receipt and extensions are rewritten, not passed through. Integers above 2^53 and exponent literals come back changed after the host re-serialises, so a provider signature over a receipt will not verify. The repo already has the bigint_json rule in canonical; the new gate must apply it. Inline on response.rs.
    3. The response gate and the strict Verdict gate disagree on the same bare Verdict. Unknown members and duplicate keys pass validate_verdict and fail normalize_interceptor_response. Pick one behaviour for both. Inline on response.rs.
    4. Spec text gaps: no reserved reason covers a malformed envelope; the duplicate-member rule uses an undefined term and omits the text-path caveat; §5.5 needs a Draft marker and the new section label is not defined anywhere. Inline on the spec.
    5. Fixture gaps: no case for the 64 KiB bound although the CHANGELOG says there is; duplicates only tested at the root; no nested Verdict that fails a semantic §5 rule; no non-object verdict. Inline on the fixture.
    6. sdk/python/python/agent_hooks/_core.pyi was not updated. Add def normalize_interceptor_response(response_json: str, /) -> str: ... after validate_verdict. mypy fails on response.py without it.
    7. Product names. The fixture case azure_style_receipt, CHANGELOG line 15, P-005 line 303 and the PR body name a vendor. Rename the case to provider_receipt and say "an existing { verdict, receipt } wrapper". Product names stay out of the spec, fixtures and docs.
    8. README and CHANGELOG present the envelope as shipped. Say it is proposed under P-005 (Draft) and may change.
    9. Commit hygiene. Retitle the PR as a conventional commit (feat(spec): ...), and drop the Co-authored-by and Copilot-Session trailers from the three commits. The squash copies them otherwise.

    Non-blocking, worth doing in the same pass:

  • Error details echo the offending key unbounded (response.rs 49, 78, 274). Truncate to 64 chars or report the pointer only.

  • from_wire(&Value) has no depth bound; a deep receipt aborts the process. Call check_depth first.

  • The size bound runs after three copies of the metadata. Measure on the borrowed values first.

  • validate_verdict_members is a second hand-kept copy of the Verdict member set. Fold it into verdict::from_wire so the two gates share one validator.

  • The 64 KiB bound should say it is a sum and how it relates to the §5.3 evidence cap. Reserved namespaces (agent_hooks, ctk) should be addressed for response extensions. "A transport that declares the envelope form" needs a definition. §5 intro and §1.1 still say an interceptor MUST return a Verdict with no cross-reference. The spec should state that the envelope rides on the spec wire version.

  • The P-005 inline schema differs from the shipped file. The Status line has an em dash. "Raised by" names no one.

  • TypeScript treats receipt: null differently from the other SDKs. Go decodes with json.Number while the rest of the Go SDK does not. Rust alone exposes an always-envelope serializer. Python raises a private exception type from the response parser.

  • The fixture pins no error codes for invalid responses, and unparseable JSON maps to a different code than ah_validate_verdict.

  • "kept in drift" in the CHANGELOG says the opposite of what is meant, and one bullet describes fixes to code that never shipped.
  • CI is green at c567d0b. Once the blocking items are in I will re-run the review and approve.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on Oct 14, 2026 21:26 UTC
    Reviewer

    Re-reviewed at 31f190e against the 16 asks. Thanks Liam, this is thorough.

    Addressed: every spec text ask (reserved reason, duplicate rule, section label and Draft marker, 64 KiB sum and its relation to the evidence cap, version model, transport definition, cross-references, reserved namespaces, host handling of receipt and extensions); every core ask (bigint and exponent literals rejected so receipts survive re-serialisation, one shared validator for both gates, depth bound, bounded error detail, size bound before cloning); every fixture and SDK ask (the new cases, HARNESS.md, the Python stub, TypeScript null handling, Go decoding, the exported Python exception); the vendor name, the README and CHANGELOG wording, the commit subjects and trailers.

    Accepted as is: the Rust-only always-envelope serializer stays, with the reason you gave.

    One item is open and it is the maintainer's, not yours: P-005 is still Draft while §5.5, the schema and the SDK surface land in this PR marked as proposed. The request-changes stays until Mohammad records the decision (set P-005 to Decided and keep the text, or hold the section and SDK surface until then). Once he does, this is an approve from my side with no further asks.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on Oct 15, 2026 08:22 UTC
    Contributor

    Liam, thanks for the thorough update. All the review asks are closed and the implementation is in good shape. One design change before I decide P-005.

    Drop receipt and keep extensions as the only carrier. A receipt is provider data, so it belongs under the provider's namespace: extensions.<provider>.receipt. Everything the proposal says about receipts already holds for extensions: opaque, re-serialised as I-JSON, never interpreted, the shared 64 KiB bound, no effect on enforcement, and signing over a provider-defined canonical form. The namespace rule also gives us two things receipt does not: two providers in one hosted stack cannot collide, and a reader can always tell who produced a field.

    What we give up is small. A generic client has to know the provider's namespace to find a receipt, and the service that already emits { verdict, receipt } renames one member. Neither is a spec concern.

    So the envelope becomes { "verdict": ..., "extensions": { "<ns>": ... } } with a closed root of two members. The receipt section of P-005 turns into guidance for providers on carrying a receipt under their namespace, and the schema, fixture cases and the five SDK types lose the receipt member. Keep the other four choices as proposed: an envelope with only verdict is valid, the 64 KiB bound on canonical extensions, bare Verdict when there are no extensions, I-JSON values with unsafe integer literals rejected.

    With that change I will record P-005 as decided on this PR and we land the spec text, schema and SDKs together. The branch also needs a rebase; main moved under README and CHANGELOG this morning.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on Oct 15, 2026 08:30 UTC
    Contributor

    One housekeeping note: P-005 is already taken by #104 (retractability as a declared capability, opened October 1). Please renumber this proposal to P-006 in the next push: the file name, the Status line references, and the mentions in the spec section, schema description, README and CHANGELOG.

    MohammadHaroonAbuomar MohammadHaroonAbuomar commented on Oct 15, 2026 20:09 UTC
    Contributor

    Checked 165a818 against the direction above. The design is done: the root is verdict and extensions, receipts live under the provider's namespace, the 64 KiB bound is over the canonical extensions object, the fixture pins the limit, the legacy root receipt is refused, all five SDK types match, and P-006 is the number everywhere. CI is green.

    Decision recorded here: P-006 is decided as of 2026-10-15 with option D and the choices listed in the proposal, with extensions as the only carrier.

    One more push and I approve:

  • Set the Status line in docs/proposals/P-006-interceptor-response-envelope.md to Decided 2026-10-15 (the format P-003 and P-004 use), and update the "proposed" and "Draft" banners that point at it: spec section 5.5 heading and callout, both schema descriptions, README line 46, the CHANGELOG bullet and its "may change" sentence, and conformance/HARNESS.md.

  • The merge commit 165a818 carries the Co-authored-by Copilot and Copilot-Session trailers again. Please drop them; a rebase onto main instead of the merge would do both at once. I squash-merge with a hand-written message either way, so the history will be clean, but the branch should match the repo rule.
  • Not blocking, your call: the parser checks the namespace grammar but does not refuse the reserved namespaces (acs, ctk, agent_hooks); the spec phrases the reservation as a provider obligation. If you prefer the parser to enforce it, add the check beside the grammar test with a fixture case per reserved name, in all five SDKs, in this PR or a follow-up.

    MohammadHaroonAbuomar MohammadHaroonAbuomar approved these changes on Oct 15, 2026 22:50 UTC
    Approved Reviewer

    Checked d38ddf4. The Status line reads Decided 2026-10-15, the Draft and proposed banners in the spec, both schema descriptions, the reserved-reasons cause text, README, CHANGELOG, HARNESS and the proposal now say adopted, and the branch is one commit rebased on main with your signoff only. The content diff against 165a818 is text only. CI is green.

    Approving. I squash-merge now with a hand-written message; this lands in 0.1.0-beta.3. Thanks for carrying it through, Liam.

    Assignees
    liamcrumm liamcrumm
    Labels
    risk: low confidence: 71.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 71.0% · Lower = rushed or shallow review
    71.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.8% · Safe to merge
    20.8%