diff --git a/README.md b/README.md index 00dc0ee..7b89220 100644 --- a/README.md +++ b/README.md @@ -1007,3 +1007,9 @@ sources are used in source validation. Provider compatibility, native GUI evidence remain open. See the [adapter contract](docs/model-cloud-adapter.md), [credential custody](docs/model-cloud-custody.md) and canonical [development evidence](docs/development.md). + +## Offline LNSAT request-record inspection + +The separate `rangoon.integrations.lnsat-request-record.v1` source profile inspects one caller-supplied, bounded synthetic request record from the selected LNSAT source contract at `35a41963ad698934c7ee00852c71355e329c34fa`. It distinguishes failed evaluation, unknown outcome, degraded evidence, generic read refusal and unavailable reads. Native completion remains a reported fact, not independently verified effect or execution authority. Requester identity and approval reasons are omitted; the separate summary contains fixed labels and counts, while host bytes retain sensitive correlation identifiers. + +The existing D3a runtime-composition decoder and its `f669181a` source pin remain unchanged. Neither decoder performs a live read, opens credentials, persists evidence, reconciles an outcome or dispatches an action. The new profile is unmounted and does not replace O1/O2, VUSL or any provider contract. The [implementation receipt](docs/development.md#offline-lnsat-request-record-decoder--october-26-2026) owns exact source/test/review evidence and remaining gates. This source work is not installed-runtime, platform, release or support qualification. diff --git a/crates/rangoon-integrations/src/lib.rs b/crates/rangoon-integrations/src/lib.rs index b5cc811..4eb2ce8 100644 --- a/crates/rangoon-integrations/src/lib.rs +++ b/crates/rangoon-integrations/src/lib.rs @@ -5,6 +5,7 @@ mod descriptor; mod inspection; pub mod lnsat_evidence; +pub mod lnsat_request_record; pub mod openshell_observation; pub mod openshell_runtime; diff --git a/crates/rangoon-integrations/src/lnsat_request_record.rs b/crates/rangoon-integrations/src/lnsat_request_record.rs new file mode 100644 index 0000000..3d2c493 --- /dev/null +++ b/crates/rangoon-integrations/src/lnsat_request_record.rs @@ -0,0 +1,1970 @@ +//! Bounded offline LNSAT action-request inspection. +#![forbid(unsafe_code)] + +use rangoon_domain::byte_digest; + +pub const MAX_INPUT_BYTES: usize = 65_536; +const MAX_DEPTH: usize = 16; +const MAX_VALUES: usize = 16_384; +const MAX_OBJECT_FIELDS: usize = 32; +const MAX_ARRAY_ITEMS: usize = 64; +const MAX_OBSERVATIONS: usize = 2; +const MAX_STRING_BYTES: usize = 4_096; +const MAX_HOST_BYTES: usize = 131_072; +const MAX_SUMMARY_BYTES: usize = 8_192; +const WIRE: &str = "lnsat.action_request_record.v1"; +const LINKED_WIRE: &str = "lnsat.action_request_linked_evidence.v1"; +const SOURCE_COMMIT: &str = "35a41963ad698934c7ee00852c71355e329c34fa"; + +#[derive(Clone, Copy, Eq, PartialEq)] +pub enum ReadUnavailable { + NotConfigured, + TransportUnavailable, + Cancelled, + Timeout, + Unauthenticated, + UnsupportedTransport, +} +pub enum RequestRecordBody { + Body200(Vec), + Refused403(Vec), + ReadUnavailable(ReadUnavailable), +} +pub struct RequestRecordInput { + pub installation_id: String, + pub environment: String, + pub selected_request_id: String, + pub expected_project_ref: String, + pub expected_resource_ref: String, + pub body: RequestRecordBody, + pub read_at: Option, +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RequestRecordError { + InputLimit, + InvalidEncoding, + InvalidJson, + DuplicateField, + StructuralLimit, + UnsupportedSchema, + InvalidEnvelope, + SelectionMismatch, + ScopeMismatch, + LineageConflict, + UnsupportedState, + OutputLimit, + SerializationFailed, +} +impl RequestRecordError { + pub const fn code(self) -> &'static str { + match self { + Self::InputLimit => "input_limit", + Self::InvalidEncoding => "invalid_encoding", + Self::InvalidJson => "invalid_json", + Self::DuplicateField => "duplicate_field", + Self::StructuralLimit => "structural_limit", + Self::UnsupportedSchema => "unsupported_schema", + Self::InvalidEnvelope => "invalid_envelope", + Self::SelectionMismatch => "selection_mismatch", + Self::ScopeMismatch => "scope_mismatch", + Self::LineageConflict => "lineage_conflict", + Self::UnsupportedState => "unsupported_state", + Self::OutputLimit => "output_limit", + Self::SerializationFailed => "serialization_failed", + } + } +} +impl RequestRecordError { + pub fn json_bytes(self) -> Vec { + let t = truth(); + encode(&object(vec![("schemaVersion",s("rangoon.integrations.lnsat-request-error.v1")),("code",s(self.code())),("truth",t)])).unwrap_or_else(|_|b"{\"schemaVersion\":\"rangoon.integrations.lnsat-request-error.v1\",\"code\":\"serialization_failed\",\"truth\":{\"authenticity\":\"unverified\",\"authority\":\"none\",\"execution\":\"unavailable\",\"authoritativeOutcome\":\"unknown\",\"independentEffect\":\"not_observed\",\"currentness\":\"unverified\"}}".to_vec()) + } +} +impl core::fmt::Display for RequestRecordError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(self.code()) + } +} +impl std::error::Error for RequestRecordError {} +impl core::fmt::Debug for RequestRecordInput { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("RequestRecordInput { payload omitted }") + } +} +impl core::fmt::Debug for RequestRecordBody { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("RequestRecordBody { payload omitted }") + } +} +pub struct RequestRecordInspection { + host_json: Vec, + summary_json: Vec, + input_digest: Option, +} +impl RequestRecordInspection { + pub fn host_json(&self) -> &[u8] { + &self.host_json + } + pub fn summary_json(&self) -> &[u8] { + &self.summary_json + } + pub fn input_digest(&self) -> Option<&str> { + self.input_digest.as_deref() + } +} +impl core::fmt::Debug for RequestRecordInspection { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("RequestRecordInspection { redacted: true }") + } +} + +pub fn inspect_request_record( + input: RequestRecordInput, +) -> Result { + context(&input)?; + match &input.body { + RequestRecordBody::ReadUnavailable(r) => unavailable(&input, *r), + RequestRecordBody::Refused403(b) => refusal(&input, b), + RequestRecordBody::Body200(b) => body(&input, b), + } +} + +fn context(i: &RequestRecordInput) -> Result<(), RequestRecordError> { + for x in [&i.installation_id, &i.environment] { + text(x, 128)?; + } + for x in [&i.expected_project_ref, &i.expected_resource_ref] { + text(x, 512)?; + } + id(&i.selected_request_id, "arq_")?; + if let Some(t) = &i.read_at { + time(t)?; + } + Ok(()) +} +fn unavailable( + i: &RequestRecordInput, + r: ReadUnavailable, +) -> Result { + let f = match r { + ReadUnavailable::NotConfigured => "read_not_configured", + ReadUnavailable::TransportUnavailable => "read_transport_unavailable", + ReadUnavailable::Cancelled => "read_cancelled", + ReadUnavailable::Timeout => "read_timeout", + ReadUnavailable::Unauthenticated => "read_unauthenticated", + ReadUnavailable::UnsupportedTransport => "read_unsupported_transport", + }; + emit( + i, + ("read_unavailable", "not_observed", "not_observed"), + J::Null, + J::Null, + None, + Some(f), + None, + ) +} +fn refusal( + i: &RequestRecordInput, + b: &[u8], +) -> Result { + let v = parse(b)?; + let o = obj(&v)?; + keys(o, &["schema", "ok", "error"])?; + eq( + get(o, "schema")?, + WIRE, + RequestRecordError::UnsupportedSchema, + )?; + if boolean(get(o, "ok")?)? { + return Err(RequestRecordError::InvalidEnvelope); + } + let e = obj(get(o, "error")?)?; + keys(e, &["code"])?; + eq( + get(e, "code")?, + "gateway.action_request_record.denied", + RequestRecordError::InvalidEnvelope, + )?; + emit( + i, + ("read_rejected_unclassified", "not_observed", "not_observed"), + J::Null, + J::Null, + Some(hash(b)), + Some("native_read_rejected_unclassified"), + None, + ) +} +fn body(i: &RequestRecordInput, b: &[u8]) -> Result { + let v = parse(b)?; + let o = obj(&v)?; + keys( + o, + &[ + "schema", + "status", + "request_id", + "evaluation_state", + "request", + "evaluation", + "observations", + "evidence", + "security_activity_touched", + ], + )?; + eq( + get(o, "schema")?, + WIRE, + RequestRecordError::UnsupportedSchema, + )?; + let request_id = string(get(o, "request_id")?)?; + id(request_id, "arq_")?; + if request_id != i.selected_request_id { + return Err(RequestRecordError::SelectionMismatch); + } + let security = boolean(get(o, "security_activity_touched")?)?; + let observations = observations(get(o, "observations")?, get(o, "request")?)?; + let digest = Some(hash(b)); + match string(get(o, "status")?)? { + "degraded" => { + eq( + get(o, "evaluation_state")?, + "evaluation_unknown", + RequestRecordError::InvalidEnvelope, + )?; + null(get(o, "request")?)?; + null(get(o, "evaluation")?)?; + null(get(o, "evidence")?)?; + if !observations.is_empty() { + return Err(RequestRecordError::InvalidEnvelope); + } + emit( + i, + ("degraded", "evaluation_unknown", "not_observed"), + J::Null, + J::Bool(security), + digest, + None, + None, + ) + } + "complete" => complete(i, o, observations, security, digest), + _ => Err(RequestRecordError::UnsupportedState), + } +} +fn complete( + i: &RequestRecordInput, + o: &[(String, J)], + obs: Vec, + security: bool, + digest: Option, +) -> Result { + let request = request(obj(get(o, "request")?)?, i)?; + let eval = get(o, "evaluation")?; + let evidence_value = get(o, "evidence")?; + let (re, policy, ev_out, evidence_out, counts) = match eval { + J::Null => { + eq( + get(o, "evaluation_state")?, + "evaluation_unknown", + RequestRecordError::InvalidEnvelope, + )?; + null(evidence_value)?; + ("evaluation_unknown", "not_observed", J::Null, J::Null, None) + } + J::Obj(e) => { + evaluation(e, &request)?; + match string(get(e, "status")?)? { + "failed" => { + eq( + get(o, "evaluation_state")?, + "evaluation_failed", + RequestRecordError::InvalidEnvelope, + )?; + null(get(e, "policy_decision_id")?)?; + let r = string(get(e, "reason_code")?)?; + if !matches!(r, "evaluation_rejected" | "persistence_failed") { + return Err(RequestRecordError::UnsupportedState); + } + null(evidence_value)?; + commitments(&request, e, &obs)?; + ( + "evaluation_failed", + "not_observed", + J::Obj(canonical( + e, + &[ + "status", + "policy_decision_id", + "reason_code", + "recorded_at", + "evidence_digest", + ], + )?), + J::Null, + None, + ) + } + "recorded" => { + eq( + get(o, "evaluation_state")?, + "policy_recorded", + RequestRecordError::InvalidEnvelope, + )?; + id(string(get(e, "policy_decision_id")?)?, "pol_")?; + eq( + get(e, "reason_code")?, + "policy_recorded", + RequestRecordError::InvalidEnvelope, + )?; + let (x, p, c) = evidence(evidence_value, &request, e, &obs)?; + ( + "policy_recorded", + p, + J::Obj(canonical( + e, + &[ + "status", + "policy_decision_id", + "reason_code", + "recorded_at", + "evidence_digest", + ], + )?), + J::Obj(x), + Some(c), + ) + } + _ => return Err(RequestRecordError::UnsupportedState), + } + } + _ => return Err(RequestRecordError::InvalidEnvelope), + }; + emit( + i, + ("complete", re, policy), + object(vec![ + ("request", J::Obj(request)), + ("evaluation", ev_out), + ("observations", J::Arr(obs)), + ("evidence", evidence_out), + ]), + J::Bool(security), + digest, + None, + counts, + ) +} +fn request( + o: &[(String, J)], + i: &RequestRecordInput, +) -> Result, RequestRecordError> { + keys( + o, + &[ + "request_id", + "requester_ref", + "project_ref", + "resource_ref", + "packet_id", + "packet_sha256", + "action_digest", + "target_digest", + "configuration_digest", + "created_at", + "evidence_digest", + ], + )?; + id(string(get(o, "request_id")?)?, "arq_")?; + if string(get(o, "request_id")?)? != i.selected_request_id { + return Err(RequestRecordError::SelectionMismatch); + } + if string(get(o, "project_ref")?)? != i.expected_project_ref + || string(get(o, "resource_ref")?)? != i.expected_resource_ref + { + return Err(RequestRecordError::ScopeMismatch); + } + for n in ["requester_ref", "project_ref", "resource_ref", "packet_id"] { + text(string(get(o, n)?)?, MAX_STRING_BYTES)? + } + for n in [ + "packet_sha256", + "action_digest", + "target_digest", + "configuration_digest", + "evidence_digest", + ] { + digest(string(get(o, n)?)?)? + } + time(string(get(o, "created_at")?)?)?; + canonical( + o, + &[ + "request_id", + "project_ref", + "resource_ref", + "packet_id", + "packet_sha256", + "action_digest", + "target_digest", + "configuration_digest", + "created_at", + "evidence_digest", + ], + ) +} +fn evaluation(o: &[(String, J)], r: &[(String, J)]) -> Result<(), RequestRecordError> { + keys( + o, + &[ + "status", + "policy_decision_id", + "reason_code", + "recorded_at", + "evidence_digest", + ], + )?; + time(string(get(o, "recorded_at")?)?)?; + if string(get(o, "recorded_at")?)? != string(get(r, "created_at")?)? { + return Err(RequestRecordError::LineageConflict); + } + digest(string(get(o, "evidence_digest")?)?)?; + Ok(()) +} + +fn observations(v: &J, r: &J) -> Result, RequestRecordError> { + let a = array(v)?; + if a.len() > MAX_OBSERVATIONS { + return Err(RequestRecordError::StructuralLimit); + }; + let root = match r { + J::Obj(x) => Some(x), + J::Null => None, + _ => return Err(RequestRecordError::InvalidEnvelope), + }; + let mut replay = false; + let mut conflict = false; + let mut out = Vec::new(); + for row in a { + let o = obj(row)?; + keys( + o, + &["kind", "submitted_digest", "observed_at", "evidence_digest"], + )?; + let kind = string(get(o, "kind")?)?; + digest(string(get(o, "submitted_digest")?)?)?; + digest(string(get(o, "evidence_digest")?)?)?; + time(string(get(o, "observed_at")?)?)?; + if let Some(root) = root { + if string(get(o, "observed_at")?)? < string(get(root, "created_at")?)? { + return Err(RequestRecordError::LineageConflict); + } + let p = string(get(root, "packet_sha256")?)?; + match kind { + "replay" if !replay => { + replay = true; + if string(get(o, "submitted_digest")?)? != p { + return Err(RequestRecordError::LineageConflict); + } + } + "conflict" if !conflict => { + conflict = true; + if string(get(o, "submitted_digest")?)? == p { + return Err(RequestRecordError::LineageConflict); + } + } + "replay" | "conflict" => return Err(RequestRecordError::LineageConflict), + _ => return Err(RequestRecordError::UnsupportedState), + } + } else if !matches!(kind, "replay" | "conflict") { + return Err(RequestRecordError::UnsupportedState); + } + if let Some(root) = root { + let encoded = compact(&[ + get(root, "request_id")?, + get(o, "kind")?, + get(o, "submitted_digest")?, + get(o, "observed_at")?, + ])?; + if hash(format!("lnsat.action_request.observation.v1\n{encoded}").as_bytes()) + != string(get(o, "evidence_digest")?)? + { + return Err(RequestRecordError::LineageConflict); + } + } + out.push(J::Obj(canonical( + o, + &["kind", "submitted_digest", "observed_at", "evidence_digest"], + )?)) + } + Ok(out) +} +const FAMILIES: &[&str] = &[ + "approvals", + "approval_decisions", + "authorization_attempts", + "authorizations", + "operations", + "consumptions", + "operation_attempts", + "receipts", + "reconciliations", + "states", +]; +type NativeObject = Vec<(String, J)>; +type EvidenceProjection = (NativeObject, &'static str, NativeObject); + +fn evidence( + v: &J, + r: &[(String, J)], + e: &[(String, J)], + obs: &[J], +) -> Result { + let o = obj(v)?; + keys( + o, + &[ + "schema", + "policy", + "approvals", + "approval_decisions", + "authorization_attempts", + "authorizations", + "operations", + "consumptions", + "operation_attempts", + "receipts", + "reconciliations", + "states", + ], + )?; + eq( + get(o, "schema")?, + LINKED_WIRE, + RequestRecordError::UnsupportedSchema, + )?; + let p = policy(obj(get(o, "policy")?)?, r, e)?; + let decision = string(get(&p, "decision")?)?; + let requires = integer(get(&p, "requires_approval")?)?; + let valid = (decision == "approval_required" && requires == 1) + || (matches!(decision, "allow" | "deny") && requires == 0); + if !valid { + return Err(RequestRecordError::LineageConflict); + }; + let mut out = vec![ + ("schema".into(), s(LINKED_WIRE)), + ("policy".into(), J::Obj(p.clone())), + ]; + let mut counts = Vec::new(); + // Reserve a conservative escaped request/context/source/omission envelope + // before retaining projected variable rows. This is a byte quota, not an + // allocator, elapsed-time, or hostile-caller containment guarantee. + let mut remaining_rows = MAX_HOST_BYTES - 49_152; + for f in FAMILIES { + let rows = array(get(o, f)?)?; + family(f, rows, &p)?; + let order = spec(f).ok_or(RequestRecordError::InvalidEnvelope)?.0; + let projected = rows + .iter() + .map(|x| { + let q = obj(x)?; + let q = if *f == "approval_decisions" { + redact(q, &["reason"]) + } else { + canonical(q, order)? + }; + if *f == "approval_decisions" { + let redacted_order = &[ + "approval_decision_id", + "approval_request_id", + "policy_decision_id", + "decision", + "decided_at", + "expires_at", + "approval_gate_satisfied", + ]; + let q = canonical(&q, redacted_order)?; + remaining_rows = remaining_rows + .checked_sub(encode(&J::Obj(q.clone()))?.len() + 1) + .ok_or(RequestRecordError::OutputLimit)?; + return Ok(q); + } + remaining_rows = remaining_rows + .checked_sub(encode(&J::Obj(q.clone()))?.len() + 1) + .ok_or(RequestRecordError::OutputLimit)?; + Ok(q) + }) + .collect::, RequestRecordError>>()? + .into_iter() + .map(J::Obj) + .collect(); + out.push(((*f).into(), J::Arr(projected))); + counts.push(((*f).into(), J::Num(rows.len().to_string()))) + } + graph(o, &p)?; + state_rules(o)?; + commitments(r, e, obs)?; + Ok(( + out, + match decision { + "allow" => "allow", + "deny" => "deny", + "approval_required" => "approval_required", + _ => return Err(RequestRecordError::UnsupportedState), + }, + counts, + )) +} +fn policy( + o: &[(String, J)], + r: &[(String, J)], + e: &[(String, J)], +) -> Result, RequestRecordError> { + keys( + o, + &[ + "decision_id", + "evaluated_at", + "expires_at", + "decision", + "requires_approval", + ], + )?; + id(string(get(o, "decision_id")?)?, "pol_")?; + if string(get(o, "decision_id")?)? != string(get(e, "policy_decision_id")?)? { + return Err(RequestRecordError::LineageConflict); + } + for n in ["evaluated_at", "expires_at"] { + time(string(get(o, n)?)?)? + } + if string(get(o, "evaluated_at")?)? != string(get(r, "created_at")?)? + || string(get(o, "expires_at")?)? < string(get(o, "evaluated_at")?)? + { + return Err(RequestRecordError::LineageConflict); + } + canonical( + o, + &[ + "decision_id", + "evaluated_at", + "expires_at", + "decision", + "requires_approval", + ], + ) +} +fn family(n: &str, a: &[J], p: &[(String, J)]) -> Result<(), RequestRecordError> { + if a.len() > MAX_ARRAY_ITEMS { + return Err(RequestRecordError::StructuralLimit); + } + let (k, idn, pfx) = spec(n).ok_or(RequestRecordError::InvalidEnvelope)?; + let mut seen = Vec::new(); + for x in a { + let o = obj(x)?; + keys(o, k)?; + let ident = string(get(o, idn)?)?; + id(ident, pfx)?; + if seen.contains(&ident) { + return Err(RequestRecordError::LineageConflict); + } + seen.push(ident); + row(n, o, p)? + } + Ok(()) +} +fn spec(n: &str) -> Option<(&'static [&'static str], &'static str, &'static str)> { + Some(match n { + "approvals" => ( + &[ + "approval_request_id", + "policy_decision_id", + "status", + "requested_at", + "expires_at", + ], + "approval_request_id", + "apr_", + ), + "approval_decisions" => ( + &[ + "approval_decision_id", + "approval_request_id", + "policy_decision_id", + "decision", + "reason", + "decided_at", + "expires_at", + "approval_gate_satisfied", + ], + "approval_decision_id", + "apd_", + ), + "authorization_attempts" => ( + &[ + "authorization_attempt_id", + "approval_decision_id", + "approval_request_id", + "policy_decision_id", + "result_status", + "requested_at", + "expires_at", + ], + "authorization_attempt_id", + "aat_", + ), + "authorizations" => ( + &[ + "authorization_id", + "authorization_attempt_id", + "approval_decision_id", + "policy_decision_id", + "issued_at", + "expires_at", + ], + "authorization_id", + "xau_", + ), + "operations" => ( + &[ + "operation_id", + "authorization_id", + "created_at", + "expires_at", + ], + "operation_id", + "opn_", + ), + "consumptions" => ( + &[ + "consumption_id", + "authorization_id", + "operation_id", + "consumed_at", + ], + "consumption_id", + "cpc_", + ), + "operation_attempts" => ( + &[ + "operation_attempt_id", + "operation_id", + "attempt_sequence", + "created_at", + ], + "operation_attempt_id", + "opa_", + ), + "receipts" => ( + &[ + "receipt_id", + "operation_id", + "operation_attempt_id", + "authorization_id", + "consumption_id", + "verification_status", + "result_digest", + "received_at", + ], + "receipt_id", + "rcp_", + ), + "reconciliations" => ( + &[ + "reconciliation_id", + "operation_id", + "operation_attempt_id", + "receipt_id", + "status", + "observed_result_digest", + "recorded_at", + ], + "reconciliation_id", + "rec_", + ), + "states" => ( + &[ + "state_event_id", + "target_entity_id", + "target_entity_kind", + "state_sequence", + "state", + "prior_state_event_id", + "prior_state_sequence", + "effective_at", + "state_digest", + ], + "state_event_id", + "ste_", + ), + _ => return None, + }) +} +fn row(n: &str, o: &[(String, J)], p: &[(String, J)]) -> Result<(), RequestRecordError> { + let pairs: &[(&str, &str)] = match n { + "approvals" => &[("policy_decision_id", "pol_")], + "approval_decisions" => &[ + ("approval_request_id", "apr_"), + ("policy_decision_id", "pol_"), + ], + "authorization_attempts" => &[ + ("approval_decision_id", "apd_"), + ("approval_request_id", "apr_"), + ("policy_decision_id", "pol_"), + ], + "authorizations" => &[ + ("authorization_attempt_id", "aat_"), + ("approval_decision_id", "apd_"), + ("policy_decision_id", "pol_"), + ], + "operations" => &[("authorization_id", "xau_")], + "consumptions" => &[("authorization_id", "xau_"), ("operation_id", "opn_")], + "operation_attempts" => &[("operation_id", "opn_")], + "receipts" => &[ + ("operation_id", "opn_"), + ("operation_attempt_id", "opa_"), + ("authorization_id", "xau_"), + ("consumption_id", "cpc_"), + ], + "reconciliations" => &[("operation_id", "opn_"), ("operation_attempt_id", "opa_")], + "states" => &[], + _ => return Err(RequestRecordError::InvalidEnvelope), + }; + for (f, x) in pairs { + id(string(get(o, f)?)?, x)? + } + if matches!( + n, + "approvals" | "approval_decisions" | "authorization_attempts" | "authorizations" + ) && string(get(o, "policy_decision_id")?)? != string(get(p, "decision_id")?)? + { + return Err(RequestRecordError::LineageConflict); + } + for (k, v) in o { + if k.ends_with("_at") { + time(string(v)?)? + } + if k.ends_with("_digest") + && !(n == "reconciliations" && k == "observed_result_digest" && matches!(v, J::Null)) + { + digest(string(v)?)? + } + } + match n { + "approvals" => eq( + get(o, "status")?, + "requested", + RequestRecordError::UnsupportedState, + )?, + "approval_decisions" => { + let d = string(get(o, "decision")?)?; + let r = string(get(o, "reason")?)?; + let g = integer(get(o, "approval_gate_satisfied")?)?; + if !matches!( + r, + "approval.operator_approved" + | "approval.operator_denied" + | "approval.scope_rejected" + | "approval.evidence_insufficient" + | "approval.request_superseded" + ) || !((d == "approved" && r == "approval.operator_approved" && g == 1) + || (d == "denied" && r != "approval.operator_approved" && g == 0)) + { + return Err(RequestRecordError::UnsupportedState); + } + } + "authorization_attempts" + if !matches!( + string(get(o, "result_status")?)?, + "persistence_prepared" | "rejected" | "failed" + ) => + { + return Err(RequestRecordError::UnsupportedState); + } + "operation_attempts" => { + let q = integer(get(o, "attempt_sequence")?)?; + if !(1..=64).contains(&q) { + return Err(RequestRecordError::StructuralLimit); + } + } + "receipts" => eq( + get(o, "verification_status")?, + "accepted", + RequestRecordError::UnsupportedState, + )?, + "reconciliations" => { + let s = string(get(o, "status")?)?; + match s { + "pending" | "unresolved" => { + null(get(o, "receipt_id")?)?; + null(get(o, "observed_result_digest")?)? + } + "matched" | "mismatch" => { + id(string(get(o, "receipt_id")?)?, "rcp_")?; + digest(string(get(o, "observed_result_digest")?)?)? + } + _ => return Err(RequestRecordError::UnsupportedState), + } + } + "states" => state(o)?, + _ => {} + } + Ok(()) +} +fn state(o: &[(String, J)]) -> Result<(), RequestRecordError> { + let kind = string(get(o, "target_entity_kind")?)?; + let t = string(get(o, "target_entity_id")?)?; + match kind { + "execution_authorization" => id(t, "xau_")?, + "operation" => id(t, "opn_")?, + "operation_attempt" => id(t, "opa_")?, + _ => return Err(RequestRecordError::UnsupportedState), + } + let n = integer(get(o, "state_sequence")?)?; + if !(1..=64).contains(&n) { + return Err(RequestRecordError::StructuralLimit); + } + if n == 1 { + null(get(o, "prior_state_event_id")?)?; + null(get(o, "prior_state_sequence")?)? + } else { + id(string(get(o, "prior_state_event_id")?)?, "ste_")?; + if integer(get(o, "prior_state_sequence")?)? != n - 1 { + return Err(RequestRecordError::LineageConflict); + } + } + let state = string(get(o, "state")?)?; + let ok = match kind { + "execution_authorization" => matches!( + state, + "active" | "cancelled" | "revoked" | "expired" | "consumed" + ), + "operation" => matches!( + state, + "prepared" | "dispatching" | "outcome_unknown" | "completed" | "failed" + ), + _ => matches!( + state, + "dispatching" | "outcome_unknown" | "completed" | "failed" + ), + }; + if !ok { + return Err(RequestRecordError::UnsupportedState); + } + time(string(get(o, "effective_at")?)?)?; + digest(string(get(o, "state_digest")?)?)?; + Ok(()) +} +fn graph(o: &[(String, J)], _p: &[(String, J)]) -> Result<(), RequestRecordError> { + let approvals = objects(array(get(o, "approvals")?)?)?; + let decisions = objects(array(get(o, "approval_decisions")?)?)?; + let attempts = objects(array(get(o, "authorization_attempts")?)?)?; + let auths = objects(array(get(o, "authorizations")?)?)?; + let ops = objects(array(get(o, "operations")?)?)?; + let cons = objects(array(get(o, "consumptions")?)?)?; + let opas = objects(array(get(o, "operation_attempts")?)?)?; + let receipts = objects(array(get(o, "receipts")?)?)?; + let recs = objects(array(get(o, "reconciliations")?)?)?; + let states = objects(array(get(o, "states")?)?)?; + for d in &decisions { + require( + &approvals, + "approval_request_id", + string(get(d, "approval_request_id")?)?, + )?; + } + for a in &attempts { + let d = require( + &decisions, + "approval_decision_id", + string(get(a, "approval_decision_id")?)?, + )?; + require( + &approvals, + "approval_request_id", + string(get(a, "approval_request_id")?)?, + )?; + if string(get(d, "approval_request_id")?)? != string(get(a, "approval_request_id")?)? + || string(get(d, "decision")?)? == "denied" + { + return Err(RequestRecordError::LineageConflict); + } + } + for a in &auths { + let q = require( + &attempts, + "authorization_attempt_id", + string(get(a, "authorization_attempt_id")?)?, + )?; + if string(get(q, "result_status")?)? != "persistence_prepared" + || string(get(q, "approval_decision_id")?)? != string(get(a, "approval_decision_id")?)? + { + return Err(RequestRecordError::LineageConflict); + } + } + for x in &ops { + require( + &auths, + "authorization_id", + string(get(x, "authorization_id")?)?, + )?; + } + for x in &cons { + let au = string(get(x, "authorization_id")?)?; + let op = string(get(x, "operation_id")?)?; + let owner = require(&ops, "operation_id", op)?; + if string(get(owner, "authorization_id")?)? != au + || count(&cons, "authorization_id", au) > 1 + || count(&cons, "operation_id", op) > 1 + { + return Err(RequestRecordError::LineageConflict); + } + } + for x in &opas { + require(&ops, "operation_id", string(get(x, "operation_id")?)?)?; + } + for x in &receipts { + let op = string(get(x, "operation_id")?)?; + let at = string(get(x, "operation_attempt_id")?)?; + let operation = require(&ops, "operation_id", op)?; + let attempt = require(&opas, "operation_attempt_id", at)?; + if string(get(operation, "authorization_id")?)? != string(get(x, "authorization_id")?)? + || string(get(attempt, "operation_id")?)? != op + { + return Err(RequestRecordError::LineageConflict); + } + if count(&receipts, "operation_id", op) > 1 + || count(&receipts, "operation_attempt_id", at) > 1 + { + return Err(RequestRecordError::LineageConflict); + } + } + for x in &recs { + let op = string(get(x, "operation_id")?)?; + require(&ops, "operation_id", op)?; + let attempt = require( + &opas, + "operation_attempt_id", + string(get(x, "operation_attempt_id")?)?, + )?; + if string(get(attempt, "operation_id")?)? != op { + return Err(RequestRecordError::LineageConflict); + } + if let J::Str(rcp) = get(x, "receipt_id")? { + let z = require(&receipts, "receipt_id", rcp)?; + if string(get(z, "operation_id")?)? != string(get(x, "operation_id")?)? + || string(get(z, "operation_attempt_id")?)? + != string(get(x, "operation_attempt_id")?)? + { + return Err(RequestRecordError::LineageConflict); + } + let same = + string(get(z, "result_digest")?)? == string(get(x, "observed_result_digest")?)?; + if (string(get(x, "status")?)? == "matched") != same { + return Err(RequestRecordError::LineageConflict); + } + } + } + for x in &opas { + let op = string(get(x, "operation_id")?)?; + let n = integer(get(x, "attempt_sequence")?)?; + if count_le(&opas, "operation_id", op, "attempt_sequence", n) != n as usize { + return Err(RequestRecordError::LineageConflict); + } + } + for x in &states { + let kind = string(get(x, "target_entity_kind")?)?; + let idv = string(get(x, "target_entity_id")?)?; + let present = match kind { + "execution_authorization" => has(&auths, "authorization_id", idv), + "operation" => has(&ops, "operation_id", idv), + "operation_attempt" => has(&opas, "operation_attempt_id", idv), + _ => false, + }; + if !present { + return Err(RequestRecordError::LineageConflict); + } + if integer(get(x, "state_sequence")?)? > 1 { + let prev = string(get(x, "prior_state_event_id")?)?; + if !states.iter().any(|q| { + string(get(q, "state_event_id").unwrap()).unwrap() == prev + && string(get(q, "target_entity_id").unwrap()).unwrap() == idv + && integer(get(q, "state_sequence").unwrap()).unwrap() + 1 + == integer(get(x, "state_sequence").unwrap()).unwrap() + }) { + return Err(RequestRecordError::LineageConflict); + } + } + } + Ok(()) +} +fn require<'a>( + a: &'a Vec<&'a [(String, J)]>, + k: &str, + v: &str, +) -> Result<&'a [(String, J)], RequestRecordError> { + a.iter() + .copied() + .find(|x| string(get(x, k).unwrap()).ok() == Some(v)) + .ok_or(RequestRecordError::LineageConflict) +} +fn has(a: &Vec<&[(String, J)]>, k: &str, v: &str) -> bool { + require(a, k, v).is_ok() +} +fn count(a: &Vec<&[(String, J)]>, k: &str, v: &str) -> usize { + a.iter() + .filter(|x| string(get(x, k).unwrap()).unwrap() == v) + .count() +} +fn count_le(a: &Vec<&[(String, J)]>, g: &str, v: &str, nm: &str, n: i64) -> usize { + a.iter() + .filter(|x| { + string(get(x, g).unwrap()).unwrap() == v && integer(get(x, nm).unwrap()).unwrap() <= n + }) + .count() +} +fn state_rules(o: &[(String, J)]) -> Result<(), RequestRecordError> { + let states = objects(array(get(o, "states")?)?)?; + let auths = objects(array(get(o, "authorizations")?)?)?; + let ops = objects(array(get(o, "operations")?)?)?; + let attempts = objects(array(get(o, "operation_attempts")?)?)?; + let cons = objects(array(get(o, "consumptions")?)?)?; + let receipts = objects(array(get(o, "receipts")?)?)?; + for state in &states { + let kind = string(get(state, "target_entity_kind")?)?; + let target = string(get(state, "target_entity_id")?)?; + let seq = integer(get(state, "state_sequence")?)?; + let at = string(get(state, "effective_at")?)?; + let same: Vec<_> = states + .iter() + .filter(|x| { + string(get(x, "target_entity_kind").unwrap()).unwrap() == kind + && string(get(x, "target_entity_id").unwrap()).unwrap() == target + }) + .copied() + .collect(); + if same.iter().enumerate().any(|(index, row)| { + integer(get(row, "state_sequence").unwrap()).unwrap() != index as i64 + 1 + }) { + return Err(RequestRecordError::LineageConflict); + } + if same.len() > 64 + || same + .iter() + .filter(|x| integer(get(x, "state_sequence").unwrap()).unwrap() == seq) + .count() + != 1 + { + return Err(RequestRecordError::LineageConflict); + } + if seq == 1 { + match kind { + "execution_authorization" => { + let a = require(&auths, "authorization_id", target)?; + if string(get(a, "issued_at")?)? != at + || string(get(state, "state")?)? != "active" + { + return Err(RequestRecordError::LineageConflict); + } + } + "operation" => { + let x = require(&ops, "operation_id", target)?; + if string(get(x, "created_at")?)? != at + || string(get(state, "state")?)? != "prepared" + { + return Err(RequestRecordError::LineageConflict); + } + } + "operation_attempt" => { + let x = require(&attempts, "operation_attempt_id", target)?; + if string(get(x, "created_at")?)? != at + || string(get(state, "state")?)? != "dispatching" + { + return Err(RequestRecordError::LineageConflict); + } + } + _ => return Err(RequestRecordError::LineageConflict), + } + } else { + let prev = require( + &same, + "state_event_id", + string(get(state, "prior_state_event_id")?)?, + )?; + if integer(get(prev, "state_sequence")?)? != seq - 1 + || string(get(prev, "effective_at")?)? > at + { + return Err(RequestRecordError::LineageConflict); + } + let from = string(get(prev, "state")?)?; + let to = string(get(state, "state")?)?; + let good = match kind { + "operation" => matches!( + (from, to), + ("prepared", "dispatching") + | ("dispatching", "outcome_unknown") + | ("dispatching", "completed") + | ("dispatching", "failed") + | ("outcome_unknown", "completed") + ), + "operation_attempt" => matches!( + (from, to), + ("dispatching", "outcome_unknown") + | ("dispatching", "completed") + | ("dispatching", "failed") + | ("outcome_unknown", "completed") + ), + "execution_authorization" => matches!( + (from, to), + ("active", "cancelled") + | ("active", "revoked") + | ("active", "expired") + | ("active", "consumed") + ), + _ => false, + }; + if !good { + return Err(RequestRecordError::LineageConflict); + } + } + } + for a in &auths { + let idv = string(get(a, "authorization_id")?)?; + let issued = string(get(a, "issued_at")?)?; + let expires = string(get(a, "expires_at")?)?; + if expires < issued { + return Err(RequestRecordError::LineageConflict); + } + let ss: Vec<_> = states + .iter() + .filter(|x| { + string(get(x, "target_entity_kind").unwrap()).unwrap() == "execution_authorization" + && string(get(x, "target_entity_id").unwrap()).unwrap() == idv + }) + .copied() + .collect(); + let terminal: Vec<_> = ss + .iter() + .filter(|x| { + matches!( + string(get(x, "state").unwrap()).unwrap(), + "cancelled" | "revoked" | "expired" | "consumed" + ) + }) + .collect(); + if ss.is_empty() || ss.len() > 2 || terminal.len() > 1 { + return Err(RequestRecordError::LineageConflict); + } + let used = cons + .iter() + .any(|x| string(get(x, "authorization_id").unwrap()).unwrap() == idv); + if used + != terminal + .iter() + .any(|x| string(get(x, "state").unwrap()).unwrap() == "consumed") + { + return Err(RequestRecordError::LineageConflict); + } + if let Some(t) = terminal.first() { + let name = string(get(t, "state")?)?; + let time = string(get(t, "effective_at")?)?; + if time < issued + || (name == "expired" && time != expires) + || (name != "expired" && time >= expires) + { + return Err(RequestRecordError::LineageConflict); + } + } + } + for operation in &ops { + let idv = string(get(operation, "operation_id")?)?; + let ss: Vec<_> = states + .iter() + .filter(|x| { + string(get(x, "target_entity_kind").unwrap()).unwrap() == "operation" + && string(get(x, "target_entity_id").unwrap()).unwrap() == idv + }) + .copied() + .collect(); + if ss.is_empty() { + return Err(RequestRecordError::LineageConflict); + } + let completed = ss + .iter() + .any(|x| string(get(x, "state").unwrap()).unwrap() == "completed"); + let r = receipts + .iter() + .filter(|x| string(get(x, "operation_id").unwrap()).unwrap() == idv) + .count(); + if (completed && r != 1) || (!completed && r != 0) { + return Err(RequestRecordError::LineageConflict); + } + } + for attempt in &attempts { + let idv = string(get(attempt, "operation_attempt_id")?)?; + let ss: Vec<_> = states + .iter() + .filter(|x| { + string(get(x, "target_entity_kind").unwrap()).unwrap() == "operation_attempt" + && string(get(x, "target_entity_id").unwrap()).unwrap() == idv + }) + .copied() + .collect(); + if ss.is_empty() { + return Err(RequestRecordError::LineageConflict); + } + let completed = ss + .iter() + .any(|x| string(get(x, "state").unwrap()).unwrap() == "completed"); + let r = receipts + .iter() + .filter(|x| string(get(x, "operation_attempt_id").unwrap()).unwrap() == idv) + .count(); + if (completed && r != 1) || (!completed && r != 0) { + return Err(RequestRecordError::LineageConflict); + } + } + for r in &receipts { + let c = require(&cons, "consumption_id", string(get(r, "consumption_id")?)?)?; + if string(get(c, "authorization_id")?)? != string(get(r, "authorization_id")?)? + || string(get(c, "operation_id")?)? != string(get(r, "operation_id")?)? + { + return Err(RequestRecordError::LineageConflict); + } + } + Ok(()) +} +fn commitments(r: &[(String, J)], e: &[(String, J)], obs: &[J]) -> Result<(), RequestRecordError> { + let v = compact(&[ + get(r, "request_id")?, + get(r, "packet_id")?, + get(r, "packet_sha256")?, + get(r, "project_ref")?, + get(r, "resource_ref")?, + get(e, "status")?, + get(e, "policy_decision_id")?, + get(e, "reason_code")?, + get(e, "recorded_at")?, + ])?; + if hash(format!("lnsat.action_request.evaluation.v1\n{v}").as_bytes()) + != string(get(e, "evidence_digest")?)? + { + return Err(RequestRecordError::LineageConflict); + } + for x in obs { + let o = obj(x)?; + let v = compact(&[ + get(r, "request_id")?, + get(o, "kind")?, + get(o, "submitted_digest")?, + get(o, "observed_at")?, + ])?; + if hash(format!("lnsat.action_request.observation.v1\n{v}").as_bytes()) + != string(get(o, "evidence_digest")?)? + { + return Err(RequestRecordError::LineageConflict); + } + } + Ok(()) +} + +fn emit( + i: &RequestRecordInput, + states: (&str, &str, &str), + native: J, + security: J, + d: Option, + failure: Option<&str>, + counts: Option>, +) -> Result { + let (a, e, p) = states; + let truth = truth(); + let omissions = omissions(); + let source = object(vec![ + ("repository", s("hypler-dev/LNSAT")), + ("commit", s(SOURCE_COMMIT)), + ("wireContract", s(WIRE)), + ("compatibility", s("source_pinned_not_runtime_qualified")), + ("transportAuthentication", s("unverified")), + ]); + let select = object(vec![ + ("installationId", s(&i.installation_id)), + ("environment", s(&i.environment)), + ("requestId", s(&i.selected_request_id)), + ("expectedProjectRef", s(&i.expected_project_ref)), + ("expectedResourceRef", s(&i.expected_resource_ref)), + ("readAt", i.read_at.as_ref().map_or(J::Null, |x| s(x))), + ]); + let host = object(vec![ + ( + "schemaVersion", + s("rangoon.integrations.lnsat-request-record.v1"), + ), + ("profileVersion", J::Num("1".into())), + ("source", source), + ("selection", select), + ("recordAvailability", s(a)), + ("reportedEvaluation", s(e)), + ("reportedPolicy", s(p)), + ("securityActivityTouched", security.clone()), + ("inputDigest", d.as_ref().map_or(J::Null, |x| s(x))), + ("native", native), + ("readFailure", failure.map_or(J::Null, s)), + ("truth", truth.clone()), + ("omissions", omissions.clone()), + ]); + let summary = object(vec![ + ( + "schemaVersion", + s("rangoon.integrations.lnsat-request-summary.v1"), + ), + ("recordAvailability", s(a)), + ("reportedEvaluation", s(e)), + ("reportedPolicy", s(p)), + ("readFailure", failure.map_or(J::Null, s)), + ("securityActivityTouched", security), + ("familyCounts", counts.map_or(J::Null, J::Obj)), + ("truth", truth), + ("omissions", omissions), + ]); + let h = encode(&host)?; + let sm = encode(&summary)?; + if h.len() > MAX_HOST_BYTES || sm.len() > MAX_SUMMARY_BYTES { + return Err(RequestRecordError::OutputLimit); + } + Ok(RequestRecordInspection { + host_json: h, + summary_json: sm, + input_digest: d, + }) +} +struct Parser<'a> { + s: &'a str, + i: usize, + n: usize, +} +fn parse(b: &[u8]) -> Result { + if b.len() > MAX_INPUT_BYTES { + return Err(RequestRecordError::InputLimit); + } + let s = core::str::from_utf8(b).map_err(|_| RequestRecordError::InvalidEncoding)?; + if s.as_bytes().starts_with(&[0xef, 0xbb, 0xbf]) { + return Err(RequestRecordError::InvalidEncoding); + } + let mut p = Parser { s, i: 0, n: 0 }; + p.ws(); + let v = p.value(1)?; + p.ws(); + if p.i != s.len() { + return Err(RequestRecordError::InvalidJson); + } + Ok(v) +} +impl Parser<'_> { + fn ws(&mut self) { + while self + .s + .as_bytes() + .get(self.i) + .is_some_and(|b| matches!(b, b' ' | b'\n' | b'\r' | b'\t')) + { + self.i += 1 + } + } + fn value(&mut self, d: usize) -> Result { + if d > MAX_DEPTH { + return Err(RequestRecordError::StructuralLimit); + } + self.n += 1; + if self.n > MAX_VALUES { + return Err(RequestRecordError::StructuralLimit); + } + self.ws(); + match self.s.as_bytes().get(self.i) { + Some(b'{') => self.object(d), + Some(b'[') => self.array(d), + Some(b'"') => Ok(J::Str(self.string()?)), + Some(b't') => { + self.word("true")?; + Ok(J::Bool(true)) + } + Some(b'f') => { + self.word("false")?; + Ok(J::Bool(false)) + } + Some(b'n') => { + self.word("null")?; + Ok(J::Null) + } + Some(b'-' | b'0'..=b'9') => self.number(), + _ => Err(RequestRecordError::InvalidJson), + } + } + fn object(&mut self, d: usize) -> Result { + self.i += 1; + self.ws(); + let mut o = Vec::new(); + if self.s.as_bytes().get(self.i) == Some(&b'}') { + self.i += 1; + return Ok(J::Obj(o)); + } + loop { + self.ws(); + if self.s.as_bytes().get(self.i) != Some(&b'"') { + return Err(RequestRecordError::InvalidJson); + } + let k = self.string()?; + if o.iter().any(|x: &(String, J)| x.0 == k) { + return Err(RequestRecordError::DuplicateField); + } + self.ws(); + if self.s.as_bytes().get(self.i) != Some(&b':') { + return Err(RequestRecordError::InvalidJson); + } + self.i += 1; + let v = self.value(d + 1)?; + o.push((k, v)); + if o.len() > MAX_OBJECT_FIELDS { + return Err(RequestRecordError::StructuralLimit); + } + self.ws(); + match self.s.as_bytes().get(self.i) { + Some(b',') => self.i += 1, + Some(b'}') => { + self.i += 1; + break; + } + _ => return Err(RequestRecordError::InvalidJson), + } + } + Ok(J::Obj(o)) + } + fn array(&mut self, d: usize) -> Result { + self.i += 1; + self.ws(); + let mut a = Vec::new(); + if self.s.as_bytes().get(self.i) == Some(&b']') { + self.i += 1; + return Ok(J::Arr(a)); + } + loop { + a.push(self.value(d + 1)?); + if a.len() > MAX_ARRAY_ITEMS { + return Err(RequestRecordError::StructuralLimit); + } + self.ws(); + match self.s.as_bytes().get(self.i) { + Some(b',') => self.i += 1, + Some(b']') => { + self.i += 1; + break; + } + _ => return Err(RequestRecordError::InvalidJson), + } + } + Ok(J::Arr(a)) + } + fn word(&mut self, w: &str) -> Result<(), RequestRecordError> { + if self.s[self.i..].starts_with(w) { + self.i += w.len(); + Ok(()) + } else { + Err(RequestRecordError::InvalidJson) + } + } + fn number(&mut self) -> Result { + let st = self.i; + let b = self.s.as_bytes(); + if b[self.i] == b'-' { + self.i += 1 + } + if b.get(self.i) == Some(&b'0') { + self.i += 1 + } else { + let x = self.i; + while b.get(self.i).is_some_and(u8::is_ascii_digit) { + self.i += 1 + } + if x == self.i { + return Err(RequestRecordError::InvalidJson); + } + } + if b.get(self.i) == Some(&b'.') { + self.i += 1; + let x = self.i; + while b.get(self.i).is_some_and(u8::is_ascii_digit) { + self.i += 1 + } + if x == self.i { + return Err(RequestRecordError::InvalidJson); + } + } + if matches!(b.get(self.i), Some(b'e' | b'E')) { + self.i += 1; + if matches!(b.get(self.i), Some(b'+' | b'-')) { + self.i += 1 + } + let x = self.i; + while b.get(self.i).is_some_and(u8::is_ascii_digit) { + self.i += 1 + } + if x == self.i { + return Err(RequestRecordError::InvalidJson); + } + } + let x = &self.s[st..self.i]; + if x.parse::().ok().filter(|x| x.is_finite()).is_none() { + return Err(RequestRecordError::InvalidJson); + } + Ok(J::Num(x.into())) + } + fn string(&mut self) -> Result { + self.i += 1; + let mut o = String::new(); + loop { + let c = self.s[self.i..] + .chars() + .next() + .ok_or(RequestRecordError::InvalidJson)?; + self.i += c.len_utf8(); + match c { + '"' => break, + '\\' => { + let e = self.s[self.i..] + .chars() + .next() + .ok_or(RequestRecordError::InvalidJson)?; + self.i += e.len_utf8(); + match e { + '"' => o.push('"'), + '\\' => o.push('\\'), + '/' => o.push('/'), + 'b' => o.push('\u{08}'), + 'f' => o.push('\u{0c}'), + 'n' => o.push('\n'), + 'r' => o.push('\r'), + 't' => o.push('\t'), + 'u' => { + let x = self.hex()?; + if (0xd800..=0xdbff).contains(&x) { + if !self.s[self.i..].starts_with("\\u") { + return Err(RequestRecordError::InvalidJson); + } + self.i += 2; + let y = self.hex()?; + if !(0xdc00..=0xdfff).contains(&y) { + return Err(RequestRecordError::InvalidJson); + } + o.push( + char::from_u32(0x10000 + ((x - 0xd800) << 10) + (y - 0xdc00)) + .ok_or(RequestRecordError::InvalidJson)?, + ) + } else if (0xdc00..=0xdfff).contains(&x) { + return Err(RequestRecordError::InvalidJson); + } else { + o.push(char::from_u32(x).ok_or(RequestRecordError::InvalidJson)?) + } + } + _ => return Err(RequestRecordError::InvalidJson), + } + } + x if x < '\u{20}' => return Err(RequestRecordError::InvalidJson), + x => o.push(x), + } + if o.len() > MAX_STRING_BYTES { + return Err(RequestRecordError::StructuralLimit); + } + } + Ok(o) + } + fn hex(&mut self) -> Result { + if self.i + 4 > self.s.len() { + return Err(RequestRecordError::InvalidJson); + } + let bytes = self + .s + .as_bytes() + .get(self.i..self.i + 4) + .ok_or(RequestRecordError::InvalidJson)?; + if !bytes.iter().all(u8::is_ascii_hexdigit) { + return Err(RequestRecordError::InvalidJson); + } + let x = core::str::from_utf8(bytes).map_err(|_| RequestRecordError::InvalidJson)?; + self.i += 4; + u32::from_str_radix(x, 16).map_err(|_| RequestRecordError::InvalidJson) + } +} +fn truth() -> J { + object(vec![ + ("authenticity", s("unverified")), + ("authority", s("none")), + ("execution", s("unavailable")), + ("authoritativeOutcome", s("unknown")), + ("independentEffect", s("not_observed")), + ("currentness", s("unverified")), + ]) +} +fn omissions() -> J { + J::Arr(vec![ + object(vec![ + ("path", s("request.requester_ref")), + ("reason", s("privacy_projection")), + ("disposition", s("policy_omission_not_presence_claim")), + ]), + object(vec![ + ("path", s("evidence.approval_decisions[*].reason")), + ("reason", s("privacy_projection")), + ("disposition", s("policy_omission_not_presence_claim")), + ]), + ]) +} +fn time(v: &str) -> Result<(), RequestRecordError> { + let b = v.as_bytes(); + if b.len() != 24 + || b[4] != b'-' + || b[7] != b'-' + || b[10] != b'T' + || b[13] != b':' + || b[16] != b':' + || b[19] != b'.' + || b[23] != b'Z' + || !b + .iter() + .enumerate() + .filter(|(i, _)| ![4, 7, 10, 13, 16, 19, 23].contains(i)) + .all(|(_, x)| x.is_ascii_digit()) + { + return Err(RequestRecordError::InvalidEnvelope); + } + let y: u32 = v[0..4] + .parse() + .map_err(|_| RequestRecordError::InvalidEnvelope)?; + let m: u32 = v[5..7] + .parse() + .map_err(|_| RequestRecordError::InvalidEnvelope)?; + let d: u32 = v[8..10] + .parse() + .map_err(|_| RequestRecordError::InvalidEnvelope)?; + let h: u32 = v[11..13] + .parse() + .map_err(|_| RequestRecordError::InvalidEnvelope)?; + let min: u32 = v[14..16] + .parse() + .map_err(|_| RequestRecordError::InvalidEnvelope)?; + let sec: u32 = v[17..19] + .parse() + .map_err(|_| RequestRecordError::InvalidEnvelope)?; + let max = match m { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) => 29, + 2 => 28, + _ => return Err(RequestRecordError::InvalidEnvelope), + }; + if d == 0 || d > max || h > 23 || min > 59 || sec > 59 { + Err(RequestRecordError::InvalidEnvelope) + } else { + Ok(()) + } +} +fn compact(a: &[&J]) -> Result { + let mut x = String::from("["); + for (i, v) in a.iter().enumerate() { + if i > 0 { + x.push(',') + } + x.push_str( + core::str::from_utf8(&encode(v)?) + .map_err(|_| RequestRecordError::SerializationFailed)?, + ) + } + x.push(']'); + Ok(x) +} +fn encode(v: &J) -> Result, RequestRecordError> { + let mut x = String::new(); + write(v, &mut x)?; + Ok(x.into_bytes()) +} +fn write(v: &J, o: &mut String) -> Result<(), RequestRecordError> { + match v { + J::Null => o.push_str("null"), + J::Bool(x) => o.push_str(if *x { "true" } else { "false" }), + J::Num(x) => o.push_str(x), + J::Str(x) => quoted(x, o), + J::Arr(a) => { + o.push('['); + for (i, x) in a.iter().enumerate() { + if i > 0 { + o.push(',') + } + write(x, o)? + } + o.push(']') + } + J::Obj(a) => { + o.push('{'); + for (i, (k, x)) in a.iter().enumerate() { + if i > 0 { + o.push(',') + } + quoted(k, o); + o.push(':'); + write(x, o)? + } + o.push('}') + } + } + if o.len() > MAX_HOST_BYTES { + return Err(RequestRecordError::OutputLimit); + } + Ok(()) +} +fn quoted(s: &str, o: &mut String) { + o.push('"'); + for c in s.chars() { + match c { + '"' => o.push_str("\\\""), + '\\' => o.push_str("\\\\"), + '\n' => o.push_str("\\n"), + '\r' => o.push_str("\\r"), + '\t' => o.push_str("\\t"), + '\u{08}' => o.push_str("\\b"), + '\u{0c}' => o.push_str("\\f"), + x if x < '\u{20}' => { + use core::fmt::Write; + let _ = write!(o, "\\u{:04x}", x as u32); + } + x => o.push(x), + } + } + o.push('"') +} +#[derive(Clone)] +enum J { + Null, + Bool(bool), + Num(String), + Str(String), + Arr(Vec), + Obj(Vec<(String, J)>), +} +fn s(x: &str) -> J { + J::Str(x.into()) +} +fn object(x: Vec<(&str, J)>) -> J { + J::Obj(x.into_iter().map(|(k, v)| (k.into(), v)).collect()) +} +fn obj(v: &J) -> Result<&[(String, J)], RequestRecordError> { + if let J::Obj(x) = v { + Ok(x) + } else { + Err(RequestRecordError::InvalidEnvelope) + } +} +fn array(v: &J) -> Result<&[J], RequestRecordError> { + if let J::Arr(x) = v { + Ok(x) + } else { + Err(RequestRecordError::InvalidEnvelope) + } +} +fn get<'a>(o: &'a [(String, J)], k: &str) -> Result<&'a J, RequestRecordError> { + o.iter() + .find(|x| x.0 == k) + .map(|x| &x.1) + .ok_or(RequestRecordError::InvalidEnvelope) +} +fn string(v: &J) -> Result<&str, RequestRecordError> { + if let J::Str(x) = v { + Ok(x) + } else { + Err(RequestRecordError::InvalidEnvelope) + } +} +fn boolean(v: &J) -> Result { + if let J::Bool(x) = v { + Ok(*x) + } else { + Err(RequestRecordError::InvalidEnvelope) + } +} +fn integer(v: &J) -> Result { + if let J::Num(x) = v { + if x.contains(['.', 'e', 'E']) { + Err(RequestRecordError::InvalidEnvelope) + } else { + x.parse().map_err(|_| RequestRecordError::InvalidEnvelope) + } + } else { + Err(RequestRecordError::InvalidEnvelope) + } +} +fn null(v: &J) -> Result<(), RequestRecordError> { + if matches!(v, J::Null) { + Ok(()) + } else { + Err(RequestRecordError::InvalidEnvelope) + } +} +fn eq(v: &J, x: &str, e: RequestRecordError) -> Result<(), RequestRecordError> { + if string(v)? == x { Ok(()) } else { Err(e) } +} +fn keys(o: &[(String, J)], e: &[&str]) -> Result<(), RequestRecordError> { + if o.len() != e.len() || o.iter().any(|x| !e.contains(&x.0.as_str())) { + Err(RequestRecordError::InvalidEnvelope) + } else { + Ok(()) + } +} +fn redact(o: &[(String, J)], r: &[&str]) -> Vec<(String, J)> { + o.iter() + .filter(|x| !r.contains(&x.0.as_str())) + .cloned() + .collect() +} +fn canonical(o: &[(String, J)], order: &[&str]) -> Result, RequestRecordError> { + order + .iter() + .map(|k| Ok(((*k).into(), get(o, k)?.clone()))) + .collect() +} +fn objects(x: &[J]) -> Result, RequestRecordError> { + x.iter().map(obj).collect() +} +fn text(v: &str, n: usize) -> Result<(), RequestRecordError> { + if v.is_empty() { + Err(RequestRecordError::InvalidEnvelope) + } else if v.len() > n { + Err(RequestRecordError::InputLimit) + } else { + Ok(()) + } +} +fn id(v: &str, p: &str) -> Result<(), RequestRecordError> { + if v.len() == 68 + && v.starts_with(p) + && v.as_bytes()[4..] + .iter() + .all(|x| matches!(x,b'0'..=b'9'|b'a'..=b'f')) + { + Ok(()) + } else { + Err(RequestRecordError::InvalidEnvelope) + } +} +fn digest(v: &str) -> Result<(), RequestRecordError> { + if v.len() == 71 + && v.starts_with("sha256:") + && v.as_bytes()[7..] + .iter() + .all(|x| matches!(x,b'0'..=b'9'|b'a'..=b'f')) + { + Ok(()) + } else { + Err(RequestRecordError::InvalidEnvelope) + } +} +fn hash(b: &[u8]) -> String { + format!("sha256:{}", byte_digest(b)) +} diff --git a/crates/rangoon-integrations/tests/lnsat_request_record.rs b/crates/rangoon-integrations/tests/lnsat_request_record.rs new file mode 100644 index 0000000..51348cb --- /dev/null +++ b/crates/rangoon-integrations/tests/lnsat_request_record.rs @@ -0,0 +1,2016 @@ +//! Bounded synthetic conformance groups S01--S36 for the request-record profile. +//! These fixtures are caller-owned bytes. They never contact LNSAT or mutate state. + +use rangoon_domain::byte_digest; +use rangoon_integrations::lnsat_request_record::{ + ReadUnavailable, RequestRecordBody, RequestRecordError, RequestRecordInput, + inspect_request_record, +}; +use serde_json::{Value, json}; + +const REQUEST: &str = "arq_0000000000000000000000000000000000000000000000000000000000000001"; +const PROJECT: &str = "project:synthetic"; +const RESOURCE: &str = "resource:synthetic"; +const REQUESTER_SENTINEL: &str = "requester-private-sentinel"; + +fn id(prefix: &str, suffix: u8) -> String { + format!("{prefix}{suffix:064x}") +} + +fn digest(suffix: u8) -> String { + format!("sha256:{suffix:064x}") +} + +fn at(second: u8) -> String { + format!("2026-10-26T12:00:{second:02}.000Z") +} + +// Keep the digest recipe deliberately local to the tests. The production decoder +// receives only the final commitment and must not supply this test oracle. +fn public_commitment(domain: &str, parts: Vec) -> String { + let body = serde_json::to_vec(&Value::Array(parts)).expect("vector serializes"); + let mut message = Vec::with_capacity(domain.len() + 1 + body.len()); + message.extend_from_slice(domain.as_bytes()); + message.push(b'\n'); + message.extend_from_slice(&body); + format!("sha256:{}", byte_digest(&message)) +} + +fn root() -> Value { + json!({ + "request_id": REQUEST, + "requester_ref": REQUESTER_SENTINEL, + "project_ref": PROJECT, + "resource_ref": RESOURCE, + "packet_id": "packet:synthetic", + "packet_sha256": digest(1), + "action_digest": digest(2), + "target_digest": digest(3), + "configuration_digest": digest(4), + "created_at": at(0), + "evidence_digest": digest(5), + }) +} + +fn policy(decision: &str) -> Value { + json!({ + "decision_id": id("pol_", 1), + "evaluated_at": at(0), + "expires_at": at(59), + "decision": decision, + "requires_approval": if decision == "approval_required" { 1 } else { 0 }, + }) +} + +fn evaluation(status: &str, policy_id: Option, reason: &str) -> Value { + let r = root(); + let packet_id = r["packet_id"].clone(); + let packet_sha = r["packet_sha256"].clone(); + let digest = public_commitment( + "lnsat.action_request.evaluation.v1", + vec![ + json!(REQUEST), + packet_id, + packet_sha, + json!(PROJECT), + json!(RESOURCE), + json!(status), + policy_id.clone().map(Value::String).unwrap_or(Value::Null), + json!(reason), + json!(at(0)), + ], + ); + json!({ + "status": status, + "policy_decision_id": policy_id, + "reason_code": reason, + "recorded_at": at(0), + "evidence_digest": digest, + }) +} + +fn observation(kind: &str, submitted: String, second: u8) -> Value { + let proof = public_commitment( + "lnsat.action_request.observation.v1", + vec![ + json!(REQUEST), + json!(kind), + json!(submitted), + json!(at(second)), + ], + ); + json!({ + "kind": kind, + "submitted_digest": submitted, + "observed_at": at(second), + "evidence_digest": proof, + }) +} + +fn evidence(decision: &str) -> Value { + json!({ + "schema": "lnsat.action_request_linked_evidence.v1", + "policy": policy(decision), + "approvals": [], + "approval_decisions": [], + "authorization_attempts": [], + "authorizations": [], + "operations": [], + "consumptions": [], + "operation_attempts": [], + "receipts": [], + "reconciliations": [], + "states": [], + }) +} + +fn complete(decision: &str) -> Value { + let policy_id = id("pol_", 1); + json!({ + "schema": "lnsat.action_request_record.v1", + "status": "complete", + "request_id": REQUEST, + "evaluation_state": "policy_recorded", + "request": root(), + "evaluation": evaluation("recorded", Some(policy_id), "policy_recorded"), + "observations": [], + "evidence": evidence(decision), + "security_activity_touched": false, + }) +} + +fn failed(reason: &str) -> Value { + json!({ + "schema": "lnsat.action_request_record.v1", + "status": "complete", + "request_id": REQUEST, + "evaluation_state": "evaluation_failed", + "request": root(), + "evaluation": evaluation("failed", None, reason), + "observations": [], + "evidence": null, + "security_activity_touched": false, + }) +} + +fn unknown() -> Value { + json!({ + "schema": "lnsat.action_request_record.v1", + "status": "complete", + "request_id": REQUEST, + "evaluation_state": "evaluation_unknown", + "request": root(), + "evaluation": null, + "observations": [], + "evidence": null, + "security_activity_touched": false, + }) +} + +fn degraded() -> Value { + json!({ + "schema": "lnsat.action_request_record.v1", + "status": "degraded", + "request_id": REQUEST, + "evaluation_state": "evaluation_unknown", + "request": null, + "evaluation": null, + "observations": [], + "evidence": null, + "security_activity_touched": true, + }) +} + +fn input(body: RequestRecordBody) -> RequestRecordInput { + RequestRecordInput { + installation_id: "synthetic-installation".into(), + environment: "test".into(), + selected_request_id: REQUEST.into(), + expected_project_ref: PROJECT.into(), + expected_resource_ref: RESOURCE.into(), + body, + read_at: Some(at(58)), + } +} + +fn bytes(value: &Value) -> Vec { + serde_json::to_vec(value).expect("fixture JSON serializes") +} + +fn reverse_top_level_bytes(value: &Value) -> Vec { + let members = value.as_object().expect("fixture object"); + let mut encoded = Vec::new(); + encoded.push(b'{'); + for (index, (key, member)) in members.iter().rev().enumerate() { + if index > 0 { + encoded.push(b','); + } + encoded.extend_from_slice(serde_json::to_string(key).unwrap().as_bytes()); + encoded.push(b':'); + encoded.extend_from_slice(serde_json::to_string(member).unwrap().as_bytes()); + } + encoded.push(b'}'); + encoded +} + +fn inspect( + value: &Value, +) -> Result +{ + inspect_request_record(input(RequestRecordBody::Body200(bytes(value)))) +} + +fn host(value: &Value) -> Value { + let result = inspect(value).expect("valid synthetic record"); + serde_json::from_slice(result.host_json()).expect("decoder host JSON") +} + +fn summary(value: &Value) -> Value { + let result = inspect(value).expect("valid synthetic record"); + serde_json::from_slice(result.summary_json()).expect("decoder summary JSON") +} + +fn err(value: &Value) -> RequestRecordError { + match inspect(value) { + Ok(_) => panic!("invalid synthetic record must be refused"), + Err(error) => error, + } +} + +fn assert_error_code(error: RequestRecordError, expected: &str) { + assert_eq!(error.code(), expected, "fixed non-echoing error code"); + let bytes = error.json_bytes(); + assert_eq!( + bytes, + reference_bytes( + &json!({"schemaVersion":"rangoon.integrations.lnsat-request-error.v1","code":expected,"truth":reference_truth()}) + ), + "exact independent error bytes" + ); + key_order(&bytes, &["schemaVersion", "code", "truth"]); + assert!(bytes.len() <= 1_024); + let value: Value = serde_json::from_slice(&bytes).expect("fixed error JSON"); + assert_exact_keys(&value, &["schemaVersion", "code", "truth"]); + assert_eq!( + value["schemaVersion"], + "rangoon.integrations.lnsat-request-error.v1" + ); + assert_eq!(value["code"], expected); + assert_truth(&value["truth"]); +} + +fn key_order(bytes: &[u8], keys: &[&str]) { + let text = std::str::from_utf8(bytes).expect("output is UTF-8"); + assert!(!text.starts_with('\u{feff}')); + assert!(!text.ends_with('\n')); + let mut previous = 0; + for key in keys { + let at = text + .find(&format!("\"{key}\":")) + .expect("required serialized key"); + assert!(at >= previous, "{key} must serialize after prior key"); + previous = at; + } +} + +fn assert_truth(value: &Value) { + assert_eq!(value["authenticity"], "unverified"); + assert_eq!(value["authority"], "none"); + assert_eq!(value["execution"], "unavailable"); + assert_eq!(value["authoritativeOutcome"], "unknown"); + assert_eq!(value["independentEffect"], "not_observed"); + assert_eq!(value["currentness"], "unverified"); +} + +fn object_keys(value: &Value) -> Vec<&str> { + value + .as_object() + .expect("object") + .keys() + .map(String::as_str) + .collect() +} + +fn assert_exact_keys(value: &Value, expected: &[&str]) { + let mut actual = object_keys(value); + let mut wanted = expected.to_vec(); + actual.sort_unstable(); + wanted.sort_unstable(); + assert_eq!(actual, wanted, "closed output object key set"); +} + +fn assert_omissions(value: &Value) { + let rows = value.as_array().expect("omission array"); + assert_eq!(rows.len(), 2); + assert_exact_keys(&rows[0], &["path", "reason", "disposition"]); + assert_exact_keys(&rows[1], &["path", "reason", "disposition"]); + assert_eq!( + rows[0], + json!({ + "path": "request.requester_ref", + "reason": "privacy_projection", + "disposition": "policy_omission_not_presence_claim", + }) + ); + assert_eq!( + rows[1], + json!({ + "path": "evidence.approval_decisions[*].reason", + "reason": "privacy_projection", + "disposition": "policy_omission_not_presence_claim", + }) + ); +} + +fn assert_raw_host_oracle(bytes: &[u8]) { + key_order( + bytes, + &[ + "schemaVersion", + "profileVersion", + "source", + "selection", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "securityActivityTouched", + "inputDigest", + "native", + "readFailure", + "truth", + "omissions", + ], + ); + let host: Value = serde_json::from_slice(bytes).expect("host JSON parses"); + assert_exact_keys( + &host, + &[ + "schemaVersion", + "profileVersion", + "source", + "selection", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "securityActivityTouched", + "inputDigest", + "native", + "readFailure", + "truth", + "omissions", + ], + ); + assert_eq!( + host["schemaVersion"], + "rangoon.integrations.lnsat-request-record.v1" + ); + assert_eq!(host["profileVersion"], 1); + assert_truth(&host["truth"]); + assert_omissions(&host["omissions"]); +} + +fn assert_host_contract( + result: &rangoon_integrations::lnsat_request_record::RequestRecordInspection, +) { + key_order( + result.host_json(), + &[ + "schemaVersion", + "profileVersion", + "source", + "selection", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "securityActivityTouched", + "inputDigest", + "native", + "readFailure", + "truth", + "omissions", + ], + ); + key_order( + result.summary_json(), + &[ + "schemaVersion", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "readFailure", + "securityActivityTouched", + "familyCounts", + "truth", + "omissions", + ], + ); + assert_raw_host_oracle(result.host_json()); + let host: Value = + serde_json::from_slice(result.host_json()).expect("host parses independently"); + let summary: Value = + serde_json::from_slice(result.summary_json()).expect("summary parses independently"); + assert_exact_keys( + &host, + &[ + "schemaVersion", + "profileVersion", + "source", + "selection", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "securityActivityTouched", + "inputDigest", + "native", + "readFailure", + "truth", + "omissions", + ], + ); + assert_exact_keys( + &summary, + &[ + "schemaVersion", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "readFailure", + "securityActivityTouched", + "familyCounts", + "truth", + "omissions", + ], + ); + assert_exact_keys( + &host["source"], + &[ + "repository", + "commit", + "wireContract", + "compatibility", + "transportAuthentication", + ], + ); + assert_exact_keys( + &host["selection"], + &[ + "installationId", + "environment", + "requestId", + "expectedProjectRef", + "expectedResourceRef", + "readAt", + ], + ); + assert_exact_keys( + &host["truth"], + &[ + "authenticity", + "authority", + "execution", + "authoritativeOutcome", + "independentEffect", + "currentness", + ], + ); + assert_eq!( + host["schemaVersion"], + "rangoon.integrations.lnsat-request-record.v1" + ); + assert_eq!(host["profileVersion"], 1); + assert_eq!(host["source"]["repository"], "hypler-dev/LNSAT"); + assert_eq!( + host["source"]["commit"], + "35a41963ad698934c7ee00852c71355e329c34fa" + ); + assert_eq!( + host["source"]["wireContract"], + "lnsat.action_request_record.v1" + ); + assert_eq!( + host["source"]["compatibility"], + "source_pinned_not_runtime_qualified" + ); + assert_eq!(host["source"]["transportAuthentication"], "unverified"); + assert_truth(&host["truth"]); + assert_truth(&summary["truth"]); + assert_eq!(host["omissions"], summary["omissions"]); + assert_omissions(&host["omissions"]); + assert!(result.host_json().len() <= 131_072); + assert!(result.summary_json().len() <= 8_192); +} + +fn state( + event: u8, + target_id: String, + kind: &str, + sequence: u8, + prior: Option<(String, u8)>, + name: &str, + second: u8, +) -> Value { + json!({ + "state_event_id": id("ste_", event), + "target_entity_id": target_id, + "target_entity_kind": kind, + "state_sequence": sequence, + "state": name, + "prior_state_event_id": prior.as_ref().map(|p| p.0.clone()), + "prior_state_sequence": prior.map(|p| p.1), + "effective_at": at(second), + "state_digest": digest(sequence.saturating_add(60)), + }) +} + +fn add_minimal_execution(document: &mut Value, terminal: &str, reconcile: Option<&str>) { + let policy_id = id("pol_", 1); + let approval_id = id("apr_", 1); + let decision_id = id("apd_", 1); + let attempt_id = id("aat_", 1); + let authorization_id = id("xau_", 1); + let operation_id = id("opn_", 1); + let consumption_id = id("cpc_", 1); + let operation_attempt_id = id("opa_", 1); + let receipt_id = id("rcp_", 1); + let evidence = document["evidence"] + .as_object_mut() + .expect("recorded evidence"); + evidence.insert("policy".into(), policy("approval_required")); + evidence.insert( + "approvals".into(), + json!([{ + "approval_request_id": approval_id, + "policy_decision_id": policy_id, + "status": "requested", + "requested_at": at(1), + "expires_at": at(59), + }]), + ); + evidence.insert( + "approval_decisions".into(), + json!([{ + "approval_decision_id": decision_id, + "approval_request_id": approval_id, + "policy_decision_id": policy_id, + "decision": "approved", + "reason": "approval.operator_approved", + "decided_at": at(2), + "expires_at": at(59), + "approval_gate_satisfied": 1, + }]), + ); + evidence.insert( + "authorization_attempts".into(), + json!([{ + "authorization_attempt_id": attempt_id, + "approval_decision_id": decision_id, + "approval_request_id": approval_id, + "policy_decision_id": policy_id, + "result_status": "persistence_prepared", + "requested_at": at(3), + "expires_at": at(59), + }]), + ); + evidence.insert( + "authorizations".into(), + json!([{ + "authorization_id": authorization_id, + "authorization_attempt_id": attempt_id, + "approval_decision_id": decision_id, + "policy_decision_id": policy_id, + "issued_at": at(4), + "expires_at": at(59), + }]), + ); + evidence.insert( + "operations".into(), + json!([{ + "operation_id": operation_id, + "authorization_id": authorization_id, + "created_at": at(5), + "expires_at": at(59), + }]), + ); + evidence.insert( + "consumptions".into(), + json!([{ + "consumption_id": consumption_id, + "authorization_id": authorization_id, + "operation_id": operation_id, + "consumed_at": at(5), + }]), + ); + evidence.insert( + "operation_attempts".into(), + json!([{ + "operation_attempt_id": operation_attempt_id, + "operation_id": operation_id, + "attempt_sequence": 1, + "created_at": at(6), + }]), + ); + if terminal == "completed" { + evidence.insert( + "receipts".into(), + json!([{ + "receipt_id": receipt_id, + "operation_id": operation_id, + "operation_attempt_id": operation_attempt_id, + "authorization_id": authorization_id, + "consumption_id": consumption_id, + "verification_status": "accepted", + "result_digest": digest(42), + "received_at": at(8), + }]), + ); + } + let mut states = vec![ + state( + 1, + authorization_id.clone(), + "execution_authorization", + 1, + None, + "active", + 4, + ), + state( + 2, + authorization_id.clone(), + "execution_authorization", + 2, + Some((id("ste_", 1), 1)), + "consumed", + 5, + ), + state(3, operation_id.clone(), "operation", 1, None, "prepared", 5), + state( + 4, + operation_id.clone(), + "operation", + 2, + Some((id("ste_", 3), 1)), + "dispatching", + 6, + ), + state( + 5, + operation_attempt_id.clone(), + "operation_attempt", + 1, + None, + "dispatching", + 6, + ), + ]; + if terminal != "dispatching" { + states.push(state( + 6, + operation_id.clone(), + "operation", + 3, + Some((id("ste_", 4), 2)), + terminal, + 7, + )); + states.push(state( + 7, + operation_attempt_id.clone(), + "operation_attempt", + 2, + Some((id("ste_", 5), 1)), + terminal, + 7, + )); + } + evidence.insert("states".into(), Value::Array(states)); + if let Some(status) = reconcile { + let (linked_receipt, observed) = match status { + "pending" | "unresolved" => (Value::Null, Value::Null), + "matched" => (json!(receipt_id), json!(digest(42))), + "mismatch" => (json!(receipt_id), json!(digest(43))), + _ => unreachable!("fixture status"), + }; + evidence.insert( + "reconciliations".into(), + json!([{ + "reconciliation_id": id("rec_", 1), + "operation_id": operation_id, + "operation_attempt_id": operation_attempt_id, + "receipt_id": linked_receipt, + "status": status, + "observed_result_digest": observed, + "recorded_at": at(9), + }]), + ); + } +} + +fn approval_rows(count: u8) -> Value { + Value::Array( + (0..count) + .map(|n| { + json!({ + "approval_request_id": id("apr_", n.saturating_add(1)), + "policy_decision_id": id("pol_", 1), + "status": "requested", + "requested_at": at(1), + "expires_at": at(59), + }) + }) + .collect(), + ) +} + +const HOST_KEYS: &[&str] = &[ + "schemaVersion", + "profileVersion", + "source", + "selection", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "securityActivityTouched", + "inputDigest", + "native", + "readFailure", + "truth", + "omissions", +]; +const SUMMARY_KEYS: &[&str] = &[ + "schemaVersion", + "recordAvailability", + "reportedEvaluation", + "reportedPolicy", + "readFailure", + "securityActivityTouched", + "familyCounts", + "truth", + "omissions", +]; +const ERROR_KEYS: &[&str] = &["schemaVersion", "code", "truth"]; +const SOURCE_KEYS: &[&str] = &[ + "repository", + "commit", + "wireContract", + "compatibility", + "transportAuthentication", +]; +const SELECTION_KEYS: &[&str] = &[ + "installationId", + "environment", + "requestId", + "expectedProjectRef", + "expectedResourceRef", + "readAt", +]; +const TRUTH_KEYS: &[&str] = &[ + "authenticity", + "authority", + "execution", + "authoritativeOutcome", + "independentEffect", + "currentness", +]; +const OMISSION_KEYS: &[&str] = &["path", "reason", "disposition"]; +const NATIVE_KEYS: &[&str] = &["request", "evaluation", "observations", "evidence"]; +const REQUEST_KEYS: &[&str] = &[ + "request_id", + "project_ref", + "resource_ref", + "packet_id", + "packet_sha256", + "action_digest", + "target_digest", + "configuration_digest", + "created_at", + "evidence_digest", +]; +const EVALUATION_KEYS: &[&str] = &[ + "status", + "policy_decision_id", + "reason_code", + "recorded_at", + "evidence_digest", +]; +const OBSERVATION_KEYS: &[&str] = &["kind", "submitted_digest", "observed_at", "evidence_digest"]; +const EVIDENCE_KEYS: &[&str] = &[ + "schema", + "policy", + "approvals", + "approval_decisions", + "authorization_attempts", + "authorizations", + "operations", + "consumptions", + "operation_attempts", + "receipts", + "reconciliations", + "states", +]; +const POLICY_KEYS: &[&str] = &[ + "decision_id", + "evaluated_at", + "expires_at", + "decision", + "requires_approval", +]; +const APPROVAL_KEYS: &[&str] = &[ + "approval_request_id", + "policy_decision_id", + "status", + "requested_at", + "expires_at", +]; +const APPROVAL_DECISION_KEYS: &[&str] = &[ + "approval_decision_id", + "approval_request_id", + "policy_decision_id", + "decision", + "decided_at", + "expires_at", + "approval_gate_satisfied", +]; +const AUTHORIZATION_ATTEMPT_KEYS: &[&str] = &[ + "authorization_attempt_id", + "approval_decision_id", + "approval_request_id", + "policy_decision_id", + "result_status", + "requested_at", + "expires_at", +]; +const AUTHORIZATION_KEYS: &[&str] = &[ + "authorization_id", + "authorization_attempt_id", + "approval_decision_id", + "policy_decision_id", + "issued_at", + "expires_at", +]; +const OPERATION_KEYS: &[&str] = &[ + "operation_id", + "authorization_id", + "created_at", + "expires_at", +]; +const CONSUMPTION_KEYS: &[&str] = &[ + "consumption_id", + "authorization_id", + "operation_id", + "consumed_at", +]; +const OPERATION_ATTEMPT_KEYS: &[&str] = &[ + "operation_attempt_id", + "operation_id", + "attempt_sequence", + "created_at", +]; +const RECEIPT_KEYS: &[&str] = &[ + "receipt_id", + "operation_id", + "operation_attempt_id", + "authorization_id", + "consumption_id", + "verification_status", + "result_digest", + "received_at", +]; +const RECONCILIATION_KEYS: &[&str] = &[ + "reconciliation_id", + "operation_id", + "operation_attempt_id", + "receipt_id", + "status", + "observed_result_digest", + "recorded_at", +]; +const STATE_KEYS: &[&str] = &[ + "state_event_id", + "target_entity_id", + "target_entity_kind", + "state_sequence", + "state", + "prior_state_event_id", + "prior_state_sequence", + "effective_at", + "state_digest", +]; +const FAMILY_COUNT_KEYS: &[&str] = &[ + "approvals", + "approval_decisions", + "authorization_attempts", + "authorizations", + "operations", + "consumptions", + "operation_attempts", + "receipts", + "reconciliations", + "states", +]; + +fn reference_object_order(object: &serde_json::Map) -> &'static [&'static str] { + let has = |key: &str| object.contains_key(key); + if has("profileVersion") { + HOST_KEYS + } else if has("familyCounts") { + SUMMARY_KEYS + } else if has("code") { + ERROR_KEYS + } else if has("repository") { + SOURCE_KEYS + } else if has("installationId") { + SELECTION_KEYS + } else if has("authenticity") { + TRUTH_KEYS + } else if has("disposition") { + OMISSION_KEYS + } else if has("request") && has("observations") { + NATIVE_KEYS + } else if has("packet_sha256") { + REQUEST_KEYS + } else if has("reason_code") { + EVALUATION_KEYS + } else if has("submitted_digest") { + OBSERVATION_KEYS + } else if has("schema") && has("policy") && has("approvals") && has("states") { + EVIDENCE_KEYS + } else if has("decision_id") { + POLICY_KEYS + } else if has("approval_gate_satisfied") { + APPROVAL_DECISION_KEYS + } else if has("approval_request_id") && has("status") { + APPROVAL_KEYS + } else if has("authorization_attempt_id") && has("result_status") { + AUTHORIZATION_ATTEMPT_KEYS + } else if has("authorization_id") && has("issued_at") { + AUTHORIZATION_KEYS + } else if has("consumption_id") && has("consumed_at") { + CONSUMPTION_KEYS + } else if has("operation_attempt_id") && has("attempt_sequence") { + OPERATION_ATTEMPT_KEYS + } else if has("receipt_id") && has("verification_status") { + RECEIPT_KEYS + } else if has("reconciliation_id") { + RECONCILIATION_KEYS + } else if has("state_event_id") { + STATE_KEYS + } else if has("operation_id") && has("expires_at") { + OPERATION_KEYS + } else if has("approvals") { + FAMILY_COUNT_KEYS + } else { + panic!("reference serializer saw an unrecognized object shape"); + } +} + +fn reference_write(value: &Value, output: &mut String) { + match value { + Value::Null => output.push_str("null"), + Value::Bool(value) => output.push_str(if *value { "true" } else { "false" }), + Value::Number(value) => output.push_str(&value.to_string()), + Value::String(value) => output.push_str(&serde_json::to_string(value).expect("string")), + Value::Array(values) => { + output.push('['); + for (index, value) in values.iter().enumerate() { + if index > 0 { + output.push(','); + } + reference_write(value, output); + } + output.push(']'); + } + Value::Object(object) => { + let keys = reference_object_order(object); + assert_eq!( + object.len(), + keys.len(), + "reference object has no extra field" + ); + output.push('{'); + for (index, key) in keys.iter().enumerate() { + if index > 0 { + output.push(','); + } + output.push_str(&serde_json::to_string(key).expect("key")); + output.push(':'); + reference_write(object.get(*key).expect("reference field"), output); + } + output.push('}'); + } + } +} + +fn reference_bytes(value: &Value) -> Vec { + let mut output = String::new(); + reference_write(value, &mut output); + output.into_bytes() +} + +fn reference_truth() -> Value { + json!({ + "authenticity": "unverified", "authority": "none", "execution": "unavailable", + "authoritativeOutcome": "unknown", "independentEffect": "not_observed", "currentness": "unverified", + }) +} + +fn reference_omissions() -> Value { + json!([ + {"path":"request.requester_ref","reason":"privacy_projection","disposition":"policy_omission_not_presence_claim"}, + {"path":"evidence.approval_decisions[*].reason","reason":"privacy_projection","disposition":"policy_omission_not_presence_claim"}, + ]) +} + +fn redact_reference_row(value: &Value, field: &str) -> Value { + let mut object = value.as_object().expect("fixture row").clone(); + object.remove(field); + Value::Object(object) +} + +fn reference_native(document: &Value) -> Value { + let mut request = document["request"] + .as_object() + .expect("complete request") + .clone(); + request.remove("requester_ref"); + let evidence = if document["evidence"].is_null() { + Value::Null + } else { + let mut evidence = document["evidence"].as_object().expect("evidence").clone(); + evidence.insert( + "approval_decisions".into(), + Value::Array( + document["evidence"]["approval_decisions"] + .as_array() + .expect("rows") + .iter() + .map(|row| redact_reference_row(row, "reason")) + .collect(), + ), + ); + Value::Object(evidence) + }; + json!({ + "request": Value::Object(request), + "evaluation": document["evaluation"].clone(), + "observations": document["observations"].clone(), + "evidence": evidence, + }) +} + +fn reference_host( + availability: &str, + evaluation: &str, + policy: &str, + native: Option, + security: Option, + input_digest: Option, + failure: Option<&str>, +) -> Value { + json!({ + "schemaVersion": "rangoon.integrations.lnsat-request-record.v1", + "profileVersion": 1, + "source": {"repository":"hypler-dev/LNSAT","commit":"35a41963ad698934c7ee00852c71355e329c34fa","wireContract":"lnsat.action_request_record.v1","compatibility":"source_pinned_not_runtime_qualified","transportAuthentication":"unverified"}, + "selection": {"installationId":"synthetic-installation","environment":"test","requestId":REQUEST,"expectedProjectRef":PROJECT,"expectedResourceRef":RESOURCE,"readAt":at(58)}, + "recordAvailability": availability, + "reportedEvaluation": evaluation, + "reportedPolicy": policy, + "securityActivityTouched": security, + "inputDigest": input_digest, + "native": native, + "readFailure": failure, + "truth": reference_truth(), + "omissions": reference_omissions(), + }) +} + +fn reference_summary(host: &Value) -> Value { + let family_counts = host["native"]["evidence"].as_object().map(|evidence| { + let mut counts = serde_json::Map::new(); + for family in FAMILY_COUNT_KEYS { + counts.insert( + (*family).into(), + json!(evidence[*family].as_array().expect("family").len()), + ); + } + Value::Object(counts) + }); + json!({ + "schemaVersion": "rangoon.integrations.lnsat-request-summary.v1", + "recordAvailability": host["recordAvailability"].clone(), + "reportedEvaluation": host["reportedEvaluation"].clone(), + "reportedPolicy": host["reportedPolicy"].clone(), + "readFailure": host["readFailure"].clone(), + "securityActivityTouched": host["securityActivityTouched"].clone(), + "familyCounts": family_counts, + "truth": reference_truth(), + "omissions": reference_omissions(), + }) +} + +fn assert_reference_case( + body: RequestRecordBody, + exact_body: Option<&[u8]>, + document: Option<&Value>, + reported: (&str, &str, &str), + security: Option, + failure: Option<&str>, +) -> ( + rangoon_integrations::lnsat_request_record::RequestRecordInspection, + Value, +) { + let (availability, evaluation, policy) = reported; + let expected_host = reference_host( + availability, + evaluation, + policy, + document.map(reference_native), + security, + exact_body.map(|body| format!("sha256:{}", byte_digest(body))), + failure, + ); + let expected_summary = reference_summary(&expected_host); + let actual = inspect_request_record(input(body)).expect("closed reference fixture accepts"); + assert_eq!(actual.host_json(), reference_bytes(&expected_host)); + assert_eq!(actual.summary_json(), reference_bytes(&expected_summary)); + (actual, expected_host) +} + +#[test] +fn s01_complete_allow_without_execution_is_reported_only() { + let result = inspect(&complete("allow")).expect("S01 valid allow"); + assert_host_contract(&result); + let host: Value = serde_json::from_slice(result.host_json()).unwrap(); + assert_eq!(host["recordAvailability"], "complete"); + assert_eq!(host["reportedPolicy"], "allow"); + assert_eq!(host["native"]["evidence"]["operations"], json!([])); + assert_eq!(host["truth"]["authority"], "none"); +} + +#[test] +fn s02_complete_deny_never_becomes_an_external_path_claim() { + let host = host(&complete("deny")); + assert_eq!(host["reportedPolicy"], "deny"); + assert_eq!(host["native"]["evidence"]["policy"]["requires_approval"], 0); + assert_eq!(host["truth"]["independentEffect"], "not_observed"); +} + +#[test] +fn s03_approval_required_preserves_distinct_rows() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "dispatching", None); + value["evidence"]["approvals"] + .as_array_mut() + .unwrap() + .push(json!({ + "approval_request_id": id("apr_", 2), + "policy_decision_id": id("pol_", 1), + "status": "requested", + "requested_at": at(1), + "expires_at": at(59), + })); + value["evidence"]["approval_decisions"] + .as_array_mut() + .unwrap() + .push(json!({ + "approval_decision_id": id("apd_", 2), + "approval_request_id": id("apr_", 2), + "policy_decision_id": id("pol_", 1), + "decision": "denied", + "reason": "approval.operator_denied", + "decided_at": at(2), + "expires_at": at(59), + "approval_gate_satisfied": 0, + })); + let host = host(&value); + assert_eq!(host["reportedPolicy"], "approval_required"); + assert_eq!( + host["native"]["evidence"]["approvals"] + .as_array() + .unwrap() + .len(), + 2 + ); + assert_eq!( + host["native"]["evidence"]["approval_decisions"] + .as_array() + .unwrap() + .len(), + 2 + ); + assert!(host["native"].get("approvalDuty").is_none()); +} + +#[test] +fn s04_failed_evaluation_reasons_are_not_unknown() { + for reason in ["evaluation_rejected", "persistence_failed"] { + let host = host(&failed(reason)); + assert_eq!(host["reportedEvaluation"], "evaluation_failed"); + assert_eq!(host["reportedPolicy"], "not_observed"); + assert!(host["native"]["evaluation"].is_object()); + assert!(host["native"]["evidence"].is_null()); + } +} + +#[test] +fn s05_unknown_evaluation_can_still_be_complete() { + let host = host(&unknown()); + assert_eq!(host["recordAvailability"], "complete"); + assert_eq!(host["reportedEvaluation"], "evaluation_unknown"); + assert!(host["native"]["evaluation"].is_null()); + assert!(host["native"]["evidence"].is_null()); +} + +#[test] +fn s06_replay_and_conflict_are_bounded_observations() { + let mut value = complete("allow"); + value["observations"] = json!([ + observation("replay", digest(1), 1), + observation("conflict", digest(9), 2), + ]); + let host = host(&value); + assert_eq!(host["native"]["observations"].as_array().unwrap().len(), 2); + assert!(host["native"].get("retryCount").is_none()); + assert_eq!(host["truth"]["independentEffect"], "not_observed"); +} + +#[test] +fn s07_issued_unconsumed_authorization_has_no_invented_operation() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "dispatching", None); + let evidence = value["evidence"].as_object_mut().unwrap(); + evidence.insert("operations".into(), json!([])); + evidence.insert("consumptions".into(), json!([])); + evidence.insert("operation_attempts".into(), json!([])); + evidence.insert( + "states".into(), + json!([state( + 1, + id("xau_", 1), + "execution_authorization", + 1, + None, + "active", + 4 + )]), + ); + let host = host(&value); + assert_eq!( + host["native"]["evidence"]["authorizations"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!(host["native"]["evidence"]["operations"], json!([])); +} + +#[test] +fn s08_dispatching_and_unknown_are_not_completion() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "outcome_unknown", None); + let host = host(&value); + let states = host["native"]["evidence"]["states"].as_array().unwrap(); + assert!(states.iter().any(|row| row["state"] == "outcome_unknown")); + assert_eq!(host["native"]["evidence"]["receipts"], json!([])); + assert_eq!(host["truth"]["authoritativeOutcome"], "unknown"); +} + +#[test] +fn s09_completed_receipt_is_reported_not_independent_effect() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "completed", None); + let host = host(&value); + assert_eq!( + host["native"]["evidence"]["receipts"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!(host["truth"]["independentEffect"], "not_observed"); +} + +#[test] +fn s10_unknown_to_completed_matched_reconciliation_stays_one_document() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "completed", Some("matched")); + let host = host(&value); + assert_eq!( + host["native"]["evidence"]["reconciliations"][0]["status"], + "matched" + ); + assert!(host["native"].get("redispatch").is_none()); + assert_eq!(host["truth"]["execution"], "unavailable"); +} + +#[test] +fn s11_pending_unresolved_and_mismatch_remain_distinct() { + for status in ["pending", "unresolved", "mismatch"] { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "completed", Some(status)); + let host = host(&value); + assert_eq!( + host["native"]["evidence"]["reconciliations"][0]["status"], + status + ); + assert_ne!( + host["native"]["evidence"]["reconciliations"][0]["status"], + "matched" + ); + } +} + +#[test] +fn s12_degraded_never_retains_prior_native_rows() { + let host = host(°raded()); + assert_eq!(host["recordAvailability"], "degraded"); + assert!(host["native"].is_null()); + assert!(host["readFailure"].is_null()); + assert_eq!(host["securityActivityTouched"], true); +} + +#[test] +fn s13_exact_generic_403_has_one_unclassified_form() { + let refusal = json!({ + "schema": "lnsat.action_request_record.v1", + "ok": false, + "error": {"code": "gateway.action_request_record.denied"}, + }); + let result = + inspect_request_record(input(RequestRecordBody::Refused403(bytes(&refusal)))).unwrap(); + let host: Value = serde_json::from_slice(result.host_json()).unwrap(); + assert_eq!(host["recordAvailability"], "read_rejected_unclassified"); + assert_eq!(host["readFailure"], "native_read_rejected_unclassified"); + assert!(host["native"].is_null()); +} + +#[test] +fn s14_every_unavailable_condition_has_a_closed_form() { + let variants = [ + (ReadUnavailable::NotConfigured, "read_not_configured"), + ( + ReadUnavailable::TransportUnavailable, + "read_transport_unavailable", + ), + (ReadUnavailable::Cancelled, "read_cancelled"), + (ReadUnavailable::Timeout, "read_timeout"), + (ReadUnavailable::Unauthenticated, "read_unauthenticated"), + ( + ReadUnavailable::UnsupportedTransport, + "read_unsupported_transport", + ), + ]; + for (condition, code) in variants { + let result = + inspect_request_record(input(RequestRecordBody::ReadUnavailable(condition))).unwrap(); + let host: Value = serde_json::from_slice(result.host_json()).unwrap(); + assert_eq!(host["recordAvailability"], "read_unavailable"); + assert_eq!(host["readFailure"], code); + assert!(host["inputDigest"].is_null()); + assert!(host["native"].is_null()); + } +} + +#[test] +fn s15_request_scope_and_namespace_mismatches_refuse() { + let mut top_request = complete("allow"); + top_request["request_id"] = json!(id("arq_", 2)); + assert!(matches!( + err(&top_request), + RequestRecordError::SelectionMismatch + )); + for (field, replacement) in [ + ("project_ref", json!("project:other")), + ("resource_ref", json!("resource:other")), + ] { + let mut value = complete("allow"); + value["request"][field] = replacement; + assert!(matches!(err(&value), RequestRecordError::ScopeMismatch)); + } +} + +#[test] +fn s16_wrong_schema_d3a_wrapper_and_unknown_fields_refuse() { + let mut wrong_schema = complete("allow"); + wrong_schema["schema"] = json!("lnsat.gateway.runtime_composition.v1_0"); + assert!(matches!( + err(&wrong_schema), + RequestRecordError::UnsupportedSchema + )); + let mut extra = complete("allow"); + extra["d3a"] = json!(true); + assert!(matches!(err(&extra), RequestRecordError::InvalidEnvelope)); +} + +#[test] +fn s17_bom_trailing_invalid_utf8_and_duplicate_decoded_keys_refuse() { + let valid = bytes(&complete("allow")); + let mut bom = vec![0xef, 0xbb, 0xbf]; + bom.extend_from_slice(&valid); + assert!(matches!( + inspect_request_record(input(RequestRecordBody::Body200(bom))), + Err(RequestRecordError::InvalidEncoding) + )); + let mut trailing = valid.clone(); + trailing.extend_from_slice(b" true"); + assert!(matches!( + inspect_request_record(input(RequestRecordBody::Body200(trailing))), + Err(RequestRecordError::InvalidJson) + )); + let duplicate = + br#"{"schema":"lnsat.action_request_record.v1","schema":"lnsat.action_request_record.v1"}"# + .to_vec(); + let duplicate_error = + inspect_request_record(input(RequestRecordBody::Body200(duplicate))).unwrap_err(); + assert_error_code(duplicate_error, "duplicate_field"); + let encoding_error = + inspect_request_record(input(RequestRecordBody::Body200(vec![0xff]))).unwrap_err(); + assert_error_code(encoding_error, "invalid_encoding"); + for duplicate in [ + br#"{"nested":{"key":0,"\u006bey":1}}"#.as_slice(), + br#"{"nested":[{"a":0,"a":1}]}"#.as_slice(), + ] { + assert_eq!( + inspect_request_record(input(RequestRecordBody::Body200(duplicate.to_vec()))) + .unwrap_err(), + RequestRecordError::DuplicateField + ); + } + // A truncated \u escape followed by multi-byte UTF-8 must return a fixed + // parse error, never panic by byte-indexing inside a scalar. + let malformed_unicode = b"\"\\u\xc3\xa9\xc3\xa9\xc3\xa9\"".to_vec(); + assert!(matches!( + inspect_request_record(input(RequestRecordBody::Body200(malformed_unicode))), + Err(RequestRecordError::InvalidJson) + )); +} + +#[test] +fn s18_missing_null_and_coercion_are_not_defaulted() { + let mut missing = complete("allow"); + missing + .as_object_mut() + .unwrap() + .remove("security_activity_touched"); + assert!(matches!(err(&missing), RequestRecordError::InvalidEnvelope)); + let mut bool_as_integer = complete("allow"); + bool_as_integer["evidence"]["policy"]["requires_approval"] = json!(false); + assert!(matches!( + err(&bool_as_integer), + RequestRecordError::InvalidEnvelope + )); + let mut string_bool = complete("allow"); + string_bool["security_activity_touched"] = json!("false"); + assert!(matches!( + err(&string_bool), + RequestRecordError::InvalidEnvelope + )); +} + +#[test] +fn s19_input_boundaries_and_impossible_reachable_limits_are_distinct() { + let exact = vec![b' '; rangoon_integrations::lnsat_request_record::MAX_INPUT_BYTES]; + assert!(matches!( + inspect_request_record(input(RequestRecordBody::Body200(exact))), + Err(RequestRecordError::InvalidJson) + )); + let over = vec![b' '; rangoon_integrations::lnsat_request_record::MAX_INPUT_BYTES + 1]; + assert!(matches!( + inspect_request_record(input(RequestRecordBody::Body200(over))), + Err(RequestRecordError::InputLimit) + )); + let value = complete("allow"); + assert!(bytes(&value).len() < rangoon_integrations::lnsat_request_record::MAX_INPUT_BYTES); + assert!(inspect(&value).is_ok()); + let mut boundary_context = input(RequestRecordBody::Body200(bytes(&value))); + boundary_context.installation_id = "i".repeat(128); + boundary_context.environment = "e".repeat(128); + boundary_context.expected_project_ref = PROJECT.into(); + boundary_context.expected_resource_ref = RESOURCE.into(); + assert!(inspect_request_record(boundary_context).is_ok()); + let mut over_context = input(RequestRecordBody::Body200(bytes(&value))); + over_context.installation_id = "i".repeat(129); + assert!(matches!( + inspect_request_record(over_context), + Err(RequestRecordError::InputLimit) + )); + let mut string_limit = complete("allow"); + string_limit["request"]["requester_ref"] = json!("r".repeat(4_096)); + assert!(inspect(&string_limit).is_ok()); + string_limit["request"]["requester_ref"] = json!("r".repeat(4_097)); + assert!(matches!( + err(&string_limit), + RequestRecordError::StructuralLimit + )); + // A valid closed envelope padded to exactly the byte cap is accepted. + let mut exact_valid = bytes(&value); + exact_valid.resize( + rangoon_integrations::lnsat_request_record::MAX_INPUT_BYTES, + b' ', + ); + assert!(inspect_request_record(input(RequestRecordBody::Body200(exact_valid.clone()))).is_ok()); + exact_valid.push(b' '); + assert_eq!( + inspect_request_record(input(RequestRecordBody::Body200(exact_valid))).unwrap_err(), + RequestRecordError::InputLimit + ); + // At a generic parser boundary the grammar succeeds then the closed envelope + // refuses; one unit beyond must be rejected by the parser's quota itself. + let exact_depth = format!("{}0{}", "[".repeat(15), "]".repeat(15)); + assert_eq!( + inspect_request_record(input(RequestRecordBody::Body200(exact_depth.into_bytes()))) + .unwrap_err(), + RequestRecordError::InvalidEnvelope + ); + for (count, expected) in [ + (32, RequestRecordError::InvalidEnvelope), + (33, RequestRecordError::StructuralLimit), + ] { + let object: serde_json::Map = + (0..count).map(|n| (format!("k{n}"), json!(0))).collect(); + assert_eq!( + inspect_request_record(input(RequestRecordBody::Body200(bytes(&Value::Object( + object + ))))) + .unwrap_err(), + expected + ); + } + // 1 root + 64 inner arrays + 4096 leaf arrays + N scalar values. + for (total, expected) in [ + (16_384, RequestRecordError::InvalidEnvelope), + (16_385, RequestRecordError::StructuralLimit), + ] { + let mut remaining = total - 1 - 64 - 4096; + let mut outer = Vec::new(); + for _ in 0..64 { + let mut inner = Vec::new(); + for _ in 0..64 { + let count = remaining.min(64); + remaining -= count; + inner.push(Value::Array(vec![json!(0); count])); + } + outer.push(Value::Array(inner)); + } + assert_eq!(remaining, 0); + assert_eq!( + inspect_request_record(input(RequestRecordBody::Body200(bytes(&Value::Array( + outer + ))))) + .unwrap_err(), + expected + ); + } + // The 16-level generic JSON shape is not reachable through this closed wire + // profile without an unknown field. Test the parser's rejected over-depth + // grammar separately rather than mislabeling an impossible "valid" body. + let deep = format!("{}0{}", "[".repeat(17), "]".repeat(17)); + assert!(matches!( + inspect_request_record(input(RequestRecordBody::Body200(deep.into_bytes()))), + Err(RequestRecordError::StructuralLimit) + )); +} + +#[test] +fn s20_linked_row_and_observation_cardinality_are_closed() { + let mut at_limit = complete("approval_required"); + at_limit["evidence"]["approvals"] = approval_rows(64); + let host = host(&at_limit); + assert_eq!( + host["native"]["evidence"]["approvals"] + .as_array() + .unwrap() + .len(), + 64 + ); + assert_eq!(summary(&at_limit)["familyCounts"]["approvals"], 64); + let mut observations = complete("allow"); + observations["observations"] = json!([ + observation("replay", digest(1), 1), + observation("conflict", digest(2), 2), + observation("replay", digest(1), 3), + ]); + assert!(matches!( + err(&observations), + RequestRecordError::StructuralLimit | RequestRecordError::LineageConflict + )); + let mut rows = complete("allow"); + rows["evidence"]["approvals"] = approval_rows(65); + assert!(matches!(err(&rows), RequestRecordError::StructuralLimit)); +} + +#[test] +fn s21_ids_hashes_and_time_aliases_must_be_canonical() { + for replacement in [ + json!("ARQ_ABC"), + json!("arq_short"), + json!("arq_ABCDEF0000000000000000000000000000000000000000000000000000000000"), + ] { + let mut value = complete("allow"); + value["request_id"] = replacement; + assert!(matches!( + err(&value), + RequestRecordError::InvalidEnvelope | RequestRecordError::SelectionMismatch + )); + } + let mut time = complete("allow"); + time["request"]["created_at"] = json!("2026-10-26T12:00:00Z"); + assert!(matches!(err(&time), RequestRecordError::InvalidEnvelope)); + let mut bad_digest = complete("allow"); + bad_digest["request"]["packet_sha256"] = + json!("sha256:ABCDEF0000000000000000000000000000000000000000000000000000000000"); + assert!(matches!( + err(&bad_digest), + RequestRecordError::InvalidEnvelope + )); + let mut bad_calendar = complete("allow"); + bad_calendar["request"]["created_at"] = json!("2026-02-30T12:00:00.000Z"); + assert!(matches!( + err(&bad_calendar), + RequestRecordError::InvalidEnvelope + )); +} + +#[test] +fn s22_dangling_duplicate_and_cross_family_joins_refuse() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "dispatching", None); + value["evidence"]["authorizations"][0]["approval_decision_id"] = json!(id("apd_", 9)); + assert!(matches!(err(&value), RequestRecordError::LineageConflict)); + let mut duplicate = complete("approval_required"); + add_minimal_execution(&mut duplicate, "dispatching", None); + let duplicate_row = duplicate["evidence"]["approvals"][0].clone(); + duplicate["evidence"]["approvals"] + .as_array_mut() + .unwrap() + .push(duplicate_row); + assert!(matches!( + err(&duplicate), + RequestRecordError::LineageConflict + )); +} + +#[test] +fn s23_consumption_attempt_and_receipt_mismatches_refuse() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "completed", None); + value["evidence"]["receipts"][0]["consumption_id"] = json!(id("cpc_", 9)); + assert!(matches!(err(&value), RequestRecordError::LineageConflict)); + let mut sequence = complete("approval_required"); + add_minimal_execution(&mut sequence, "completed", None); + sequence["evidence"]["operation_attempts"][0]["attempt_sequence"] = json!(2); + assert!(matches!( + err(&sequence), + RequestRecordError::LineageConflict + )); +} + +#[test] +fn s24_state_predecessor_sequence_time_and_transition_gaps_refuse() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "completed", None); + value["evidence"]["states"][3]["prior_state_sequence"] = json!(9); + assert!(matches!(err(&value), RequestRecordError::LineageConflict)); + let mut unsupported = complete("approval_required"); + add_minimal_execution(&mut unsupported, "completed", None); + unsupported["evidence"]["states"][3]["state"] = json!("revived"); + assert!(matches!( + err(&unsupported), + RequestRecordError::UnsupportedState + )); + let mut backward_time = complete("approval_required"); + add_minimal_execution(&mut backward_time, "completed", None); + backward_time["evidence"]["states"][3]["effective_at"] = json!(at(4)); + assert!(matches!( + err(&backward_time), + RequestRecordError::LineageConflict + )); + let mut fork = complete("approval_required"); + add_minimal_execution(&mut fork, "completed", None); + let copied = fork["evidence"]["states"][3].clone(); + fork["evidence"]["states"] + .as_array_mut() + .unwrap() + .push(copied); + assert!(matches!(err(&fork), RequestRecordError::LineageConflict)); +} + +#[test] +fn s25_reconciliation_tuple_mismatches_refuse() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "completed", Some("matched")); + value["evidence"]["reconciliations"][0]["observed_result_digest"] = json!(digest(9)); + assert!(matches!(err(&value), RequestRecordError::LineageConflict)); + let mut pending = complete("approval_required"); + add_minimal_execution(&mut pending, "completed", Some("pending")); + pending["evidence"]["reconciliations"][0]["receipt_id"] = json!(id("rcp_", 1)); + assert!(matches!(err(&pending), RequestRecordError::InvalidEnvelope)); +} + +#[test] +fn s26_failed_or_receiptless_terminal_chains_do_not_gain_effect_claims() { + let mut unknown_chain = complete("approval_required"); + add_minimal_execution(&mut unknown_chain, "outcome_unknown", None); + let host = host(&unknown_chain); + assert_eq!(host["truth"]["independentEffect"], "not_observed"); + let mut impossible = complete("approval_required"); + add_minimal_execution(&mut impossible, "completed", None); + impossible["evidence"]["receipts"] = json!([]); + assert!(matches!( + err(&impossible), + RequestRecordError::LineageConflict + )); +} + +#[test] +fn s27_requester_and_approval_reason_are_validated_then_redacted() { + let mut value = complete("approval_required"); + add_minimal_execution(&mut value, "dispatching", None); + let result = inspect(&value).unwrap(); + let host_text = std::str::from_utf8(result.host_json()).unwrap(); + let summary_text = std::str::from_utf8(result.summary_json()).unwrap(); + assert!(!host_text.contains(REQUESTER_SENTINEL)); + assert!(!host_text.contains("approval.operator_approved")); + assert!(!summary_text.contains(REQUESTER_SENTINEL)); + assert!(!summary_text.contains("approval.operator_approved")); + assert!(!format!("{result:?}").contains(REQUESTER_SENTINEL)); + value["evidence"]["approval_decisions"][0]["reason"] = json!("private-free-text-must-refuse"); + assert_eq!(err(&value), RequestRecordError::UnsupportedState); + let mut invalid_requester = complete("allow"); + invalid_requester["request"]["requester_ref"] = Value::Null; + assert_eq!(err(&invalid_requester), RequestRecordError::InvalidEnvelope); +} + +#[test] +fn s28_summary_has_no_copied_native_identifiers_or_times() { + let result = inspect(&complete("allow")).unwrap(); + let summary_text = std::str::from_utf8(result.summary_json()).unwrap(); + let packet = digest(1); + let created = at(0); + for secret in [ + REQUEST, + PROJECT, + RESOURCE, + "packet:synthetic", + packet.as_str(), + created.as_str(), + ] { + assert!(!summary_text.contains(secret)); + } + assert!(host(&complete("allow"))["native"]["request"]["request_id"].is_string()); +} + +#[test] +fn s29_unexpected_sensitive_wire_fields_refuse_without_echo() { + let mut value = complete("allow"); + value["token"] = json!("secret-never-echo"); + let error = err(&value); + assert!(matches!(error, RequestRecordError::InvalidEnvelope)); + let text = format!("{error:?}"); + assert!(!text.contains("secret-never-echo")); +} + +#[test] +fn s30_security_activity_is_only_reported_bookkeeping() { + let mut value = complete("allow"); + value["security_activity_touched"] = json!(true); + let host = host(&value); + assert_eq!(host["securityActivityTouched"], true); + assert_eq!(host["truth"]["authority"], "none"); + assert_eq!(host["truth"]["independentEffect"], "not_observed"); +} + +#[test] +fn s31_serialized_output_oracle_covers_every_variant() { + for (error, code) in [ + (RequestRecordError::InputLimit, "input_limit"), + (RequestRecordError::InvalidEncoding, "invalid_encoding"), + (RequestRecordError::InvalidJson, "invalid_json"), + (RequestRecordError::DuplicateField, "duplicate_field"), + (RequestRecordError::StructuralLimit, "structural_limit"), + (RequestRecordError::UnsupportedSchema, "unsupported_schema"), + (RequestRecordError::InvalidEnvelope, "invalid_envelope"), + (RequestRecordError::SelectionMismatch, "selection_mismatch"), + (RequestRecordError::ScopeMismatch, "scope_mismatch"), + (RequestRecordError::LineageConflict, "lineage_conflict"), + (RequestRecordError::UnsupportedState, "unsupported_state"), + (RequestRecordError::OutputLimit, "output_limit"), + ( + RequestRecordError::SerializationFailed, + "serialization_failed", + ), + ] { + assert_error_code(error, code); + } + let allow = complete("allow"); + let allow_bytes = bytes(&allow); + let (allow_actual, allow_expected) = assert_reference_case( + RequestRecordBody::Body200(allow_bytes.clone()), + Some(&allow_bytes), + Some(&allow), + ("complete", "policy_recorded", "allow"), + Some(false), + None, + ); + + let failed = failed("evaluation_rejected"); + let failed_bytes = bytes(&failed); + assert_reference_case( + RequestRecordBody::Body200(failed_bytes.clone()), + Some(&failed_bytes), + Some(&failed), + ("complete", "evaluation_failed", "not_observed"), + Some(false), + None, + ); + + let unknown = unknown(); + let unknown_bytes = bytes(&unknown); + assert_reference_case( + RequestRecordBody::Body200(unknown_bytes.clone()), + Some(&unknown_bytes), + Some(&unknown), + ("complete", "evaluation_unknown", "not_observed"), + Some(false), + None, + ); + + let mut full_graph = complete("approval_required"); + add_minimal_execution(&mut full_graph, "completed", Some("matched")); + let full_graph_bytes = bytes(&full_graph); + assert_reference_case( + RequestRecordBody::Body200(full_graph_bytes.clone()), + Some(&full_graph_bytes), + Some(&full_graph), + ("complete", "policy_recorded", "approval_required"), + Some(false), + None, + ); + + let degraded = degraded(); + let degraded_bytes = bytes(°raded); + assert_reference_case( + RequestRecordBody::Body200(degraded_bytes.clone()), + Some(°raded_bytes), + None, + ("degraded", "evaluation_unknown", "not_observed"), + Some(true), + None, + ); + + let refusal = bytes(&json!({ + "schema":"lnsat.action_request_record.v1", + "ok":false, + "error":{"code":"gateway.action_request_record.denied"}, + })); + assert_reference_case( + RequestRecordBody::Refused403(refusal.clone()), + Some(&refusal), + None, + ("read_rejected_unclassified", "not_observed", "not_observed"), + None, + Some("native_read_rejected_unclassified"), + ); + + for (read, failure) in [ + (ReadUnavailable::NotConfigured, "read_not_configured"), + ( + ReadUnavailable::TransportUnavailable, + "read_transport_unavailable", + ), + (ReadUnavailable::Cancelled, "read_cancelled"), + (ReadUnavailable::Timeout, "read_timeout"), + (ReadUnavailable::Unauthenticated, "read_unauthenticated"), + ( + ReadUnavailable::UnsupportedTransport, + "read_unsupported_transport", + ), + ] { + assert_reference_case( + RequestRecordBody::ReadUnavailable(read), + None, + None, + ("read_unavailable", "not_observed", "not_observed"), + None, + Some(failure), + ); + } + + let permuted_bytes = reverse_top_level_bytes(&allow); + let (permuted_actual, _) = assert_reference_case( + RequestRecordBody::Body200(permuted_bytes.clone()), + Some(&permuted_bytes), + Some(&allow), + ("complete", "policy_recorded", "allow"), + Some(false), + None, + ); + assert_ne!(allow_actual.input_digest(), permuted_actual.input_digest()); + assert_eq!(allow_actual.summary_json(), permuted_actual.summary_json()); + + let mut nested_wrong = allow_expected.clone(); + nested_wrong["native"]["request"]["project_ref"] = json!("project:wrong"); + assert!( + std::panic::catch_unwind(|| { + assert_eq!(allow_actual.host_json(), reference_bytes(&nested_wrong)); + }) + .is_err() + ); + let mut extra_field = allow_expected.clone(); + extra_field["native"]["evidence"]["policy"]["extra"] = json!(true); + assert!(std::panic::catch_unwind(|| reference_bytes(&extra_field)).is_err()); + assert!( + std::panic::catch_unwind(|| { + assert_eq!( + allow_actual.host_json(), + reverse_top_level_bytes(&allow_expected) + ); + }) + .is_err() + ); + let expected_bytes = reference_bytes(&allow_expected); + let policy_bytes = reference_bytes(&allow_expected["native"]["evidence"]["policy"]); + let reversed_policy = reverse_top_level_bytes(&allow_expected["native"]["evidence"]["policy"]); + let offset = expected_bytes + .windows(policy_bytes.len()) + .position(|window| window == policy_bytes) + .expect("nested policy bytes"); + let mut nested_order = expected_bytes.clone(); + nested_order.splice(offset..offset + policy_bytes.len(), reversed_policy); + assert!( + std::panic::catch_unwind(|| { + assert_eq!(allow_actual.host_json(), nested_order.as_slice()); + }) + .is_err() + ); + + let mut malformed = allow; + malformed["unexpected"] = json!(true); + assert_error_code(err(&malformed), "invalid_envelope"); +} + +#[test] +fn s32_input_digest_binds_exact_bytes_and_commitment_tampering_refuses() { + let value = complete("allow"); + let original = bytes(&value); + let result = + inspect_request_record(input(RequestRecordBody::Body200(original.clone()))).unwrap(); + let expected = format!("sha256:{}", byte_digest(&original)); + assert_eq!(result.input_digest(), Some(expected.as_str())); + let mut tampered = value; + tampered["evaluation"]["evidence_digest"] = json!(digest(99)); + assert!(matches!( + err(&tampered), + RequestRecordError::LineageConflict + )); +} + +#[test] +fn s33_foreign_openshell_fields_do_not_create_a_bridge() { + let mut value = complete("allow"); + value["openshell_trace"] = json!(REQUEST); + assert!(matches!(err(&value), RequestRecordError::InvalidEnvelope)); +} + +#[test] +fn s34_profile_is_separate_from_d3a_i1_a1_o1_and_o2() { + let result = inspect(&complete("allow")).unwrap(); + let text = std::str::from_utf8(result.host_json()).unwrap(); + for forbidden in [ + "runtime_composition", + "DecodedWindow", + "operator-view.v1", + "O1", + "O2", + ] { + assert!(!text.contains(forbidden)); + } + assert!(text.contains("rangoon.integrations.lnsat-request-record.v1")); +} + +#[test] +fn s35_public_input_shape_has_no_transport_or_mutation_port() { + let _ = RequestRecordInput { + installation_id: "i".into(), + environment: "e".into(), + selected_request_id: REQUEST.into(), + expected_project_ref: PROJECT.into(), + expected_resource_ref: RESOURCE.into(), + body: RequestRecordBody::ReadUnavailable(ReadUnavailable::Timeout), + read_at: None, + }; + // Compile-time construction is the structural oracle: the public input has + // only caller context and typed bytes/read condition, never URL, callback, + // credential, store, process, clock, or reconciliation capability. +} + +#[test] +fn s36_decoder_is_provider_free_and_not_an_o1_o2_serializer() { + let result = inspect(&complete("allow")).unwrap(); + let host_text = std::str::from_utf8(result.host_json()).unwrap(); + let summary_text = std::str::from_utf8(result.summary_json()).unwrap(); + assert!(!host_text.contains("provider")); + assert!(!summary_text.contains("provider")); + assert!(!host_text.contains("operator-view")); +} diff --git a/docs/development.md b/docs/development.md index ed882e4..1574376 100644 --- a/docs/development.md +++ b/docs/development.md @@ -3935,3 +3935,31 @@ Validation: `node --test tests/workspace-lock-model.test.mjs tests/workspace-loc Independent review: an OpenAI GPT-5.6-Terra xhigh security reviewer found an observed-close purge/ack omission and a stale-C1 identity gap; both were fixed with regression tests, then no P1/P2 remained. Its P3 missing locked→unlock success test was added. A separate OpenAI GPT-5.6-Terra xhigh UI reviewer found light-theme action contrast and a false unavailable announcement during successful reload; both were fixed and its final review passed with no open P1/P2/P3. A GPT-5.6-Terra high frontend worker authored the initial bounded implementation; the Sol controller owned contract, security fixes, integration, QA, docs and final judgment. GLM source transfer was rejected by automatic approval review; no Z.AI transfer or retry occurred. Native GPT review supplied the safe fallback. Spark was not used. Acceptance remains bounded to source and synthetic UI evidence. Production host still mounts Legacy plaintext and portable backups remain plaintext; Managed construction is test-only. A qualified encrypted factory, native sheet/actual vault GUI, durable recovery/failure wake across process exits, explicit Legacy import, encrypted archives and isolated macOS/Windows/Linux GUI evidence remain open. No normal database/vault, provider, paid call, credential, execution, default activation, migration, installer, push, merge, deploy or release occurred in this packet. + +## Offline LNSAT request-record decoder — October 26, 2026 + +Authority: Jeff directly accepted the reviewed decoder, bounded synthetic tests and independent GPT review. Canonical source evidence is `/private/tmp/rangoon-request-record-source-20261026`; the accepted preparation remains `/private/tmp/rangoon-request-record-decoder-preparation-20261025-VMBBo0`, using spec_03, OUTPUT_CONTRACT_02, NATIVE_FIELDS, NATIVE_RULES and matrix03. Repository branch/base is `codex/personal-workbench-20261024` at `c132ea62bc57b29375ee8c5a3a38ca005462ca40`; substantial earlier uncommitted work is preserved. This packet owns only new decoder/test files, the exact module declaration, and additive README/connector/ledger text. No publication or runtime authority follows. + +Experience: truthful offline request/evaluation/linked-evidence inspection with separate complete, unknown, failed, degraded, refused and unavailable states. No UI or renderer is mounted. Technical: strict bounded duplicate-aware parsing, exact wire/selector/type/enum checks, canonical dates/digests, coherent approval/authorization/consumption/attempt/receipt/state/reconciliation joins, public evaluation/observation commitments and ordered deterministic projection. Exact inputDigest binds original body bytes; input key reordering changes that digest while all other canonical projection data and summary stay invariant. D3a's source/tests/fixture and f669181a runtime-composition pin remain byte-exact; the new profile independently selects LNSAT source35a41963, not current-main or installed compatibility. + +Privacy/authority: validate before omitting requester_ref and approval-decision reason. Host bytes retain sensitive correlation identifiers in caller-owned memory; summaries contain fixed labels and bounded counts, and Debug/errors do not echo payload. No new dependency/build privilege, credential/session, network, storage, clock, process, live read or reconciliation port exists. A coherent receipt means reported native evidence, never authenticated authority or independently verified effect. Native GET permissions, reconciliation-write authority, consent/encrypted retention/purge and all six connected L01–L06 obligations remain separate and NOT_RUN. Rangoon remains provider-independent; O1/O2, VUSL and OpenShell contracts are unchanged. Applicable OpenSSF/ISO work is bounded engineering evidence, not a badge/compliance/security-clearance claim. + +Validation: existing conditional Rust1.99.1 compiler/rustdoc/Cargo/rustfmt/Clippy tuple verified using the repository checker; locked offline dependencies, no installs/downloads or cache transfer. Each recorded controller command is bounded to at most600seconds/8MiB combined output. tests04 passes81 unique package tests:19 library,14 unchanged D3a,36 new synthetic/structural decoder groups and12 OpenShell observations; repeated earlier attempts are not additional unique cases. Strict all-target package Clippy02 and workspace format-check01 pass. Tests are trusted controller source fixtures, not native platform, physical custody/deadline/cleanup, real effect, production runtime or support proof. Source/static-only S35 supplements the compile-time API check; it is not a sandbox/syscall audit. Final document-check and independent-review outcome are recorded below when complete. + +Earlier syntax/type errors, test borrow failure,33/36 first behavioral result and strict lint failure remain in evidence. Three oracle corrections retain strict refusal: decoded-string overflow is StructuralLimit; invalid pending/null tuple is InvalidEnvelope; canonical projection invariance excludes the mandatory exact-body digest. The malformed Unicode escape byte-slicing defect and incomplete draft graph/output ordering were corrected before qualification. All available exact drafts remain retained; no universal historical draft-preservation claim. During work five unowned documents changed concurrently; their current bytes were left untouched, with dated hash observations rather than an unchanged-whole-tree claim. Shared-doc additions preserve current prefixes. Original missing caches, restored originals and frozen native/VM/archive evidence were never probed. + +Producer: primary Codex integration plus native OpenAI gpt_worker roles configured gpt-5.6-terra/high for disjoint implementation/test drafts. Reviewer: fresh native OpenAI gpt_reviewer configured gpt-5.6-terra/xhigh, backend runtime model ID unexposed. Independent source/test review is PASS; the final document readback is recorded separately. No GLM/external-provider source transfer, commit, push, PR, merge, install, target Git/runtime, host/VM/native/archive operation, deploy or release occurred. Next work remains separately scoped; no automatic promotion to connected operation. + + + +Final source/test qualification: independent native OpenAI GPT reviewer PASS with no actionable P1/P2/P3 on source1365148451d70c35afc01491078e0b8b5c9ab2c7eb506082d933ac921d720b40 and testea65867f1c8e562bb9894d8a90348df720519b12445e5e58c722dd3170b0bc8c. Review's P2 exposed incomplete S31 byte-oracle coverage; the corrected independent serializer now compares full host/summary bytes for all variants and a full graph, nested field/value/order mutations, and all13 fixed errors. The initial reference-oracle count/evidence-shape error is preserved. Final tests10 passes36/36, strict Clippy04 and owned-format02 pass. The unchanged45 package regressions reuse tests04; there are81 unique tests, not accumulated repeated counts. Document-only final readback is separate; source/test/review evidence does not open L01–L06 or runtime. No current packet publication occurred. + +## Request-record decoder publication — October 26, 2026 + +Jeff separately authorized committing and pushing only the reviewed decoder slice, opening a PR and hosted source CI; merge, live reads, reconciliation, local installs and product/target runtime remain closed. Publication is isolated from the dirty worktree on public main `9bd9be17d17fd8f778ec88f8e9b9f41df5c01dc4`. Only the two decoder files, one module declaration and their README/connector/development additions are selected; the publication compatibility delta is recorded below. No D3a, dependency, toolchain or workflow change is included. Earlier Rust 1.99.1 fixture evidence is dated and conditional; public main still selects Rust 1.85.0 for core CI and 1.98.0 for desktop. Hosted exact-candidate results remain pending. No previous green source result establishes this candidate or runtime compatibility. Private publication receipts: `/private/tmp/rangoon-decoder-publication-20261026`. + +Publication integration found the reviewed decoder used unsigned `is_multiple_of` (stable since Rust 1.87) although public core CI selects Rust 1.85. Only the leap-year expression was replaced with equivalent remainder comparisons against the same fixed nonzero divisors 4, 100 and 400. The original reviewed source remains preserved in its private packet and dirty checkout. Test bytes and wire/output behavior are unchanged; the corrected publication source requires separate Rust 1.85 validation and independent delta review before publication. No CI pin, workflow, dependency or D3a changes are included. + +Current publication validation: the existing Rust 1.85.0 tuple passed all 78 package tests (19 library, 11 unchanged public-base D3a, 36 new decoder and 12 OpenShell), zero failures/ignored, through locked offline Cargo. The earlier 81-test source receipt includes three unrelated dirty-worktree D3a tests and is not the public-base regression count. Strict package all-target Clippy02 passes with warnings denied. Clippy01 correctly rejected one needless explicit implementation lifetime; replacing `impl<'a> Parser<'a>` with `impl Parser<'_>` is the second compatibility-only line change. No lint exemption was added. Workspace Rustfmt01 and document/reference checks (469 authored files, eight image hashes and historical brief) pass; the final exact-source format/readback and independent integration review are recorded separately. Existing source reviews are reused for the unchanged decoder/test behavior; historical receipts and failed attempts remain preserved. + +Publication integration qualification: final Rust 1.85 package tests02 passed 78/78; strict all-target package Clippy02, final workspace Rustfmt02, scoped whitespace and document/reference validation passed (469 authored text files). Fresh independent native OpenAI `gpt_reviewer`, configured `gpt-5.6-terra/xhigh`, reviewed the six-path integration and exact two-line compatibility delta: PASS with no actionable P1/P2/P3. Backend runtime model ID is unexposed. No source/test/dependency/workflow bytes changed after those checks. Hosted source CI and publication outcome remain separately pending; no merge or runtime authority follows. diff --git a/docs/lnsat-evidence-connector.md b/docs/lnsat-evidence-connector.md index 9ad12f4..b49d3fd 100644 --- a/docs/lnsat-evidence-connector.md +++ b/docs/lnsat-evidence-connector.md @@ -90,3 +90,15 @@ A1 remains frozen and unavailable. D3 adds a separately versioned native-evidenc ## Non-goals and open questions Unresolved before D3b: supported LNSAT artifact and exact read contract; least-privilege external caller route; whether individual approval/audit evidence can be read without excessive privilege; native payload retention; and trustworthy cross-engine binding. This document opens none of those gates and makes no current LNSAT support claim. LNSAT installation, configuration mutation, action submission, grant redemption, POST reconciliation, managed proxying, and automatic OpenShell correlation are outside D3. + +## Separate offline request-record profile — October 26, 2026 + +Direct human source acceptance opened the reviewed request-record decoder, bounded synthetic tests and independent GPT review only. The private preparation packet remains frozen; its historical preparation-only labels are superseded only for this exact source/test slice. The [development receipt](development.md#offline-lnsat-request-record-decoder--october-26-2026) owns actual validation and review results. + +`rangoon-integrations::lnsat_request_record` is a separate pure memory decoder for `lnsat.action_request_record.v1` at selected source commit `35a41963ad698934c7ee00852c71355e329c34fa`. That immutable research pin is not current-main, installed-version or runtime compatibility proof. D3a's module, test fixtures, outputs and `f669181a` runtime-composition pin are preserved. + +One coherent caller-owned record is checked against independently selected request/project/resource references. Strict bounded parsing rejects duplicate decoded keys, type coercion, unknown fields, noncanonical IDs/digests/timestamps, contradictory linked objects and unsupported states. Public evaluation/observation digest checks establish reported byte consistency only. Root commitment authentication cannot be derived without private material, which this decoder never requests. Unknown, degraded, refused and unavailable outcomes never become success or permission to retry. Completed chains require their coherent receipt/state joins but remain reported native completion, not physical causal effect. + +Host output removes `requester_ref` and approval-decision `reason` after validation. It retains sensitive native identifiers, references, digests and times only in caller-owned host memory, with a fixed omission ledger. It is not anonymous, renderer-safe or accepted for plaintext persistence. Summary bytes contain only fixed labels and bounded counts; errors and Debug/Display are payload-free. No secret/session/header/path/URL/callback input, logger, network, database, clock sampling, storage or reconciliation interface is introduced. + +Offline decode claims no authentication or permission. A later native GET requires the engine's paired current session/proof and ReadEvidence plus active Owner or original-requester scope. Evidence reading never grants reconciliation-write authority. No POST, login, session cleanup, local capability, role upgrade, production observer/coordinator or actual Git consequence is opened. L01–L06 connected checks, credential custody, consent/encrypted retention/purge, transport, target OS/runtime and independent effect/reconciliation qualification remain separate and unrun. No O1/O2 wire conversion or UI is mounted; Rangoon remains usable without LNSAT and every provider.