//! Trusted host-only NAPI adapter. The TS loader authenticates D01 data with //! validateDatasetV2; this envelope binds identity but is not a second normalizer //! or an untrusted-code sandbox. No mutable financial/clock handles are exported. use super::canonical::{financial_view, parse as parse_contract}; use crate::financial::{ contract::*, replay::*, reporting::ReportingFacts, result::{project, FinancialProjection}, }; use napi::{Error, Result}; #[cfg(not(test))] use napi_derive::napi; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::{json, Value}; #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Identity { version: Version, session_id: Id, dataset_hash: String, } #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Load { identity: Identity, prepared: PreparedReplay, config: ReplayConfig, manifest: Value, } #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Advance { identity: Identity, event_budget: Counter, } #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Submit { identity: Identity, barrier_id: Id, decisions: Vec, } /// Borrow retained provenance and flattened financial facts instead of building /// a serde_json::Value tree for the entire nested journal. #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct ProjectionResult<'a> { format: &'static str, projection_version: Version, financial_version: Version, identity: &'a Identity, status: &'static str, manifest: &'a Value, policy: &'a ReplayConfig, view: Value, limitations: &'a [String], model_limitations: &'static [&'static str], projection: FinancialProjection<'a>, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct ReportResult<'a> { #[serde(flatten)] financial: ProjectionResult<'a>, reporting_version: Version, reporting: &'a ReportingFacts, } fn error(error: impl std::fmt::Display) -> Error { Error::from_reason(error.to_string()) } fn parse(input: &str) -> Result { parse_contract(input, "unexpected or missing session contract fields") } pub struct ReplayHost { replay: Option, identity: Identity, manifest: Value, config: ReplayConfig, delivered: usize, } impl ReplayHost { pub fn new(input: String) -> Result { let load: Load = parse(&input)?; let hash = &load.identity.dataset_hash; if hash.len() != 64 || !hash .bytes() .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) || load.identity.session_id != load.config.matching.risk.ledger.session_id || serde_json::to_value(&load.prepared.dataset_id).map_err(error)? != json!(hash) || load.manifest.get("hash") != Some(&json!(hash)) || load.manifest.get("version") != Some(&json!(2)) { return Err(error("session/dataset identity or version mismatch")); } let replay = Replay::new(load.prepared, load.config.clone()).map_err(error)?; Ok(Self { replay: Some(replay), identity: load.identity, manifest: load.manifest, config: load.config, delivered: 0, }) } pub fn advance(&mut self, input: String) -> Result { let request: Advance = parse(&input)?; self.check(&request.identity)?; let replay = self.replay.as_mut().unwrap(); let step = replay .advance(usize::try_from(request.event_budget.get()).map_err(error)?) .map_err(error)?; // Borrow a delta, not checkpoint/history clones. Only published bars can // enter this array; the future vector is never serialized to callbacks. let observations: Vec<_> = replay.observations_since(self.delivered).collect(); let delivered = self.delivered + observations.len(); let payload = match step { ReplayStep::Progress { processed } => json!({"type":"progress", "processed":processed}), ReplayStep::Decision(barrier) => { json!({"type":"decisionBatch", "barrier":barrier, "view":view(replay)?}) } ReplayStep::Complete => json!({"type":"complete"}), ReplayStep::Failed { diagnostic } => json!({"type":"failed", "diagnostic":diagnostic}), }; let output = serde_json::to_string( &json!({"identity":self.identity,"step":payload,"observations":observations}), ) .map_err(error)?; self.delivered = delivered; Ok(output) } pub fn submit(&mut self, input: String) -> Result { let request: Submit = parse(&input)?; self.check(&request.identity)?; let outcome = self .replay .as_mut() .unwrap() .submit(DecisionSubmission { barrier_id: request.barrier_id, decisions: request.decisions, }) .map_err(error)?; serde_json::to_string(&json!({"identity":self.identity,"outcome":outcome})).map_err(error) } pub fn finalize(&self, input: String) -> Result { let identity: Identity = parse(&input)?; self.check(&identity)?; let replay = self.replay.as_ref().unwrap(); if replay.status() != &ReplayStatus::Complete { return Err(error("only a complete replay can finalize successfully")); } serde_json::to_string(&json!({ "identity":self.identity,"status":"complete", "manifest":self.manifest, "policy":self.config,"view":view(replay)?, "receipts":replay.financial().receipts(), "limitations":replay.limitations(),"modelLimitations":replay.model_limitations() })) .map_err(error) } pub fn dispose(&mut self) { self.replay = None; } pub fn project(&self, input: String) -> Result { let identity: Identity = parse(&input)?; self.check(&identity)?; let replay = self.replay.as_ref().unwrap(); if replay.status() != &ReplayStatus::Complete { return Err(error("only a complete replay can project successfully")); } serde_json::to_string(&ProjectionResult { format: "projection", projection_version: Version, financial_version: Version, identity: &self.identity, status: "complete", manifest: &self.manifest, policy: &self.config, view: view(replay)?, limitations: replay.limitations(), model_limitations: replay.model_limitations(), projection: project(replay.financial().ledger()).map_err(error)?, }) .map_err(error) } pub fn report(&self, input: String) -> Result { let identity: Identity = parse(&input)?; self.check(&identity)?; let replay = self.replay.as_ref().unwrap(); let reporting = replay.reporting().map_err(error)?; serde_json::to_string(&ReportResult { financial: ProjectionResult { format: "report", projection_version: Version, financial_version: Version, identity: &self.identity, status: "complete", manifest: &self.manifest, policy: &self.config, view: view(replay)?, limitations: replay.limitations(), model_limitations: replay.model_limitations(), projection: project(replay.financial().ledger()).map_err(error)?, }, reporting_version: Version, reporting, }) .map_err(error) } } // NAPI's impl macro requires literal method annotations. Keep this tiny // delegation out of Rust unit tests; ReplayHost is the exact production host. #[cfg(not(test))] #[napi] pub struct FinancialReplaySession(ReplayHost); #[cfg(not(test))] #[napi] impl FinancialReplaySession { #[napi(constructor)] pub fn new(input: String) -> Result { Ok(Self(ReplayHost::new(input)?)) } #[napi] pub fn advance(&mut self, input: String) -> Result { self.0.advance(input) } #[napi] pub fn submit(&mut self, input: String) -> Result { self.0.submit(input) } #[napi] pub fn finalize(&self, input: String) -> Result { self.0.finalize(input) } #[napi] pub fn project(&self, input: String) -> Result { self.0.project(input) } #[napi] pub fn report(&self, input: String) -> Result { self.0.report(input) } #[napi] pub fn dispose(&mut self) { self.0.dispose(); } } impl ReplayHost { fn check(&self, identity: &Identity) -> Result<()> { if self.replay.is_none() { return Err(error("replay session is disposed")); } if identity.session_id != self.identity.session_id || identity.dataset_hash != self.identity.dataset_hash { return Err(error("session/dataset identity mismatch")); } Ok(()) } } fn view(replay: &Replay) -> Result { let matching = replay.financial(); financial_view(matching.risk(), matching.admission_revision(), |id| { matching.order(id) }) } #[cfg(test)] mod tests { use super::*; use crate::financial::native_paper_tests::stage_financial_transaction; // Drive the paper host from the same financial commands as replay. Compare // every published boundary, including open reservations, fills and finish. fn assert_paper_view(replay: &Replay, identity: &Value, paper: &mut Value) { let delivered = paper["checkpoint"]["receipts"].as_array().unwrap().len(); for receipt in &replay.financial().receipts()[delivered..] { let crate::financial::matching::MatchingInput::Engine(command) = &receipt.input else { panic!("fixture unexpectedly contains an operator command"); }; *paper = serde_json::from_str( &stage_financial_transaction( json!({ "version": 1, "kind": "apply", "identity": identity, "checkpoint": paper["checkpoint"], "command": command, }) .to_string(), ) .unwrap(), ) .unwrap(); } assert_eq!(paper["view"], view(replay).unwrap()); assert_eq!( paper["checkpoint"], serde_json::to_value(replay.financial().checkpoint()).unwrap() ); } #[test] fn native_intent_trace_matches_direct_replay_receipts() { // The TS fixture asserts its verified D01 adaptation equals this exact // load; compare the NAPI pull transport with direct authoritative replay. let fixture = include_str!("../../../../../test/fixtures/native-replay-load.json"); let load: Load = parse(fixture).unwrap(); let paper_identity = json!({ "sessionId": load.identity.session_id, "accountId": load.config.matching.risk.ledger.account_id, }); let mut paper: Value = serde_json::from_str( &stage_financial_transaction( json!({ "version": 1, "kind": "initialize", "identity": paper_identity, "config": load.config.matching, }) .to_string(), ) .unwrap(), ) .unwrap(); let mut direct = Replay::new(load.prepared, load.config).unwrap(); let mut native = ReplayHost::new(fixture.into()).unwrap(); let identity = serde_json::to_value(&load.identity).unwrap(); let mut sequence = 0; loop { assert_paper_view(native.replay.as_ref().unwrap(), &paper_identity, &mut paper); let raw = native .advance(json!({"identity":identity,"eventBudget":1}).to_string()) .unwrap(); let response: Value = serde_json::from_str(&raw).unwrap(); match direct.advance(1).unwrap() { ReplayStep::Progress { .. } => assert_eq!(response["step"]["type"], "progress"), ReplayStep::Decision(barrier) => { assert_eq!( response["step"]["barrier"], serde_json::to_value(&barrier).unwrap() ); let decisions:Vec=serde_json::from_value(json!([{ "version":1,"sessionId":"f07-fixture","barrierId":barrier.barrier_id,"revision":barrier.revision, "decision":{"ownerId":"A","decisionId":serde_json::to_string(&json!(["trace",sequence,"A"])).unwrap(),"sequence":sequence}, "intent":{"mode":"target","targets":if sequence==0 {json!([{"instrumentId":"X0.US","quantity":"2.00000000"}])} else {json!([])}} }])).unwrap(); let native_out:Value=serde_json::from_str(&native.submit(json!({"identity":identity,"barrierId":barrier.barrier_id,"decisions":decisions}).to_string()).unwrap()).unwrap(); let outcome = direct .submit(DecisionSubmission { barrier_id: barrier.barrier_id, decisions, }) .unwrap(); assert_eq!( native_out["outcome"], serde_json::to_value(outcome).unwrap() ); sequence += 1; } ReplayStep::Complete => break, ReplayStep::Failed { diagnostic } => panic!("{diagnostic}"), } } assert_paper_view(native.replay.as_ref().unwrap(), &paper_identity, &mut paper); let final_result: Value = serde_json::from_str(&native.finalize(identity.to_string()).unwrap()).unwrap(); assert_eq!( final_result["receipts"], serde_json::to_value(direct.financial().receipts()).unwrap() ); assert_eq!(final_result["view"]["portfolio"]["cash"], "9975.76000000"); assert_eq!(final_result["view"]["equity"], "10005.76000000"); let before = native.replay.as_ref().unwrap().checkpoint(); let compact = native.project(identity.to_string()).unwrap(); assert_eq!(native.project(identity.to_string()).unwrap(), compact); assert_eq!(native.replay.as_ref().unwrap().checkpoint(), before); assert_eq!( serde_json::from_str::(&native.finalize(identity.to_string()).unwrap()).unwrap(), final_result ); let projected: Value = serde_json::from_str(&compact).unwrap(); let report = native.report(identity.to_string()).unwrap(); assert_eq!(native.report(identity.to_string()).unwrap(), report); assert_eq!(native.project(identity.to_string()).unwrap(), compact); assert_eq!(native.replay.as_ref().unwrap().checkpoint(), before); let reported: Value = serde_json::from_str(&report).unwrap(); assert_eq!(reported["projection"], projected["projection"]); assert_eq!(reported["reporting"]["occupiedMs"], "120000"); assert_eq!(projected["view"], final_result["view"]); assert!(projected.get("receipts").is_none()); let load: Load = parse(fixture).unwrap(); let restored = Replay::restore(load.prepared, load.config, &before).unwrap(); assert_eq!( projected["projection"], serde_json::to_value(project(restored.financial().ledger()).unwrap()).unwrap() ); assert_eq!( reported["reporting"], serde_json::to_value(restored.reporting().unwrap()).unwrap() ); native.dispose(); assert!(native.finalize(identity.to_string()).is_err()); assert!(native.project(identity.to_string()).is_err()); assert!(native.report(identity.to_string()).is_err()); } }