Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

fix(observation): retain named tool receipts and empty end-stream frames (#107)

澄潭3b478222bb6b
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index 807294ad..aa6be23f 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -1364,6 +1364,20 @@
],
"reason": "Released public compute connection test callers from supported 0.2.0 and 0.3.0 omit the label. Normalize only that omission to the authenticated catalog option name; current named requests preserve the supplied label and protected Desktop checks still require an explicit label. Explicit null/invalid names, unknown fields and untrusted catalog facts remain rejected.",
"removal_condition": "Remove only after the supported released public request shape is explicitly retired with a caller migration path under the release support policy. Do not regenerate the frozen released request with the current producer."
+ },
+ {
+ "contract": "hiroute.observation.product-execution-envelope/v2",
+ "field": "function-only execution digest sha256:80b4ff13af8abc79d7721fea42141300beade2acf1d2659983ceaafcdc6e4799 and omitted required_named.tool_kind",
+ "mode": "recovery_read_only",
+ "owner": "domain/observation",
+ "reason": "Supported 0.2.0 d625e653, 0.3.0 ce4c4802 and 0.3.1 13856abd Product facts encode required_named with only name. Interpret omission as Function and keep that canonical encoding to authenticate retained fact/receipt digests. The 0.3.0/0.3.1 envelope digest and its optional pricing remain readable only in persisted recovery; live ingestion uses the current digest. Gateway live input still requires tool_kind, and Custom always retains its explicit discriminator. Inline frozen choice and digest fixtures preserve the exact released shapes.",
+ "removal_condition": "Retire only when every supported activity store and retained backup has no function-only contract rows/receipts, or an explicit identity-preserving migration replaces this reader. Keep the Function canonical encoding while retained authenticated digests depend on it.",
+ "allowed_paths": [
+ "crates/domain/src/observation/execution.rs",
+ "crates/domain/src/observation/execution_validation.rs",
+ "crates/domain/src/observation/execution_tests.rs",
+ "crates/observation/src/store/tests/store_flow.rs"
+ ]
}
]
}
diff --git a/crates/domain/src/observation/execution.rs b/crates/domain/src/observation/execution.rs
index 90684691..f643bdaa 100644
--- a/crates/domain/src/observation/execution.rs
+++ b/crates/domain/src/observation/execution.rs
@@ -19,7 +19,7 @@ use super::{
/// through `validate_persisted_contract`; they are never accepted by live ingestion.
pub const EXECUTION_FACT_SCHEMA_V2: &str = "hiroute.observation.product-execution-envelope/v2";
pub const EXECUTION_FACT_PORT_DIGEST_V2: &str =
- "sha256:80b4ff13af8abc79d7721fea42141300beade2acf1d2659983ceaafcdc6e4799";
+ "sha256:4f0dbcc9f7862133e73e451f64d7a6d6e5de146d958ac8bf3a4d1acc885b6b1d";
/// Gateway profile digests are canonical except on its explicit degraded-observation path.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
@@ -362,13 +362,34 @@ pub struct ReasonLedgerEntryV1 {
pub group_id: Option<String>,
}
+#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ToolKindRequirementV1 {
+ #[default]
+ Function,
+ Custom,
+}
+
+impl ToolKindRequirementV1 {
+ fn is_function(&self) -> bool {
+ *self == Self::Function
+ }
+}
+
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ToolChoiceRequirementV1 {
None,
Auto,
RequiredAny,
- RequiredNamed { name: String },
+ RequiredNamed {
+ // Released Product facts identify only functions. Keep their canonical bytes and
+ // authenticated digests; Custom must retain its explicit callable discriminator.
+ // Gateway's live DTO still requires tool_kind before the adapter reaches this codec.
+ #[serde(default, skip_serializing_if = "ToolKindRequirementV1::is_function")]
+ tool_kind: ToolKindRequirementV1,
+ name: String,
+ },
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
diff --git a/crates/domain/src/observation/execution_tests.rs b/crates/domain/src/observation/execution_tests.rs
index 59698bae..5e570925 100644
--- a/crates/domain/src/observation/execution_tests.rs
+++ b/crates/domain/src/observation/execution_tests.rs
@@ -249,6 +249,55 @@ fn legacy_execution_trust_without_plan_display_name_remains_readable() {
legacy.validate().unwrap();
}
+#[test]
+fn released_product_execution_digest_is_recovery_only_with_pricing() {
+ // Exact Product contract digest at supported 0.3.0 ce4c4802 and 0.3.1 13856abd.
+ let released_digest = CanonicalDigest::parse(
+ "sha256:80b4ff13af8abc79d7721fea42141300beade2acf1d2659983ceaafcdc6e4799",
+ )
+ .unwrap();
+ for mut envelope in gateway_fact_envelopes() {
+ envelope.schema_digest = released_digest.clone();
+ if matches!(envelope.fact, ExecutionFactV1::AttemptStarted { .. }) {
+ envelope.pricing = Some(
+ serde_json::from_value(serde_json::json!({
+ "schema_version": "hiroute.observation.execution-pricing/v1",
+ "request_generation": null,
+ "captured_at_ms": 0,
+ "attempt_execution_at_ms": 0,
+ "quote": null,
+ "reference_quote": null,
+ "unknown_reason": "snapshot_unavailable"
+ }))
+ .unwrap(),
+ );
+ }
+ assert_eq!(
+ envelope.validate(),
+ Err(ExecutionFactError::UnsupportedSchema)
+ );
+ envelope.validate_persisted_contract().unwrap();
+ let original = CanonicalDigest::of(&envelope).unwrap();
+ let decoded: ExecutionFactEnvelopeV1 =
+ serde_json::from_slice(&serde_json::to_vec(&envelope).unwrap()).unwrap();
+ assert_eq!(decoded, envelope);
+ assert_eq!(CanonicalDigest::of(&decoded).unwrap(), original);
+ }
+ let mut custom = gateway_fact_envelopes().remove(0);
+ custom.schema_digest = released_digest;
+ let ExecutionFactV1::RouteDecision(route) = &mut custom.fact else {
+ unreachable!()
+ };
+ route.requirements.tool_choice = ToolChoiceRequirementV1::RequiredNamed {
+ tool_kind: ToolKindRequirementV1::Custom,
+ name: "read_number".into(),
+ };
+ assert_eq!(
+ custom.validate_persisted_contract(),
+ Err(ExecutionFactError::InvalidFact)
+ );
+}
+
#[test]
fn typed_dynamic_edges_roundtrip_without_an_untyped_field_sink() {
let mut unavailable = candidate();
@@ -559,6 +608,54 @@ fn candidate() -> CandidateDecisionFactV1 {
}
}
+#[test]
+fn released_named_function_choice_preserves_canonical_bytes_and_digest() {
+ // Frozen Product serializer shape at supported 0.2.0 d625e653, 0.3.0 ce4c4802 and
+ // 0.3.1 13856abd. Do not regenerate this input with the current serializer.
+ let released = serde_json::json!({"kind": "required_named", "name": "read_number"});
+ let decoded: ToolChoiceRequirementV1 = serde_json::from_value(released.clone()).unwrap();
+ assert_eq!(
+ decoded,
+ ToolChoiceRequirementV1::RequiredNamed {
+ tool_kind: ToolKindRequirementV1::Function,
+ name: "read_number".into(),
+ }
+ );
+ assert_eq!(serde_json::to_value(&decoded).unwrap(), released);
+ assert_eq!(
+ CanonicalDigest::of(&decoded).unwrap(),
+ CanonicalDigest::of(&released).unwrap()
+ );
+ let mut explicit = released;
+ explicit["tool_kind"] = serde_json::json!("function");
+ assert_eq!(
+ serde_json::from_value::<ToolChoiceRequirementV1>(explicit).unwrap(),
+ decoded
+ );
+}
+
+#[test]
+fn custom_tool_choice_stays_distinct_and_strict() {
+ let custom =
+ serde_json::json!({"kind": "required_named", "tool_kind": "custom", "name": "read_number"});
+ let decoded: ToolChoiceRequirementV1 = serde_json::from_value(custom.clone()).unwrap();
+ assert_eq!(
+ decoded,
+ ToolChoiceRequirementV1::RequiredNamed {
+ tool_kind: ToolKindRequirementV1::Custom,
+ name: "read_number".into(),
+ }
+ );
+ assert_eq!(serde_json::to_value(decoded).unwrap(), custom);
+ for invalid in [
+ serde_json::json!({"kind": "required_named", "tool_kind": "unknown", "name": "read_number"}),
+ serde_json::json!({"kind": "required_named", "tool_kind": null, "name": "read_number"}),
+ serde_json::json!({"kind": "required_named", "tool_kind": "function", "name": "read_number", "extra": true}),
+ ] {
+ assert!(serde_json::from_value::<ToolChoiceRequirementV1>(invalid).is_err());
+ }
+}
+
fn requirements() -> RequestCapabilityRequirementsV1 {
RequestCapabilityRequirementsV1 {
ingress_protocol: IngressProtocolV1::Responses,
diff --git a/crates/domain/src/observation/execution_validation.rs b/crates/domain/src/observation/execution_validation.rs
index 185ebd5a..f8b19124 100644
--- a/crates/domain/src/observation/execution_validation.rs
+++ b/crates/domain/src/observation/execution_validation.rs
@@ -26,7 +26,11 @@ impl ExecutionFactEnvelopeV1 {
&& self.schema_version == EXECUTION_FACT_SCHEMA_V2
&& self.schema_digest.as_str()
== "sha256:de91d4f2333db66f0ec3f8b63ce192267dee0a56b65f34180b06996b232fb2c6";
- if !(current || persisted_v1 || persisted_pre_branch)
+ let persisted_function_only = allow_persisted_v1
+ && self.schema_version == EXECUTION_FACT_SCHEMA_V2
+ && self.schema_digest.as_str()
+ == "sha256:80b4ff13af8abc79d7721fea42141300beade2acf1d2659983ceaafcdc6e4799";
+ if !(current || persisted_v1 || persisted_pre_branch || persisted_function_only)
|| self.channel != ExecutionFactChannelV1::ExecutionFact
{
return Err(ExecutionFactError::UnsupportedSchema);
@@ -51,6 +55,18 @@ impl ExecutionFactEnvelopeV1 {
}
self.trust.validate()?;
self.fact.validate()?;
+ if !current
+ && matches!(
+ &self.fact,
+ ExecutionFactV1::RouteDecision(route)
+ if matches!(route.requirements.tool_choice,
+ ToolChoiceRequirementV1::RequiredNamed {
+ tool_kind: ToolKindRequirementV1::Custom, ..
+ })
+ )
+ {
+ return Err(ExecutionFactError::InvalidFact);
+ }
if let ExecutionFactV1::BranchAssessmentRecorded {
trigger_request_id, ..
} = &self.fact
@@ -59,7 +75,9 @@ impl ExecutionFactEnvelopeV1 {
return Err(ExecutionFactError::InvalidFact);
}
if let Some(pricing) = &self.pricing {
- if !current || !matches!(self.fact, ExecutionFactV1::AttemptStarted { .. }) {
+ if !(current || persisted_function_only)
+ || !matches!(self.fact, ExecutionFactV1::AttemptStarted { .. })
+ {
return Err(ExecutionFactError::InvalidFact);
}
pricing.validate()?;
diff --git a/crates/domain/src/observation/lifecycle.rs b/crates/domain/src/observation/lifecycle.rs
index bbf410a1..e57ae93b 100644
--- a/crates/domain/src/observation/lifecycle.rs
+++ b/crates/domain/src/observation/lifecycle.rs
@@ -69,6 +69,7 @@ pub enum LifecycleFactV2 {
},
ResponseFrameAccepted {
frame_id: String,
+ /// Actual transport-accepted bytes; an accepted empty end-stream frame is zero.
byte_count: u64,
downstream_delivery: String,
},
@@ -141,12 +142,9 @@ impl LifecycleFactEnvelopeV2 {
}
LifecycleFactV2::ResponseFrameAccepted {
frame_id,
- byte_count,
downstream_delivery,
- } if frame_id.trim().is_empty()
- || *byte_count == 0
- || downstream_delivery.trim().is_empty() =>
- {
+ ..
+ } if frame_id.trim().is_empty() || downstream_delivery.trim().is_empty() => {
Err(LifecycleContractErrorV2::InvalidFact)
}
_ => Ok(()),
diff --git a/crates/domain/src/observation/pricing.rs b/crates/domain/src/observation/pricing.rs
index 6e8fee9c..85677c6c 100644
--- a/crates/domain/src/observation/pricing.rs
+++ b/crates/domain/src/observation/pricing.rs
@@ -91,7 +91,7 @@ impl ExecutionPricingEvidenceV1 {
/// One Product contract for priced and unpriced execution. The optional field records whether
/// pricing evidence existed; absence never selects another envelope version.
-pub const EXECUTION_PRODUCT_CONTRACT: &str = r#"{"schema":"hiroute.observation.product-execution-envelope/v2","extends_digest":"sha256:5aad4c450a2a296ec557b7a934bfbf70ad69a8e8fe9bc7539db46830a2940069","optional_field":"pricing","pricing_schema":"hiroute.observation.execution-pricing/v1","pricing_fields":["usage_semantics","schema_version","request_generation?","captured_at_ms","attempt_execution_at_ms","quote?","reference_quote?","unknown_reason?"],"scope":"attempt_started_only","quote_type":"FrozenPriceQuoteV1","quote_time_unit":"unix_seconds","capture_time_unit":"unix_milliseconds","route_identity":{"replaces_trust_fields":["agent_plan_revision_id","agent_plan_semantic_digest"],"replaces_route_decision_fields":["plan_revision"],"field":"route","tag":"kind","plan":{"revision":"positive_u64","semantic_digest":"sha256"},"fixed":{"binding_digest":"sha256"},"plan_identity":"required_for_plan_null_for_fixed","fixed_plan_display_name":"forbidden","route_decision_matches_trust":true},"complexity_decision":{"fields":["strategy_id","schema_version","payload_digest","branch_id","policy?","competence_trigger?","execution_group","simple_probability?","simple_threshold_millis?","selection_reason","complexity_score?","threshold?","decision_source","reason_codes","matched_user_phrase_ids","fallback_used","classification_duration_micros?","fallback_reason?"],"sources":["inherited","external_classifier","user_phrase","builtin_rules","unresolved"],"fallback_reasons":["timeout","unavailable","rejected_input","invalid_output"]},"branch_execution":{"scope":"agent_turn_finished","fields":["policy","group","candidate_index"],"policy_fields":["name","floor_millis","criteria_digest?"]},"competence_protection":{"scope":"route_decision.complexity.competence_trigger","fields":["segment_id","score","floor_millis","from_group"]}}"#;
+pub const EXECUTION_PRODUCT_CONTRACT: &str = r#"{"schema":"hiroute.observation.product-execution-envelope/v2","extends_digest":"sha256:5aad4c450a2a296ec557b7a934bfbf70ad69a8e8fe9bc7539db46830a2940069","optional_field":"pricing","pricing_schema":"hiroute.observation.execution-pricing/v1","pricing_fields":["usage_semantics","schema_version","request_generation?","captured_at_ms","attempt_execution_at_ms","quote?","reference_quote?","unknown_reason?"],"scope":"attempt_started_only","quote_type":"FrozenPriceQuoteV1","quote_time_unit":"unix_seconds","capture_time_unit":"unix_milliseconds","route_identity":{"replaces_trust_fields":["agent_plan_revision_id","agent_plan_semantic_digest"],"replaces_route_decision_fields":["plan_revision"],"field":"route","tag":"kind","plan":{"revision":"positive_u64","semantic_digest":"sha256"},"fixed":{"binding_digest":"sha256"},"plan_identity":"required_for_plan_null_for_fixed","fixed_plan_display_name":"forbidden","route_decision_matches_trust":true},"complexity_decision":{"fields":["strategy_id","schema_version","payload_digest","branch_id","policy?","competence_trigger?","execution_group","simple_probability?","simple_threshold_millis?","selection_reason","complexity_score?","threshold?","decision_source","reason_codes","matched_user_phrase_ids","fallback_used","classification_duration_micros?","fallback_reason?"],"sources":["inherited","external_classifier","user_phrase","builtin_rules","unresolved"],"fallback_reasons":["timeout","unavailable","rejected_input","invalid_output"]},"branch_execution":{"scope":"agent_turn_finished","fields":["policy","group","candidate_index"],"policy_fields":["name","floor_millis","criteria_digest?"]},"competence_protection":{"scope":"route_decision.complexity.competence_trigger","fields":["segment_id","score","floor_millis","from_group"]},"named_tool_choice":{"kinds":["function","custom"],"function_encoding":"implicit","custom_encoding":"explicit_tool_kind","omitted_kind":"function"}}"#;
#[cfg(test)]
mod tests {
diff --git a/crates/gateway/README.md b/crates/gateway/README.md
index 505a794f..c20b96fc 100644
--- a/crates/gateway/README.md
+++ b/crates/gateway/README.md
@@ -15,6 +15,13 @@ The standalone `hirouted` entry can attach the same typed diagnostics using
capture or execution-fact storage. At Info, failed attempts retain the safe
actual model and reasoning controls, HTTP protocol/status and body commit state.
+For operational lifecycle telemetry, [accepted response capture](src/observation/content.rs)
+reports transport writes only after they succeed, including an empty end-stream write.
+[Product lifecycle validation](../domain/src/observation/lifecycle.rs) preserves its actual
+zero byte count and frame identity; the [bounded receiver](../observation/src/writer/lifecycle.rs)
+ACKs it in sequence before RequestFinished. These transport events describe delivery;
+semantic output, usage and the business receipt retain their own facts.
+
Messages thinking computation is projected in
[request/native.rs](src/adapters/request/native.rs); request-local `thinking.display`
is resolved by [ingress.rs](src/adapters/ingress.rs) before Replay externalization.
diff --git a/crates/integrations/src/agents/pi_runtime_tests.rs b/crates/integrations/src/agents/pi_runtime_tests.rs
index 8615629e..f9031d11 100644
--- a/crates/integrations/src/agents/pi_runtime_tests.rs
+++ b/crates/integrations/src/agents/pi_runtime_tests.rs
@@ -2,18 +2,24 @@ use super::*;
use std::os::unix::fs::PermissionsExt;
fn native_fixture(root: &Path, body: &str) -> PathBuf {
+ let input = root.join("node-body.sh");
+ std::fs::write(&input, format!("#!/bin/sh\n{body}\n")).unwrap();
+ std::fs::set_permissions(&input, std::fs::Permissions::from_mode(0o600)).unwrap();
+ // The executable is immutable; writable test bodies are interpreter inputs.
+ // This avoids turning a version/output assertion into an executable-busy failure.
let path = root.join("node");
- std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
+ std::os::unix::fs::symlink(
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pi-node-launcher.sh"),
+ &path,
+ )
+ .unwrap();
path
}
#[test]
fn supported_cold_pi_node_is_not_rejected_after_two_seconds() {
let root = tempfile::tempdir().unwrap();
- let node = root.path().join("node");
- std::fs::write(&node, "#!/bin/sh\nsleep 3; printf 'v24.19.0\\n'\n").unwrap();
- std::fs::set_permissions(&node, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let node = native_fixture(root.path(), "sleep 3; printf 'v24.19.0\\n'");
assert!(validate_pi_node(&node).is_ok());
}
@@ -54,6 +60,48 @@ fn pi_checks_preserve_stage_reason_and_owned_timeout_cleanup() {
);
}
+#[cfg(target_os = "linux")]
+#[test]
+fn pi_node_fixture_preserves_version_with_a_writable_input() {
+ let root = tempfile::tempdir().unwrap();
+ let node = native_fixture(root.path(), "echo v22.18.0");
+ let writable_input = std::fs::OpenOptions::new()
+ .write(true)
+ .open(root.path().join("node-body.sh"))
+ .unwrap();
+ assert_eq!(
+ validate_pi_node(&node),
+ Err(NativeDependencyFailureV1 {
+ check: NativeDependencyCheckV1::PiNodeVersion,
+ reason: NativeDependencyFailureReasonV1::Unsupported,
+ })
+ );
+ drop(writable_input);
+}
+
+#[cfg(target_os = "linux")]
+#[test]
+fn pi_node_busy_executable_reports_unavailable_before_version_parsing() {
+ let root = tempfile::tempdir().unwrap();
+ let node = root.path().join("busy-node");
+ std::fs::write(&node, "#!/bin/sh\necho v22.18.0\n").unwrap();
+ std::fs::set_permissions(&node, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let writable_executable = std::fs::OpenOptions::new().write(true).open(&node).unwrap();
+ let error = std::process::Command::new(&node)
+ .arg("--version")
+ .output()
+ .unwrap_err();
+ assert_eq!(error.kind(), std::io::ErrorKind::ExecutableFileBusy);
+ assert_eq!(
+ validate_pi_node(&node),
+ Err(NativeDependencyFailureV1 {
+ check: NativeDependencyCheckV1::PiNodeVersion,
+ reason: NativeDependencyFailureReasonV1::Unavailable,
+ })
+ );
+ drop(writable_executable);
+}
+
#[test]
fn cold_pi_sdk_keeps_exact_scope_and_does_not_reuse_failed_capability() {
let root = tempfile::tempdir().unwrap();
diff --git a/crates/integrations/src/gateway/mod.rs b/crates/integrations/src/gateway/mod.rs
index 950079f2..3ac372b7 100644
--- a/crates/integrations/src/gateway/mod.rs
+++ b/crates/integrations/src/gateway/mod.rs
@@ -3,6 +3,8 @@
//! These functions perform no lookup, caching, queueing, retry, or business inference. Every
//! input first decodes as the Gateway-owned type and every output validates as the Product-owned
//! type, so an unknown field or schema drift fails before a receiver or credential authority.
+//! Named tool choices retain kind and name. Product's canonical Function encoding omits the
+//! default kind to preserve released immutable fact/receipt digests; Custom stays explicit.
use hiroute_domain::{
CONVERSATION_CONTENT_PORT_DIGEST_V2, CONVERSATION_CONTENT_SCHEMA_V2,
diff --git a/crates/integrations/src/gateway/tests.rs b/crates/integrations/src/gateway/tests.rs
index 5d05ff63..fa307eaa 100644
--- a/crates/integrations/src/gateway/tests.rs
+++ b/crates/integrations/src/gateway/tests.rs
@@ -147,6 +147,49 @@ fn gateway_adapter_projects_lifecycle_exactly_and_rejects_unknown_field() {
);
}
+#[test]
+fn gateway_adapter_preserves_zero_byte_lifecycle_end_stream_frame() {
+ let payload = json!({
+ "schema_version": LIFECYCLE_FACT_SCHEMA,
+ "schema_digest": LIFECYCLE_FACT_PORT_DIGEST,
+ "channel": "lifecycle",
+ "producer": producer("gateway-lifecycle"),
+ "sequence": 5,
+ "event_id": "lifecycle-end-stream-5",
+ "correlation": correlation(),
+ "occurred_at_unix_nanos": 1,
+ "fact": {
+ "kind": "response_frame_accepted",
+ "frame_id": "frame-empty-end-stream",
+ "byte_count": 0,
+ "downstream_delivery": "full_frame_transport_accepted"
+ },
+ "loss_watermark": null,
+ "completeness_delta": null
+ });
+ // ReplayBodySession reports an accepted empty EOF write through the same
+ // lifecycle DTO as a nonempty body frame; its actual byte count stays zero.
+ let gateway: hiroute_gateway::server::core_runtime::observation::LifecycleFactEnvelopeV1 =
+ serde_json::from_value(payload.clone()).unwrap();
+ let projected = project_lifecycle_payload(&serde_json::to_vec(&gateway).unwrap()).unwrap();
+ assert_eq!(serde_json::to_value(projected).unwrap(), payload);
+
+ for field in ["frame_id", "downstream_delivery"] {
+ let mut invalid = payload.clone();
+ invalid["fact"][field] = json!("");
+ assert_eq!(
+ project_lifecycle_payload(&serde_json::to_vec(&invalid).unwrap()),
+ Err(GatewayProjectionError::InvalidOutput)
+ );
+ }
+ let mut unknown = payload;
+ unknown["fact"]["content"] = json!("not a lifecycle field");
+ assert_eq!(
+ project_lifecycle_payload(&serde_json::to_vec(&unknown).unwrap()),
+ Err(GatewayProjectionError::InvalidInput)
+ );
+}
+
#[test]
fn gateway_adapter_projects_flat_execution_receipt_into_frozen_trust() {
let payload = execution_payload(
@@ -331,6 +374,60 @@ fn gateway_adapter_tags_provider_native_reasoning_for_product_receipts() {
);
}
+#[test]
+fn gateway_adapter_preserves_every_tool_choice_identity() {
+ use hiroute_gateway::server::core_runtime::model_ir::{ToolChoice, ToolKindV1};
+
+ for (choice, expected) in [
+ (ToolChoice::None, json!({"kind": "none"})),
+ (ToolChoice::Auto, json!({"kind": "auto"})),
+ (ToolChoice::RequiredAny, json!({"kind": "required_any"})),
+ (
+ ToolChoice::RequiredNamed {
+ tool_kind: ToolKindV1::Function,
+ name: "read_number".into(),
+ },
+ // Product's canonical Function form preserves released fact/receipt digests.
+ json!({"kind": "required_named", "name": "read_number"}),
+ ),
+ (
+ ToolChoice::RequiredNamed {
+ tool_kind: ToolKindV1::Custom,
+ name: "read_number".into(),
+ },
+ json!({"kind": "required_named", "tool_kind": "custom", "name": "read_number"}),
+ ),
+ ] {
+ let mut fact = complete_execution_facts().remove(0);
+ fact["requirements"]["tool_choice"] = serde_json::to_value(&choice).unwrap();
+ let payload = execution_payload(fact, 1, false);
+ let projected = project_execution_payload(&serde_json::to_vec(&payload).unwrap())
+ .unwrap_or_else(|error| panic!("{choice:?} was rejected: {error:?}"));
+ assert_eq!(
+ serde_json::to_value(projected.fact).unwrap()["requirements"]["tool_choice"],
+ expected,
+ "{choice:?} lost its callable identity"
+ );
+ }
+}
+
+#[test]
+fn gateway_adapter_rejects_incomplete_or_unknown_named_tool_identity() {
+ for choice in [
+ json!({"kind": "required_named", "name": "read_number"}),
+ json!({"kind": "required_named", "tool_kind": "unknown", "name": "read_number"}),
+ json!({"kind": "required_named", "tool_kind": "function", "name": "read_number", "extra": true}),
+ ] {
+ let mut fact = complete_execution_facts().remove(0);
+ fact["requirements"]["tool_choice"] = choice;
+ let payload = execution_payload(fact, 1, false);
+ assert_eq!(
+ project_execution_payload(&serde_json::to_vec(&payload).unwrap()),
+ Err(GatewayProjectionError::InvalidInput),
+ );
+ }
+}
+
#[test]
fn gateway_adapter_projects_every_execution_fact_variant_without_loss() {
let facts = complete_execution_facts();
diff --git a/crates/integrations/tests/fixtures/pi-node-launcher.sh b/crates/integrations/tests/fixtures/pi-node-launcher.sh
new file mode 100755
index 00000000..b2db6338
--- /dev/null
+++ b/crates/integrations/tests/fixtures/pi-node-launcher.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+# Keep the executable immutable; the private body is interpreter input.
+exec /bin/sh "${0%/*}/node-body.sh" "$@"
diff --git a/crates/observation/src/store/tests/store_flow.rs b/crates/observation/src/store/tests/store_flow.rs
index c183e47d..a4bee3d3 100644
--- a/crates/observation/src/store/tests/store_flow.rs
+++ b/crates/observation/src/store/tests/store_flow.rs
@@ -153,3 +153,172 @@ fn fact_log_tamper_and_unknown_contract_version_fail_closed() {
"dedup must validate the authoritative raw fact instead of trusting its ACK ledger"
);
}
+
+#[test]
+fn named_tool_request_closes_before_agent_turn_and_reopens_without_digest_drift() {
+ use hiroute_domain::{CanonicalDigest, ToolChoiceRequirementV1, ToolKindRequirementV1};
+
+ for tool_kind in [
+ ToolKindRequirementV1::Function,
+ ToolKindRequirementV1::Custom,
+ ] {
+ let temporary = tempdir().unwrap();
+ let fixture = Fixture::new("named-tool");
+ let store = open_store(temporary.path());
+ let fact_writer = writer(&store);
+ let channel = fact_channel(&fixture, 512 * 1024);
+ let mut facts = request_facts(&fixture, "attempt-named", finished("attempt-named"), 100);
+ let ExecutionFactV1::RouteDecision(route) = &mut facts[0].fact else {
+ unreachable!()
+ };
+ route.requirements.tool_choice = ToolChoiceRequirementV1::RequiredNamed {
+ tool_kind,
+ name: "read_number".into(),
+ };
+ assert!(
+ !facts
+ .iter()
+ .any(|event| matches!(event.fact, ExecutionFactV1::AgentTurnFinished { .. }))
+ );
+ for fact in facts.clone() {
+ assert!(matches!(
+ offer_fact(&fact_writer, &channel, fact),
+ WriterCycleOutcome::Ack(_)
+ ));
+ }
+ let receipt_id = hiroute_domain::ReceiptId::parse(fixture.request.as_str()).unwrap();
+ let receipt = store.get_receipt(&fixture.workspace, &receipt_id).unwrap();
+ assert_eq!(receipt.outcome, hiroute_domain::RequestOutcome::Accepted);
+ assert_eq!(
+ receipt.facts_completeness,
+ hiroute_domain::FactsCompleteness::Complete
+ );
+ assert_eq!(receipt.ordered_facts[0].fact, facts[0].fact);
+ let before = receipt.digest().unwrap();
+ let original_fact_digest = CanonicalDigest::of(&facts[0]).unwrap();
+ drop(channel);
+ drop(fact_writer);
+ drop(store);
+ let reopened = open_store(temporary.path());
+ let read = reopened
+ .get_receipt(&fixture.workspace, &receipt_id)
+ .unwrap();
+ assert_eq!(read, receipt);
+ assert_eq!(read.digest().unwrap(), before);
+ let stored = crate::store::fact_log::load_request(
+ &reopened.connection.lock(),
+ &fixture.workspace,
+ &fixture.request,
+ )
+ .unwrap();
+ assert_eq!(stored, facts);
+ assert_eq!(
+ CanonicalDigest::of(&stored[0]).unwrap(),
+ original_fact_digest
+ );
+ assert!(matches!(
+ offer_fact(
+ &writer(&reopened),
+ &fact_channel(&fixture, 512 * 1024),
+ facts[9].clone()
+ ),
+ WriterCycleOutcome::Ack(_)
+ ));
+ }
+}
+
+#[test]
+fn released_function_only_facts_and_receipt_reopen_alongside_current_writes() {
+ use hiroute_domain::{CanonicalDigest, ExecutionFactEnvelopeV1};
+
+ let temporary = tempdir().unwrap();
+ let fixture = Fixture::new("released-named-tool");
+ let store = open_store(temporary.path());
+ let facts = request_facts(&fixture, "attempt-old", finished("attempt-old"), 100);
+ let mut released = Vec::new();
+ // Freeze only the changed fields from the supported 0.3.0/0.3.1 Product serializer;
+ // the unchanged fixture supplies the surrounding valid request and attempt identities.
+ for mut bytes in facts.iter().map(|fact| serde_json::to_value(fact).unwrap()) {
+ bytes["schema_digest"] = serde_json::json!(
+ "sha256:80b4ff13af8abc79d7721fea42141300beade2acf1d2659983ceaafcdc6e4799"
+ );
+ if bytes["fact"]["kind"] == "route_decision" {
+ bytes["fact"]["requirements"]["tool_choice"] =
+ serde_json::json!({"kind": "required_named", "name": "read_number"});
+ }
+ let original_digest = CanonicalDigest::of(&bytes).unwrap();
+ let decoded: ExecutionFactEnvelopeV1 = serde_json::from_value(bytes.clone()).unwrap();
+ assert!(
+ decoded.validate().is_err(),
+ "old contracts are recovery only"
+ );
+ decoded.validate_persisted_contract().unwrap();
+ assert_eq!(serde_json::to_value(&decoded).unwrap(), bytes);
+ assert_eq!(CanonicalDigest::of(&decoded).unwrap(), original_digest);
+ released.push((decoded, original_digest));
+ }
+ // Model retained rows through the existing immutable writer, without admitting the old
+ // contract into live ingestion. Reads still authenticate the original row digests.
+ {
+ let mut connection = store.connection.lock();
+ let transaction = connection.transaction().unwrap();
+ for (fact, digest) in &released {
+ crate::store::fact_log::insert(&transaction, fact, digest).unwrap();
+ crate::receipt::apply_fact(&transaction, fact).unwrap();
+ }
+ transaction.commit().unwrap();
+ }
+ let receipt_id = hiroute_domain::ReceiptId::parse(fixture.request.as_str()).unwrap();
+ let before = store.get_receipt(&fixture.workspace, &receipt_id).unwrap();
+ let before_digest = before.digest().unwrap();
+ drop(store);
+ let reopened = open_store(temporary.path());
+ assert_eq!(
+ reopened
+ .get_receipt(&fixture.workspace, &receipt_id)
+ .unwrap(),
+ before
+ );
+ assert_eq!(before.digest().unwrap(), before_digest);
+ let old_facts = crate::store::fact_log::load_request(
+ &reopened.connection.lock(),
+ &fixture.workspace,
+ &fixture.request,
+ )
+ .unwrap();
+ for (read, (original, digest)) in old_facts.iter().zip(&released) {
+ assert_eq!(read, original);
+ assert_eq!(CanonicalDigest::of(read).unwrap(), *digest);
+ }
+ let current = Fixture::new("current-after-released");
+ let fact_writer = writer(&reopened);
+ let channel = fact_channel(&current, 512 * 1024);
+ for fact in request_facts(&current, "attempt-new", finished("attempt-new"), 200) {
+ assert!(matches!(
+ offer_fact(&fact_writer, &channel, fact),
+ WriterCycleOutcome::Ack(_)
+ ));
+ }
+ assert!(
+ reopened
+ .get_receipt(
+ &current.workspace,
+ &hiroute_domain::ReceiptId::parse(current.request.as_str()).unwrap()
+ )
+ .is_ok()
+ );
+ assert_eq!(
+ reopened
+ .get_receipt(&fixture.workspace, &receipt_id)
+ .unwrap(),
+ before
+ );
+ assert!(matches!(
+ offer_fact(
+ &fact_writer,
+ &fact_channel(&fixture, 512 * 1024),
+ released[0].0.clone()
+ ),
+ WriterCycleOutcome::Nack(_)
+ ));
+}
diff --git a/crates/observation/src/writer/lifecycle_tests.rs b/crates/observation/src/writer/lifecycle_tests.rs
index 2644cb52..d09aa5c1 100644
--- a/crates/observation/src/writer/lifecycle_tests.rs
+++ b/crates/observation/src/writer/lifecycle_tests.rs
@@ -86,6 +86,48 @@ fn lifecycle_receiver_accepts_every_exact_event_kind_and_replay() {
assert_eq!(receiver.accepted_len().unwrap(), 6);
}
+#[test]
+fn lifecycle_receiver_accepts_empty_end_stream_without_a_sequence_gap() {
+ let receiver = BoundedLifecycleReceiverV2::new(4).unwrap();
+ let events = [
+ LifecycleFactV2::RequestAccepted {
+ ingress_protocol: "responses".into(),
+ },
+ LifecycleFactV2::ResponseFrameAccepted {
+ frame_id: "frame-body".into(),
+ byte_count: 64,
+ downstream_delivery: "full_frame_transport_accepted".into(),
+ },
+ LifecycleFactV2::ResponseFrameAccepted {
+ frame_id: "frame-empty-end-stream".into(),
+ byte_count: 0,
+ downstream_delivery: "full_frame_transport_accepted".into(),
+ },
+ LifecycleFactV2::RequestFinished {
+ outcome: "succeeded".into(),
+ },
+ ];
+ let expected: Vec<_> = events
+ .into_iter()
+ .enumerate()
+ .map(|(index, fact)| envelope(u64::try_from(index + 1).unwrap(), fact))
+ .collect();
+ for event in &expected {
+ let feedback = receiver.receive_lifecycle(event).unwrap();
+ assert!(matches!(
+ feedback,
+ ObservationFeedback::Ack(ref ack)
+ if ack.highest_contiguous_sequence == event.sequence
+ && ack.highest_accounted_sequence == event.sequence
+ ));
+ if event.sequence == 3 {
+ assert_eq!(receiver.receive_lifecycle(event).unwrap(), feedback);
+ assert_eq!(receiver.accepted_len().unwrap(), 3);
+ }
+ }
+ assert_eq!(receiver.records().unwrap(), expected);
+}
+
#[test]
fn bounded_lifecycle_receiver_evicts_after_capacity_and_nacks_sequence_gap() {
let receiver = BoundedLifecycleReceiverV2::new(1).unwrap();
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
index c4a442a4..30140a97 100644
--- a/docs/code-map/architecture.md
+++ b/docs/code-map/architecture.md
@@ -78,6 +78,8 @@ Scan → Prepare → Save → restart → native use, including stale-source rej
| Concern | Owner | What callers must preserve |
| --- | --- | --- |
| Native Agent session correlation | [Gateway identity resolver](../../crates/gateway/src/context_hold/identity.rs), [native input guide](../../crates/gateway/README.md#native-session-correlation) | One identity feeds ContextHold, decision history and observation; native IDs precede content inference, malformed or conflicting claims remain request-scoped |
+| Named tool decision facts and request receipts | [Strict Gateway adapter](../../crates/integrations/src/gateway/mod.rs), [Product tool choice](../../crates/domain/src/observation/execution.rs), [receipt writer](../../crates/observation/src/receipt/mod.rs) | Preserve callable kind and name; Product's implicit Function encoding preserves historical digests. Each completed HTTP request closes independently of an unfinished Agent turn; [boundary regressions](../../crates/integrations/src/gateway/tests.rs) cover all tool choices |
+| Lifecycle acceptance of empty response end-stream frames | [Transport acceptance capture](../../crates/gateway/src/observation/content.rs), [Product lifecycle validation](../../crates/domain/src/observation/lifecycle.rs), [bounded receiver](../../crates/observation/src/writer/lifecycle.rs) | Successful zero-byte end-stream writes are real operational events with a zero byte count; identity remains strict. [Receiver regressions](../../crates/observation/src/writer/lifecycle_tests.rs) preserve continuous ACK through RequestFinished |
| Capture completeness | [Content completeness](../../crates/observation/src/content/completeness.rs), [session query](../../crates/observation/src/query_v2/sessions.rs) | Aggregate every required request/direction; a finished stream or readable preview does not prove the session is complete |
| Streaming memory | [Capture](../../crates/gateway/src/observation/provider/capture.rs), [pending delivery](../../crates/gateway/src/observation/provider/capture/tracker.rs) | Decoder, projector and delivery tracker share the stream budget; queue capacity is not capture evidence |
| Upstream fault attribution | [Wire projection](../../crates/gateway/src/observation/provider/wire_diagnostic.rs), [attempt association](../../crates/gateway/src/observation/request/diagnostic.rs), [decision calls](../../crates/gateway/src/core_runtime/classification/diagnostic.rs) | Actual bounded model/control fields, negotiated HTTP protocol, closed error codes, hashed request IDs and separate client headers/body commit facts must preserve the real outcome without prompts or provider error text |
diff --git a/docs/code-map/testing.md b/docs/code-map/testing.md
index b8af2394..512505b4 100644
--- a/docs/code-map/testing.md
+++ b/docs/code-map/testing.md
@@ -38,6 +38,7 @@ validate the oracle. The real installed management loop is in
| Observe native routing and rejected attempts | [NativeContextUpstream](../../crates/daemon/tests/support/native_context_fixture.py): count every model POST, including rejected endpoints/models/credentials; keep the ledger for positive route/history assertions |
| Prove exact Continue, concurrent routes and cancellation | [Native context](../../crates/daemon/tests/support/native_context_product.py), [boundary journey](../../crates/daemon/tests/support/native_context_boundaries.py), [boundary oracle guide](../../crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md) |
| Prove restoration of old durable state | [Frozen producer fixtures](../../crates/local-storage/src/migrations/fixtures/README.md), [crash-boundary tests](../../crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs): old bytes through the current consumer, not a new serializer pretending to be history |
+| Preserve native probe failure classification | [Pi probe tests](../../crates/integrations/src/agents/pi_runtime_tests.rs), [immutable launcher](../../crates/integrations/tests/fixtures/pi-node-launcher.sh): mutable test bodies are interpreter inputs; executable availability and version/output failures have separate assertions |
| Exercise actual Desktop controls | [Browser scenario map](../../apps/desktop/tests/README.md) and native acceptance: select stable scenario IDs and require every declared outcome |
The publication fixture leases its listener address across daemon restarts; do
diff --git a/e2e/product/golden/observation/local-observation-boundary.v2.json b/e2e/product/golden/observation/local-observation-boundary.v2.json
index 66bcda24..d7021601 100644
--- a/e2e/product/golden/observation/local-observation-boundary.v2.json
+++ b/e2e/product/golden/observation/local-observation-boundary.v2.json
@@ -5,7 +5,7 @@
"production_evidence": "installed-standalone-headless-management-loop",
"composition_owner": "TASK-142003",
"execution_fact_schema": "hiroute.observation.product-execution-envelope/v2",
- "execution_fact_port_digest": "sha256:80b4ff13af8abc79d7721fea42141300beade2acf1d2659983ceaafcdc6e4799",
+ "execution_fact_port_digest": "sha256:4f0dbcc9f7862133e73e451f64d7a6d6e5de146d958ac8bf3a4d1acc885b6b1d",
"conversation_content_schema": "hiroute.observation.conversation-content-envelope/v2",
"conversation_content_port_digest": "sha256:6f17cd772a0fb322d25dd31dc95e34325cbabbd68912b32f5bb9bed526adfe44",
"acknowledgement_schema": "hiroute.observation.ack/v2",