feat(research): add financial contracts and availability-aware datasets

Implement reviewed F01/D01 foundations without changing active trading runtimes. Validate strict Rust/TypeScript financial wire contracts, decimal postings, versioned datasets, explicit calendars, provenance, and v1 compatibility.
This commit is contained in:
Boki 2026-10-22 20:51:25 -04:00
parent 243e9ab43f
commit b4af840d4e
25 changed files with 4071 additions and 43 deletions

17
Cargo.lock generated
View file

@ -56,6 +56,12 @@ dependencies = [
"num-traits",
]
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "async-trait"
version = "0.1.88"
@ -252,6 +258,7 @@ dependencies = [
"parking_lot",
"rand",
"rand_distr",
"rust_decimal",
"serde",
"serde_json",
"statrs",
@ -766,6 +773,16 @@ version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "rust_decimal"
version = "1.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a"
dependencies = [
"arrayvec",
"num-traits",
]
[[package]]
name = "rustc-demangle"
version = "0.1.25"

View file

@ -29,6 +29,7 @@ napi = { version = "2", features = ["async", "chrono_date", "serde-json"] }
napi-derive = "2"
# Math and statistics
rust_decimal = { version = "=1.43.0", default-features = false }
statrs = "0.16"
rand = "0.8"
rand_distr = "0.4"

View file

@ -0,0 +1,368 @@
//! Strict v1 economic wire shapes. Internal engine commands are deliberately a
//! different type from strategy decisions: strategies cannot submit fills,
//! cash mutations, marks, or account-risk-session boundaries.
use super::scalar::Posting;
use serde::{de, Deserialize, Deserializer, Serialize};
const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct Id(String);
impl<'de> Deserialize<'de> for Id {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
// Preserve existing instrument/provider IDs verbatim. Dataset admission
// validates instrument membership; generic identity is not that parser.
if s.is_empty() || s.bytes().any(|c| c < 0x20 || c == 0x7f) {
return Err(de::Error::custom(
"expected nonempty identity without control characters",
));
}
Ok(Self(s))
}
}
// JSON.parse accepts integral1.0/1e0 as numbers. Rust uses the same safe-number
// semantics rather than accepting u64 values JavaScript cannot represent.
fn safe_integer<'de, D: Deserializer<'de>>(d: D, signed: bool) -> Result<i64, D::Error> {
let n = serde_json::Number::deserialize(d)?;
let f = n
.as_f64()
.ok_or_else(|| de::Error::custom("expected a safe integer"))?;
if !f.is_finite()
|| f.fract() != 0.0
|| f.abs() > MAX_SAFE_INTEGER as f64
|| (!signed && f < 0.0)
{
return Err(de::Error::custom("expected a safe integer"));
}
Ok(f as i64)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct Counter(u64);
impl Counter {
pub fn get(self) -> u64 {
self.0
}
}
impl TryFrom<u64> for Counter {
type Error = &'static str;
fn try_from(value: u64) -> Result<Self, Self::Error> {
if value <= MAX_SAFE_INTEGER as u64 {
Ok(Self(value))
} else {
Err("expected a safe counter")
}
}
}
impl<'de> Deserialize<'de> for Counter {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Ok(Self(safe_integer(d, false)? as u64))
}
}
/// Unix milliseconds; event time, never an inferred processing clock.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct EventTime(i64);
impl EventTime {
pub fn get(self) -> i64 {
self.0
}
}
impl TryFrom<i64> for EventTime {
type Error = &'static str;
fn try_from(value: i64) -> Result<Self, Self::Error> {
if (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&value) {
Ok(Self(value))
} else {
Err("expected a safe event time")
}
}
}
impl<'de> Deserialize<'de> for EventTime {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Ok(Self(safe_integer(d, true)?))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "Counter", into = "Counter")]
pub struct Version;
impl TryFrom<Counter> for Version {
type Error = &'static str;
fn try_from(value: Counter) -> Result<Self, Self::Error> {
if value.0 == 1 {
Ok(Self)
} else {
Err("unsupported financial protocol version")
}
}
}
impl From<Version> for Counter {
fn from(_: Version) -> Self {
Self(1)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "Posting", into = "Posting")]
pub struct NonNegative(Posting);
impl TryFrom<Posting> for NonNegative {
type Error = &'static str;
fn try_from(value: Posting) -> Result<Self, Self::Error> {
if value.is_negative() {
Err("expected a nonnegative posting")
} else {
Ok(Self(value))
}
}
}
impl From<NonNegative> for Posting {
fn from(value: NonNegative) -> Self {
value.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "Posting", into = "Posting")]
pub struct Positive(Posting);
impl TryFrom<Posting> for Positive {
type Error = &'static str;
fn try_from(value: Posting) -> Result<Self, Self::Error> {
if value.is_negative() || value.is_zero() {
Err("expected a positive posting")
} else {
Ok(Self(value))
}
}
}
impl From<Positive> for Posting {
fn from(value: Positive) -> Self {
value.0
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DecisionIdentity {
pub owner_id: Id,
pub decision_id: Id,
pub sequence: Counter,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskSessionIdentity {
pub calendar_id: Id,
pub calendar_revision: Id,
pub session_id: Id,
pub starts_at: EventTime,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Fee {
pub fee_id: Id,
pub amount: NonNegative,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Side {
Buy,
Sell,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TimeInForce {
GTC,
DAY,
IOC,
FOK,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase",
deny_unknown_fields
)]
pub enum EngineCommandBody {
ApplyFill {
decision: DecisionIdentity,
order_id: Id,
fill_id: Id,
instrument_id: Id,
side: Side,
quantity: Positive,
price: Positive,
fee: Fee,
},
Mark {
instrument_id: Id,
price: Positive,
},
RiskSessionBoundary {
risk_session: RiskSessionIdentity,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EngineFinancialCommand {
pub version: Version,
pub session_id: Id,
pub account_id: Id,
/// Scoped to(sessionId, accountId); identical payload retries are idempotent,
/// conflicting reuse rejects. F02 implements the receipt store, not F01.
pub command_id: Id,
pub event_time: EventTime,
pub body: EngineCommandBody,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Target {
pub instrument_id: Id,
pub quantity: NonNegative,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase",
deny_unknown_fields
)]
pub enum OrderIntent {
Market {
order_id: Id,
instrument_id: Id,
side: Side,
quantity: Positive,
time_in_force: TimeInForce,
},
Limit {
order_id: Id,
instrument_id: Id,
side: Side,
quantity: Positive,
price: Positive,
time_in_force: TimeInForce,
},
Cancel {
order_id: Id,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "camelCase", deny_unknown_fields)]
pub enum StrategyIntent {
Target { targets: Vec<Target> },
Orders { orders: Vec<OrderIntent> },
}
/// A decision in a shared barrier, not an independent mutation endpoint.
/// Registered per-instance mode, owner authority, complete barrier membership,
/// stable admission order and staged state/RNG are enforced by F07/S01.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct StrategyDecision {
pub version: Version,
pub session_id: Id,
pub barrier_id: Id,
pub revision: Counter,
pub decision: DecisionIdentity,
pub intent: StrategyIntent,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct OwnerPosition {
pub owner_id: Id,
pub instrument_id: Id,
pub quantity: NonNegative,
pub remaining_cost: NonNegative,
pub realized_gross_pnl: Posting,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct OwnerFees {
pub owner_id: Id,
pub amount: NonNegative,
}
/// Economic projection ONLY. This is not a complete restorable engine/session
/// snapshot: F02/F04/F07 own receipts, reservations, open orders, risk state,
/// replay cursors and strategy/RNG state. Average cost is deliberately absent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FinancialSnapshot {
pub version: Version,
pub session_id: Id,
pub account_id: Id,
pub revision: Counter,
pub base_currency: Id,
pub reserve_owner_id: Id,
pub cash: NonNegative,
pub positions: Vec<OwnerPosition>,
pub fees: Vec<OwnerFees>,
pub risk_session: RiskSessionIdentity,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase",
deny_unknown_fields
)]
pub enum FinancialEffect {
FillApplied {
owner_id: Id,
order_id: Id,
fill_id: Id,
instrument_id: Id,
price: Positive,
cash_delta: Posting,
quantity_delta: Posting,
released_basis: NonNegative,
realized_gross_pnl: Posting,
},
FeeApplied {
owner_id: Id,
fill_id: Id,
fee_id: Id,
amount: NonNegative,
},
MarkUpdated {
instrument_id: Id,
price: Positive,
},
RiskSessionChanged {
risk_session: RiskSessionIdentity,
},
Rejected {
code: Id,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FinancialEffects {
pub version: Version,
pub session_id: Id,
pub account_id: Id,
pub command_id: Id,
pub event_time: EventTime,
pub revision: Counter,
/// Transition order is authoritative; consumers must not sort these effects.
pub effects: Vec<FinancialEffect>,
}

View file

@ -0,0 +1,9 @@
//! Canonical financial contracts, not yet connected to either legacy simulator.
//!
//! F01 defines transport and checked posting primitives. F02 owns ledger
//! transitions/idempotency; F04 owns risk; F06/F07 own replay/session state.
pub mod contract;
pub mod scalar;
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,107 @@
use rust_decimal::{Decimal, RoundingStrategy};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, str::FromStr};
pub const POSTING_SCALE: u32 = 8;
/// The entire 96-bit coefficient remains available at the fixed posting scale.
pub const MAX_POSTING: &str = "792281625142643375935.43950335";
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ScalarError {
#[error("expected a plain decimal string with at most 8 fractional digits")]
InvalidDecimal,
#[error("financial posting exceeds the fixed-8 decimal range")]
Overflow,
}
/// Money/quantity transport uses strings, never f64. No float constructor or
/// unchecked arithmetic operator is exposed. Multiplication and proportional
/// division are intentionally left to F02's operation-specific implementation:
/// checked decimal operations can still round intermediate precision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Posting(Decimal);
impl Posting {
pub const ZERO: Self = Self(Decimal::ZERO);
pub fn is_negative(self) -> bool {
self.0.is_sign_negative() && !self.0.is_zero()
}
pub fn is_zero(self) -> bool {
self.0.is_zero()
}
pub fn checked_add(self, other: Self) -> Result<Self, ScalarError> {
Self::from_exact_decimal(self.0.checked_add(other.0).ok_or(ScalarError::Overflow)?)
}
pub fn checked_sub(self, other: Self) -> Result<Self, ScalarError> {
Self::from_exact_decimal(self.0.checked_sub(other.0).ok_or(ScalarError::Overflow)?)
}
/// Posting boundary for an already exact internal decimal calculation.
/// Callers must not pass a previously precision-losing intermediate.
/// https://docs.rs/rust_decimal/1.43.0/rust_decimal/enum.RoundingStrategy.html
pub fn from_exact_decimal(value: Decimal) -> Result<Self, ScalarError> {
let max = Decimal::from_str_exact(MAX_POSTING).expect("fixed decimal constant");
// Reject out-of-range intermediates before rounding as well as after it.
if value.abs() > max {
return Err(ScalarError::Overflow);
}
let mut rounded =
value.round_dp_with_strategy(POSTING_SCALE, RoundingStrategy::MidpointAwayFromZero);
if rounded.abs() > max {
return Err(ScalarError::Overflow);
}
if rounded.is_zero() {
rounded = Decimal::ZERO;
}
rounded.rescale(POSTING_SCALE);
// rescale is infallible and may silently use less precision. Never allow
// that behavior through the authoritative fixed-8 boundary.
if rounded.scale() != POSTING_SCALE {
return Err(ScalarError::Overflow);
}
Ok(Self(rounded))
}
}
impl FromStr for Posting {
type Err = ScalarError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let unsigned = text.strip_prefix('-').unwrap_or(text);
let (integer, fraction) = unsigned.split_once('.').unwrap_or((unsigned, ""));
if integer.is_empty()
|| !integer.bytes().all(|c| c.is_ascii_digit())
|| (integer.len() > 1 && integer.starts_with('0'))
|| (unsigned.contains('.') && fraction.is_empty())
|| fraction.len() > POSTING_SCALE as usize
|| !fraction.bytes().all(|c| c.is_ascii_digit())
{
return Err(ScalarError::InvalidDecimal);
}
let value = Decimal::from_str_exact(text).map_err(|_| ScalarError::Overflow)?;
Self::from_exact_decimal(value)
}
}
impl fmt::Display for Posting {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:.8}", self.0)
}
}
impl Serialize for Posting {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for Posting {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(de::Error::custom)
}
}

View file

@ -0,0 +1,241 @@
use super::{
contract::*,
scalar::{Posting, ScalarError, MAX_POSTING},
};
use rust_decimal::Decimal;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
const SCALARS: &str = include_str!("../../../../../test/fixtures/economics/scalars.json");
const CONTRACTS: &str = include_str!("../../../../../test/fixtures/economics/contracts.json");
const LEDGER_SPECS: &str = include_str!("../../../../../test/fixtures/economics/ledger-specs.json");
fn posting(text: &str) -> Posting {
text.parse().unwrap()
}
fn fixture(text: &str) -> Value {
serde_json::from_str(text).unwrap()
}
fn roundtrip<T: DeserializeOwned + Serialize>(value: Value) -> Result<Value, serde_json::Error> {
serde_json::to_value(serde_json::from_value::<T>(value)?)
}
fn parse_wire(kind: &str, value: Value) -> Result<Value, serde_json::Error> {
match kind {
"command" => roundtrip::<EngineFinancialCommand>(value),
"decision" => roundtrip::<StrategyDecision>(value),
"snapshot" => roundtrip::<FinancialSnapshot>(value),
"effects" => roundtrip::<FinancialEffects>(value),
_ => panic!("unknown fixture kind"),
}
}
fn annotate(case: &Value) {
for field in ["id", "owningTask", "assumptions", "handCalculation"] {
assert!(!case[field].as_str().unwrap().is_empty(), "missing {field}");
}
}
#[test]
fn rust_ts_fixture_parse_parity() {
let scalars = fixture(SCALARS);
for case in scalars["cases"].as_array().unwrap() {
annotate(case);
let parsed = serde_json::from_value::<Posting>(case["input"].clone());
if let Some(expected) = case["canonical"].as_str() {
assert_eq!(parsed.unwrap().to_string(), expected, "{}", case["id"]);
} else {
assert!(parsed.is_err(), "{}", case["id"]);
}
}
let contracts = fixture(CONTRACTS);
let valid = contracts["valid"].as_array().unwrap();
for case in valid {
annotate(case);
let parsed = parse_wire(case["type"].as_str().unwrap(), case["input"].clone()).unwrap();
assert_eq!(parsed, case["canonical"], "{}", case["id"]);
assert_eq!(
parse_wire(case["type"].as_str().unwrap(), parsed.clone()).unwrap(),
parsed
);
}
for case in contracts["invalid"].as_array().unwrap() {
annotate(case);
let base = valid.iter().find(|v| v["id"] == case["base"]).unwrap();
let mut input = base["input"].clone();
let path: Vec<_> = case["path"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap())
.collect();
let pointer = if path.len() == 1 {
String::new()
} else {
format!("/{}", path[..path.len() - 1].join("/"))
};
let parent = input
.pointer_mut(&pointer)
.unwrap()
.as_object_mut()
.unwrap();
parent.insert(path.last().unwrap().to_string(), case["value"].clone());
assert!(
parse_wire(base["type"].as_str().unwrap(), input).is_err(),
"{}",
case["id"]
);
}
}
#[test]
fn safe_integer_json_number_parity() {
let contracts = fixture(CONTRACTS);
annotate(&contracts["numeric"]);
for case in contracts["numeric"]["cases"].as_array().unwrap() {
let raw = case["raw"].as_str().unwrap();
assert_eq!(
serde_json::from_str::<Counter>(raw).is_ok(),
case["counterValid"].as_bool().unwrap(),
"counter {raw}"
);
assert_eq!(
serde_json::from_str::<EventTime>(raw).is_ok(),
case["timestampValid"].as_bool().unwrap(),
"timestamp {raw}"
);
}
assert!(Counter::try_from(u64::MAX).is_err());
assert!(EventTime::try_from(i64::MAX).is_err());
assert!(EventTime::try_from(i64::MIN).is_err());
assert_eq!(
Counter::try_from(9_007_199_254_740_991).unwrap().get(),
9_007_199_254_740_991
);
assert_eq!(
EventTime::try_from(-9_007_199_254_740_991).unwrap().get(),
-9_007_199_254_740_991
);
}
#[test]
fn rounding_ties_positive_negative() {
for case in fixture(SCALARS)["rounding"].as_array().unwrap() {
annotate(case);
let exact = Decimal::from_str_exact(case["input"].as_str().unwrap()).unwrap();
assert_eq!(
Posting::from_exact_decimal(exact).unwrap().to_string(),
case["expected"].as_str().unwrap()
);
// External precision is rejected, not silently rounded like internal postings.
assert!(case["input"].as_str().unwrap().parse::<Posting>().is_err());
}
}
#[test]
fn overflow_rejected() {
let data = fixture(SCALARS);
let case = &data["overflow"];
annotate(case);
let max = posting(MAX_POSTING);
let quantum = posting(case["quantum"].as_str().unwrap());
assert_eq!(max.checked_add(quantum), Err(ScalarError::Overflow));
assert_eq!(
posting(&format!("-{MAX_POSTING}")).checked_sub(quantum),
Err(ScalarError::Overflow)
);
assert_eq!(
max.checked_sub(quantum)
.unwrap()
.checked_add(quantum)
.unwrap(),
max
);
assert_eq!(
Posting::from_exact_decimal(
Decimal::from_str_exact(case["roundingOverflow"].as_str().unwrap()).unwrap()
),
Err(ScalarError::Overflow)
);
assert_eq!(
Posting::from_exact_decimal(Decimal::MAX),
Err(ScalarError::Overflow)
);
assert_eq!(
Posting::from_exact_decimal(Decimal::MIN),
Err(ScalarError::Overflow)
);
assert_eq!(Posting::ZERO.to_string(), "0.00000000");
}
#[test]
fn basis_residual_spec() {
let data = fixture(LEDGER_SPECS);
let case = &data["basis"];
annotate(case);
assert_eq!(case["owningTask"], "F02");
// Check the independent hand calculation, not a replacement ledger simulator.
assert_eq!(
case["releases"],
serde_json::json!(["1.66666667", "1.66666667", "1.66666666"])
);
let midpoint = Decimal::from_str_exact("1.666666665").unwrap();
assert_eq!(
Posting::from_exact_decimal(midpoint).unwrap(),
posting("1.66666667")
);
let initial = posting(case["initialCost"].as_str().unwrap());
let mut remaining = initial;
let mut released = Posting::ZERO;
for (index, value) in case["releases"].as_array().unwrap().iter().enumerate() {
let amount = posting(value.as_str().unwrap());
remaining = remaining.checked_sub(amount).unwrap();
released = released.checked_add(amount).unwrap();
assert_eq!(
remaining.to_string(),
case["remainingCosts"][index].as_str().unwrap()
);
}
assert_eq!(released, initial);
assert_eq!(remaining, Posting::ZERO);
}
#[test]
fn command_id_conflict_spec() {
let data = fixture(LEDGER_SPECS);
let case = &data["commandIds"];
annotate(case);
assert_eq!(case["owningTask"], "F02");
let parse =
|name: &str| serde_json::from_value::<EngineFinancialCommand>(case[name].clone()).unwrap();
let original = parse("original");
let retry = parse("retry");
let conflict = parse("conflict");
let independent = parse("independent");
// Typed payload equality ignores JSON key order and accepted decimal padding.
assert_eq!(original, retry);
assert_eq!(
(
&original.session_id,
&original.account_id,
&original.command_id
),
(
&conflict.session_id,
&conflict.account_id,
&conflict.command_id
)
);
assert_ne!(original.body, conflict.body);
assert_ne!(original.session_id, independent.session_id);
assert_eq!(original.body, independent.body);
}
#[test]
fn strategy_cannot_parse_internal_financial_mutations() {
let contracts = fixture(CONTRACTS);
let command = &contracts["valid"][0]["input"];
assert!(serde_json::from_value::<StrategyDecision>(command.clone()).is_err());
assert!(serde_json::from_value::<EngineFinancialCommand>(
contracts["valid"][3]["input"].clone()
)
.is_err());
}

View file

@ -6,6 +6,7 @@ pub mod adapters;
pub mod orderbook;
pub mod risk;
pub mod positions;
pub mod financial;
#[cfg(not(test))]
pub mod api;
pub mod analytics;
@ -227,4 +228,4 @@ impl TradingCore {
pub fn get_time(&self) -> DateTime<Utc> {
self.time_provider.now()
}
}
}

View file

@ -0,0 +1,622 @@
import { createHash } from 'node:crypto';
import { z } from 'zod';
import {
parseInstrumentId,
type HistoricalBarV2,
type HistoricalDatasetInputV2,
type HistoricalDatasetMetadataV2,
type HistoricalDatasetV2,
} from '@stock-bot/types';
import { validateDataset } from './historical-dataset';
const text = z.string().min(1);
const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
const sequence = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const price = z.number().finite().positive();
const day = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.refine(value => {
const parsed = Date.parse(value);
return Number.isFinite(parsed) && new Date(parsed).toISOString().slice(0, 10) === value;
}, 'Invalid session date');
const hash = z
.string()
.length(64)
.regex(/^[a-f0-9]{64}$/);
const prices = {
open: price,
high: price,
low: price,
close: price,
volume: z.number().finite().nonnegative(),
};
const metadataSchema = z
.object({
calendars: z
.array(
z
.object({
id: text,
venue: text,
timeZone: text,
revision: text,
source: text,
startDate: day,
endDate: day,
sessions: z
.array(z.object({ date: day, open: instant, close: instant }).strict())
.min(1),
})
.strict()
)
.min(1),
series: z
.array(
z
.object({
id: text,
instrumentId: text,
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
calendarId: text,
venue: text,
source: z.object({ provider: text, revision: text }).strict(),
timestamp: z.enum(['session-date', 'interval-start', 'interval-end']),
availability: z.enum(['explicit', 'interval-end-assumption']),
adjustment: z.enum(['raw', 'provider-adjusted']),
})
.strict()
)
.min(1),
executionSeries: z.array(z.object({ instrumentId: text, seriesId: text }).strict()).min(1),
bounds: z.object({ warmupStart: instant, tradeStart: instant, tradeEnd: instant }).strict(),
universe: z
.object({
selection: z.enum(['point-in-time', 'current-constituents', 'unknown']),
asOf: instant.nullable(),
revision: text,
instrumentIds: z.array(text).min(1),
})
.strict(),
corporateActions: z
.array(
z
.object({
instrumentId: text,
status: z.enum(['unknown', 'action-free', 'known-actions']),
start: instant,
end: instant,
revision: text,
actions: z.array(
z
.object({
effectiveAt: instant,
kind: z.enum(['split', 'dividend', 'other']),
reference: text,
})
.strict()
),
})
.strict()
)
.min(1),
})
.strict();
const sourceBarSchema = z
.object({
seriesId: text,
timestamp: z.union([day, instant]),
availableAt: instant.optional(),
sourceSequence: sequence,
...prices,
vwap: price.nullable().optional(),
})
.strict();
const barSchema = z
.object({
seriesId: text,
instrumentId: text,
intervalStart: instant,
intervalEnd: instant,
eventTime: instant,
availableAt: instant,
sourceSequence: sequence,
...prices,
vwap: price.nullable(),
})
.strict();
const manifestSchema = metadataSchema
.extend({
version: z.literal(2),
hash,
normalizationRevision: z.literal('historical-normalization-v2'),
parentDatasetHash: hash.nullable(),
volumePolicy: z.literal('reported'),
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
intradayPolicy: z.literal('full-duration-session-contained'),
eligibility: z.enum(['eligible', 'exploratory', 'ineligible']),
limitations: z.array(text),
barCount: z.number().int().positive(),
})
.strict();
const durations = { '1m': 60_000, '5m': 300_000, '15m': 900_000, '1h': 3_600_000 };
const prepared = new WeakSet<object>();
const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
function unique(values: readonly string[], label: string): void {
if (new Set(values).size !== values.length) {
throw new Error(`Duplicate ${label}`);
}
}
function parseMetadata(input: unknown) {
const metadata = metadataSchema.parse(input);
const { bounds, universe } = metadata;
if (bounds.warmupStart > bounds.tradeStart || bounds.tradeStart >= bounds.tradeEnd) {
throw new Error('Invalid warmup/trade bounds');
}
unique(
metadata.calendars.map(c => c.id),
'calendar'
);
metadata.calendars.sort((a, b) => compare(a.id, b.id));
for (const calendar of metadata.calendars) {
if (calendar.startDate >= calendar.endDate) {
throw new Error('Invalid calendar coverage');
}
const formatter = new Intl.DateTimeFormat('en-CA', {
timeZone: calendar.timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
const localDate = (time: number) => {
const parts = formatter.formatToParts(time);
return ['year', 'month', 'day']
.map(key => parts.find(part => part.type === key)?.value ?? '')
.join('-');
};
if (
localDate(bounds.warmupStart) < calendar.startDate ||
localDate(bounds.tradeEnd - 1) >= calendar.endDate
) {
throw new Error('Calendar coverage must include warmup and trade bounds');
}
unique(
calendar.sessions.map(s => s.date),
'calendar session'
);
calendar.sessions.sort((a, b) => compare(a.date, b.date));
let previousClose = -1;
for (const session of calendar.sessions) {
if (
session.date < calendar.startDate ||
session.date >= calendar.endDate ||
session.open >= session.close ||
session.open < previousClose ||
localDate(session.open) !== session.date ||
localDate(session.close) !== session.date
) {
throw new Error('Invalid retained calendar session');
}
previousClose = session.close;
}
}
unique(
metadata.series.map(s => s.id),
'series'
);
metadata.series.sort((a, b) => compare(a.id, b.id));
for (const series of metadata.series) {
parseInstrumentId(series.instrumentId);
const calendar = metadata.calendars.find(c => c.id === series.calendarId);
if (
!calendar ||
calendar.venue !== series.venue ||
(series.interval === '1d') !== (series.timestamp === 'session-date')
) {
throw new Error('Unknown calendar/venue or incompatible timestamp mapping');
}
}
const instruments = [...new Set(metadata.series.map(s => s.instrumentId))].sort(compare);
unique(
metadata.executionSeries.map(s => s.instrumentId),
'execution instrument'
);
unique(
metadata.executionSeries.map(s => s.seriesId),
'execution series'
);
metadata.executionSeries.sort((a, b) => compare(a.instrumentId, b.instrumentId));
if (
JSON.stringify(metadata.executionSeries.map(s => s.instrumentId)) !==
JSON.stringify(instruments) ||
metadata.executionSeries.some(
e => !metadata.series.some(s => s.id === e.seriesId && s.instrumentId === e.instrumentId)
)
) {
throw new Error('Choose exactly one execution series per instrument');
}
unique(universe.instrumentIds, 'universe instrument');
universe.instrumentIds.sort(compare);
if (
JSON.stringify(universe.instrumentIds) !== JSON.stringify(instruments) ||
(universe.selection === 'point-in-time' &&
(universe.asOf === null || universe.asOf > bounds.tradeStart))
) {
throw new Error('Invalid universe/as-of selection');
}
unique(
metadata.corporateActions.map(c => c.instrumentId),
'action coverage'
);
metadata.corporateActions.sort((a, b) => compare(a.instrumentId, b.instrumentId));
if (
JSON.stringify(metadata.corporateActions.map(c => c.instrumentId)) !==
JSON.stringify(instruments)
) {
throw new Error('Corporate-action coverage required for every instrument');
}
for (const coverage of metadata.corporateActions) {
if (
coverage.start > bounds.warmupStart ||
coverage.end < bounds.tradeEnd ||
coverage.start >= coverage.end ||
(coverage.status === 'known-actions') !== coverage.actions.length > 0 ||
coverage.actions.some(a => a.effectiveAt < coverage.start || a.effectiveAt >= coverage.end)
) {
throw new Error('Invalid corporate-action coverage');
}
unique(
coverage.actions.map(a => a.reference),
'corporate-action reference'
);
coverage.actions.sort(
(a, b) => a.effectiveAt - b.effectiveAt || compare(a.reference, b.reference)
);
}
return metadata;
}
function assess(metadata: HistoricalDatasetMetadataV2, parentDatasetHash: string | null) {
const limitations = [
'Open liquidity must use previously available volume; intraday partial bars are unsupported',
];
let eligibility: 'eligible' | 'exploratory' | 'ineligible' = 'eligible';
if (parentDatasetHash) {
limitations.push('Legacy v1 VWAP provenance is unavailable; converted VWAP is null');
}
if (metadata.universe.selection !== 'point-in-time') {
eligibility = 'exploratory';
limitations.push('Universe selection is not verified point-in-time');
}
for (const coverage of metadata.corporateActions) {
if (coverage.status === 'unknown') {
if (eligibility !== 'ineligible') {
eligibility = 'exploratory';
}
limitations.push(`Unknown corporate-action coverage: ${coverage.instrumentId}`);
}
if (
coverage.actions.some(
a =>
a.effectiveAt >= metadata.bounds.warmupStart && a.effectiveAt < metadata.bounds.tradeEnd
)
) {
eligibility = 'ineligible';
limitations.push(`Unsupported corporate actions in dataset range: ${coverage.instrumentId}`);
}
}
for (const selection of metadata.executionSeries) {
if (metadata.series.find(s => s.id === selection.seriesId)?.adjustment !== 'raw') {
eligibility = 'ineligible';
limitations.push(`Adjusted prices cannot execute: ${selection.seriesId}`);
}
}
for (const series of metadata.series) {
if (series.availability === 'interval-end-assumption') {
limitations.push(`Availability assumes zero data delay at interval end: ${series.id}`);
}
}
return { eligibility, limitations };
}
/** Per-preparation indexes, not a cross-dataset cache. Session lookup is logarithmic. */
function indexMetadata(metadata: HistoricalDatasetMetadataV2) {
return {
series: new Map(metadata.series.map(series => [series.id, series])),
calendars: new Map(
metadata.calendars.map(calendar => [
calendar.id,
{
...calendar,
byDate: new Map(calendar.sessions.map(session => [session.date, session])),
},
])
),
};
}
function containingSession(
sessions: HistoricalDatasetMetadataV2['calendars'][number]['sessions'],
start: number,
end: number
) {
let low = 0,
high = sessions.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if ((sessions[middle]?.open ?? Infinity) <= start) {
low = middle + 1;
} else {
high = middle;
}
}
const session = sessions[low - 1];
return session && end <= session.close ? session : undefined;
}
function validateBars(
metadata: HistoricalDatasetMetadataV2,
input: readonly unknown[]
): HistoricalBarV2[] {
if (!input.length) {
throw new Error('Dataset requires bars');
}
const index = indexMetadata(metadata);
const intervals = new Set<string>(),
sequences = new Set<string>(),
seen = new Set<string>();
const bars = input.map(value => {
const bar = barSchema.parse(value);
const series = index.series.get(bar.seriesId);
const calendar = series && index.calendars.get(series.calendarId);
const session =
calendar && containingSession(calendar.sessions, bar.intervalStart, bar.intervalEnd);
const duration = series?.interval === '1d' ? null : series ? durations[series.interval] : null;
if (
!series ||
bar.instrumentId !== series.instrumentId ||
!session ||
bar.intervalStart >= bar.intervalEnd ||
(duration === null
? bar.intervalStart !== session.open || bar.intervalEnd !== session.close
: bar.intervalEnd - bar.intervalStart !== duration) ||
bar.eventTime !== bar.intervalEnd ||
bar.availableAt < bar.eventTime ||
(series.availability === 'interval-end-assumption' && bar.availableAt !== bar.intervalEnd) ||
bar.intervalStart < metadata.bounds.warmupStart ||
bar.intervalStart >= metadata.bounds.tradeEnd ||
bar.intervalEnd > metadata.bounds.tradeEnd ||
bar.high < Math.max(bar.open, bar.close) ||
bar.low > Math.min(bar.open, bar.close)
) {
throw new Error('Invalid bar values, session interval or availability');
}
const intervalKey = JSON.stringify([bar.seriesId, bar.intervalStart, bar.intervalEnd]);
const sequenceKey = JSON.stringify([bar.seriesId, bar.sourceSequence]);
if (intervals.has(intervalKey) || sequences.has(sequenceKey)) {
throw new Error('Duplicate or conflicting bar interval/source sequence');
}
intervals.add(intervalKey);
sequences.add(sequenceKey);
seen.add(bar.seriesId);
return bar;
});
if (seen.size !== metadata.series.length) {
throw new Error('Every declared series requires observations');
}
let previous: HistoricalBarV2 | undefined;
for (const bar of [...bars].sort(
(a, b) => compare(a.seriesId, b.seriesId) || a.intervalStart - b.intervalStart
)) {
if (previous?.seriesId === bar.seriesId && bar.intervalStart < previous.intervalEnd) {
throw new Error('Overlapping intervals within one series');
}
previous = bar;
}
bars.sort(
(a, b) =>
a.availableAt - b.availableAt ||
compare(a.instrumentId, b.instrumentId) ||
compare(a.seriesId, b.seriesId) ||
a.sourceSequence - b.sourceSequence
);
return bars;
}
function freeze<T>(value: T): T {
if (value && typeof value === 'object') {
for (const child of Object.values(value)) {
freeze(child);
}
Object.freeze(value);
}
return value;
}
function finish(
metadata: ReturnType<typeof parseMetadata>,
bars: HistoricalBarV2[],
parentDatasetHash: string | null
): HistoricalDatasetV2 {
const manifest = {
...metadata,
version: 2 as const,
normalizationRevision: 'historical-normalization-v2' as const,
parentDatasetHash,
volumePolicy: 'reported' as const,
qualityPolicy: 'reject-invalid-no-interpolation' as const,
intradayPolicy: 'full-duration-session-contained' as const,
...assess(metadata, parentDatasetHash),
barCount: bars.length,
};
const digest = createHash('sha256').update(`{"manifest":${JSON.stringify(manifest)},"bars":[`);
bars.forEach((bar, index) => digest.update((index ? ',' : '') + JSON.stringify(bar)));
const dataset = freeze({
manifest: { ...manifest, hash: digest.update(']}').digest('hex') },
bars,
});
prepared.add(dataset);
return dataset;
}
function create(input: unknown, parentDatasetHash: string | null): HistoricalDatasetV2 {
const parsed = z
.object({ metadata: metadataSchema, bars: z.array(sourceBarSchema).min(1) })
.strict()
.parse(input);
const metadata = parseMetadata(parsed.metadata);
const index = indexMetadata(metadata);
const bars = parsed.bars.map(row => {
const series = index.series.get(row.seriesId);
const calendar = series && index.calendars.get(series.calendarId);
if (!series || !calendar) {
throw new Error('Unknown series/calendar mapping');
}
if (series.availability === 'explicit' && row.availableAt === undefined) {
throw new Error('Explicit availability policy requires availableAt on every bar');
}
let intervalStart: number, intervalEnd: number;
if (series.interval === '1d') {
const session = typeof row.timestamp === 'string' && calendar.byDate.get(row.timestamp);
if (!session) {
throw new Error('Unknown daily session mapping');
}
intervalStart = session.open;
intervalEnd = session.close;
} else {
if (typeof row.timestamp !== 'number') {
throw new Error('Intraday timestamp requires an explicit instant');
}
const duration = durations[series.interval];
intervalStart =
series.timestamp === 'interval-start' ? row.timestamp : row.timestamp - duration;
intervalEnd = intervalStart + duration;
}
return {
seriesId: series.id,
instrumentId: series.instrumentId,
intervalStart,
intervalEnd,
eventTime: intervalEnd,
availableAt: row.availableAt ?? intervalEnd,
sourceSequence: row.sourceSequence,
open: row.open,
high: row.high,
low: row.low,
close: row.close,
volume: row.volume,
vwap: row.vwap ?? null,
};
});
return finish(metadata, validateBars(metadata, bars), parentDatasetHash);
}
/** No storage/provider access or implicit v1 cutover. Tables and timestamp semantics are mandatory. */
export function createDatasetV2(input: HistoricalDatasetInputV2): HistoricalDatasetV2 {
return create(input, null);
}
/** Recompute constraints, eligibility and hash; untrusted values are detached before freezing. */
export function validateDatasetV2(input: unknown): HistoricalDatasetV2 {
if (input && typeof input === 'object' && prepared.has(input)) {
return input as HistoricalDatasetV2;
}
const parsed = z
.object({ manifest: manifestSchema, bars: z.array(barSchema).min(1) })
.strict()
.parse(input);
const {
version: _version,
hash: expectedHash,
normalizationRevision: _revision,
parentDatasetHash,
volumePolicy: _volume,
qualityPolicy: _quality,
intradayPolicy: _intraday,
eligibility,
limitations,
barCount,
...rawMetadata
} = parsed.manifest;
const metadata = parseMetadata(rawMetadata);
const dataset = finish(metadata, validateBars(metadata, parsed.bars), parentDatasetHash);
if (
dataset.manifest.hash !== expectedHash ||
barCount !== dataset.bars.length ||
eligibility !== dataset.manifest.eligibility ||
JSON.stringify(limitations) !== JSON.stringify(dataset.manifest.limitations) ||
(parentDatasetHash !== null && dataset.bars.some(bar => bar.vwap !== null))
) {
throw new Error('Dataset v2 hash/content or derived policy mismatch');
}
return dataset;
}
/** Unknown coverage remains exploratory; this assertion does not certify economic correctness. */
export function assertDatasetV2Executable(input: unknown): HistoricalDatasetV2 {
const dataset = validateDatasetV2(input);
if (dataset.manifest.eligibility === 'ineligible') {
throw new Error(`Dataset is not executable: ${dataset.manifest.limitations.join('; ')}`);
}
return dataset;
}
/** Explicit conversion keeps the original v1 hash and treats all legacy VWAP as unknown. */
export function convertDatasetV1ToV2(
input: unknown,
metadata: HistoricalDatasetMetadataV2
): HistoricalDatasetV2 {
const legacy = validateDataset(input);
const normalized = parseMetadata(metadata);
if (
normalized.series.length !== legacy.manifest.instruments.length ||
normalized.series.some(
series =>
series.interval !== legacy.manifest.interval ||
series.adjustment !== legacy.manifest.policy.adjustment ||
series.availability !== 'interval-end-assumption' ||
!legacy.manifest.sources.some(
source =>
source.instrumentId === series.instrumentId &&
source.provider === series.source.provider &&
source.revision === series.source.revision
)
)
) {
throw new Error(
'V1 conversion requires one matching source/interval/adjustment series per instrument'
);
}
if (
JSON.stringify(normalized.executionSeries.map(s => s.instrumentId)) !==
JSON.stringify(legacy.manifest.instruments.map(i => i.id))
) {
throw new Error('V1 conversion must retain every instrument');
}
const sequences = new Map<string, number>();
const bars = legacy.bars.map(bar => {
const series = normalized.series.find(s => s.instrumentId === bar.symbol);
if (!series) {
throw new Error('V1 conversion is missing an instrument mapping');
}
const sourceSequence = sequences.get(series.id) ?? 0;
sequences.set(series.id, sourceSequence + 1);
return {
seriesId: series.id,
timestamp:
series.interval === '1d'
? new Date(bar.timestamp).toISOString().slice(0, 10)
: bar.timestamp,
sourceSequence,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: null,
};
});
return create({ metadata: normalized, bars }, legacy.manifest.hash);
}

View file

@ -1,8 +1,8 @@
# Revised development roadmap
Baseline `b7aeca4` · reviewed 2026-10-22 · **First five waves committed; next implementation policy-gated; see manifest execution_scope**
Baseline `b7aeca4` · reviewed 2026-10-22 · **First five waves committed; ADR-002/003/004 approved; F01/D01 validated, uncommitted**
Authorization update: the first five waves are independently reviewed, validated and committed. The latest “commit and continue” authorized the W04 implementation and planning closeout commits. Continuation readiness was checked: no remaining scheduled task has both code and architecture-policy prerequisites satisfied. Explicit approval is requested for ADR-002/003/004 before F01 and D01; no policy approval is inferred from a generic continuation request. Pushes, PRs and trading operations remain outside scope.
Authorization update: the first five waves are independently reviewed, validated and committed. After the W04 closeout, the owner explicitly answered “yes” to ADR-002/003/004 as written and continuation with F01/D01. Those two tasks were independently reviewed and integrated from isolated worktrees; combined gates passed. They remain `review` / `validated_uncommitted` pending owner acceptance/commit. No other ADR is approved. Sixth-wave commits, pushes, PRs and trading operations remain outside scope.
## Strategy and review outcome
@ -17,15 +17,15 @@ The existing web workbench improves during engine migration. Legacy results rema
| Decision | Direction | Approval |
| --- | --- | --- |
| [ADR-001](architecture/decisions/001-ownership.md) | TS product/strategy code; Rust financial authority; retain monolith and workers | User-mandated |
| [ADR-002](architecture/decisions/002-financial-policy.md) | Maintained checked decimal; 8-place half-up postings; authoritative remaining cost; owner books from day one; initial cash-funded long-only account | Explicit economic approval |
| [ADR-003](architecture/decisions/003-time-and-datasets.md) | Availability/event phases; open-only next-interval matching; explicit zero-latency convention; mark-open terminal policy; account risk-session clock | Explicit execution/data approval |
| [ADR-004](architecture/decisions/004-strategy-boundary.md) | NAPI pull sessions in existing workers; tagged decision barriers; IPC for untrusted code; no embedded JS | Plan approval |
| [ADR-002](architecture/decisions/002-financial-policy.md) | Maintained checked decimal; 8-place half-up postings; authoritative remaining cost; owner books from day one; initial cash-funded long-only account | Approved by owner, 2026-10-22 |
| [ADR-003](architecture/decisions/003-time-and-datasets.md) | Availability/event phases; open-only next-interval matching; explicit zero-latency convention; mark-open terminal policy; account risk-session clock | Approved by owner, 2026-10-22 |
| [ADR-004](architecture/decisions/004-strategy-boundary.md) | NAPI pull sessions in existing workers; tagged decision barriers; IPC for untrusted code; no embedded JS | Approved by owner, 2026-10-22 |
| [ADR-005](architecture/decisions/005-durable-cutover.md) | One Rust transition kernel; resident research state; private staged paper state under existing SQL transactions | Plan approval |
| [ADR-006](architecture/decisions/006-research-product.md) | Existing API/queue/database; immutable versions, provenance and evidence retention; no laboratory framework | Plan approval |
| [ADR-007](architecture/decisions/007-ai-boundary.md) | Isolated untrusted code, research-only permissions/budgets; human-only paper promotion; live disabled | Explicit trust-model approval |
| [ADR-008](architecture/decisions/008-performance.md) | Measure actual paths; cursor replay and bounded trials; caching/DSL only when measured | Plan approval; later optimization go/no-go |
Long-only is a proposed first canonical model, not deletion of short history or a silent change to current paper accounts. If first-release shorts are required, approve borrowing/margin policy and fixtures before F01. C01/C03/C04/W01 do not depend on those unresolved economic choices.
Long-only is the approved first canonical model, not deletion of short history or a silent change to current paper accounts. Short/margin support still needs a separate approved borrowing policy and fixtures. C01/C03/C04/W01 preserve the legacy behavior described in their task scopes.
## Milestones
@ -81,7 +81,7 @@ Completed wave; the table records its original rationale. Exact prompts, paths,
Recommend **3 simultaneous implementers**, reserving one slot for coordination/independent review. Start C01 + C03 + W01; rotate C04 into the first freed slot, or start C04 first if runtime containment is the immediate operational need. These four have no mutual code dependencies and disjoint writable files. Four concurrent implementers are technically possible but not recommended without separate review capacity.
O01/P01, W03 and W04 are committed. W04 adds validated real-browser end-to-end verification of the existing workbench. F01/D01 still require their ADR approvals; no subsequent implementation starts before its prerequisites are satisfied.
O01/P01, W03 and W04 are committed. W04 adds validated real-browser end-to-end verification of the existing workbench. F01/D01 now have explicit ADR approval and passed integrated validation; subsequent tasks remain prerequisite-gated pending acceptance/commit.
## Second-wave handoff — 2026-10-22
@ -167,7 +167,26 @@ Logs, five reviewed file hashes and native artifact identities are recorded in t
Limits: Chromium only (138.0.7204.23). A standalone probe reproduced a Bun 1.2.17 server-initiated websocket close/reconnect shutdown hang; final coverage uses an actual client-initiated disconnect and does not suppress server cleanup failures or claim server-initiated shutdown coverage. An author-reported first clean-worktree build had a browser/logger type-resolution ordering failure; a retry and the combined check passed, but no fix or reproducible diagnosis is claimed. Existing build warnings remain. UI fixtures and native smoke do not certify same-bar execution, canonical accounting, ownership or funding semantics.
Next: approve ADR-002/003/004 before F01, ADR-003 before D01, and ADR-006 before the parallel R01 product lane. The post-commit readiness review found 32 remaining scheduled tasks and no ungated candidate. F01, D01 and R01 have satisfied code prerequisites but pending ADRs; optimization/deferred work is not a substitute. Do not start financial or trust-model changes by interpreting this test completion or the continuation request as policy approval.
At the fifth-wave closeout, the readiness review found 32 remaining scheduled tasks and no ungated candidate. The owner subsequently explicitly approved ADR-002/003/004, unblocking F01/D01; that approval is separate from test completion or the earlier generic continuation request. R01 still requires ADR-006. Optimization/deferred work is not a substitute for prerequisite completion.
## Sixth-wave handoff — 2026-10-22
F01 and D01 are independently accepted and `review` / `validated_uncommitted`. Base `243e9ab`; isolated worktrees under `/tmp/stock-bot-wave6.uIuYHz/`. Financial and dataset owners implemented in parallel, with an independent read-only reviewer; the integrator merged their common types exports.
- **F01:** Pinned maintained decimal dependency; checked exact decimal ingress, fixed-8 half-away posting, bounded arithmetic, versioned Rust/TypeScript contracts, owner/decision identities and hand-derived economic fixtures. Strategy intents cannot parse as internal financial mutations. Safe integer, Unicode, strict decimal, overflow and wire-roundtrip regressions pass. The snapshot is only an economic projection. F02 still owns actual ledger/dedup transitions and operation-specific proportional basis arithmetic; generic multiply/divide was deliberately not introduced.
- **D01:** Additive v2 normalizer retains interval/event/availability time, source sequence, explicit versioned calendars, execution-series selection, universe/action coverage and limitations. Hash-verified v1 conversion retains its parent hash and makes unverifiable legacy VWAP unknown. DST/half-days, delayed availability, conflicts, overlapping intervals, parent-hash syntax and prefix stability are tested. Unsupported action/adjusted execution data rejects; unknown coverage remains exploratory. Initial intraday support requires full-duration session-contained bars.
Combined validation passed:
- `CARGO_BUILD_JOBS=2 bun run check`: 60 tooling, 43 utility, 35 calculation, 334 integration and 44 Rust tests, zero failures. Build, typecheck, contracts, lint and secret audit passed. The initial sandbox attempt failed native spawning/worker checks; the escalated full rerun passed.
- Final focused rerun after formatting two JSON fixtures: 35 TypeScript tests / 601 assertions and 44 Rust tests, zero failures. Parsed fixture values match the independently reviewed source exactly.
- Standalone strict TypeScript, explicit scoped ESLint, scoped Prettier and `git diff --check` passed. Reviewed hashes match except the deliberate shared-export merge and documented formatting-only differences. Full hashes, logs and independently rebuilt addon identities are in the manifest.
No PostgreSQL/Redis or Chromium rerun was needed for these additive, unused contracts: SQL, APIs, UI and current execution paths did not change. No throughput certification is claimed. Existing build warnings remain; isolated clean builds needed existing dependency builds/retries, without a build-system fix.
Only the verified stalled sandbox test processes were stopped after the successful rerun. No user services or data were removed; worktrees and logs remain available.
Existing v1 snapshots and financial runtimes remain unchanged. F01 is not a working canonical ledger; D01 prefix tests are not F06 replay enforcement. No paper account conversion, extra backlog task, commit, push, PR or trading operation occurred. After acceptance/commit, the next coherent pair is **F02 owner-aware Rust ledger + D02 intraday storage integration**, with one financial owner and disjoint data ownership.
## Deferred and rejected

View file

@ -1,6 +1,6 @@
# ADR-002 — Money, cost basis, ownership and funding
Status: **owner approval required**. This revision replaces the unimplemented half-even/rounded-average proposal; it does not alter current code.
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). This revision replaces the unimplemented half-even/rounded-average proposal; approval does not itself alter legacy code or accounts.
## Selected minimal policy

View file

@ -1,6 +1,6 @@
# ADR-003 — Information availability and execution timing
Status: **owner approval required**.
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). Versioned implementation remains task-gated; legacy snapshots/results are preserved.
## Selected policy

View file

@ -1,6 +1,6 @@
# ADR-004 — One pull-session boundary, not two strategy frameworks
Status: proposed for approval.
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). Session execution is implemented by F07/S01, not by approving this contract direction.
## Selected approach

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**First five waves committed; further implementation awaits architecture-policy approval.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). Other tasks and unresolved policies remain gated.
**First five waves committed; ADR-002/003/004 approved; F01/D01 validated, uncommitted.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). F01/D01 await owner acceptance/commit; other tasks and unresolved policies remain gated.
## One source of truth
@ -29,7 +29,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [F01 Define the minimal financial contract and economic fixtures](tasks/F01.md) | P0 / blocked | ADR-002, ADR-003, ADR-004 | — | Rust financial contract owner / M |
| [F01 Define the minimal financial contract and economic fixtures](tasks/F01.md) | P0 / review | ADR-002, ADR-003, ADR-004 (approved) | — | Rust financial contract owner / M |
| [F02 Implement one owner-aware financial ledger](tasks/F02.md) | P0 / blocked | F01, ADR-002 | — | Rust accounting / L |
| [F03 Add strategy-owned position books and fill allocations](tasks/F03.md) | P0 / merged → F02 | None | — | Rust portfolio accounting / M |
| [F04 Enforce cash reservations and portfolio risk centrally](tasks/F04.md) | P0 / blocked | F02, ADR-002, ADR-003 | — | Rust financial risk / L |
@ -42,7 +42,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [D01 Introduce availability-aware dataset v2](tasks/D01.md) | P0 / blocked | ADR-003 | — | TypeScript trading infrastructure / M |
| [D01 Introduce availability-aware dataset v2](tasks/D01.md) | P0 / review | ADR-003 (approved) | — | TypeScript trading infrastructure / M |
| [D02 Connect supported intraday storage to research datasets](tasks/D02.md) | P1 / blocked | D01 | — | TypeScript trading infrastructure / M |
| [D03 Add dataset eligibility and corporate-action safeguards](tasks/D03.md) | P1 / merged → D01 | None | — | TypeScript trading infrastructure / M |
| [D04 Provide prefix-safe shared feature calculation](tasks/D04.md) | P1 / deferred | S01, P01 | — | Quantitative feature engineering / M |
@ -115,4 +115,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
The first five waves are independently reviewed, validated and committed with owner approval. **W04** is committed as `550d8b7`; its five implementation/dependency hashes still match the reviewed and tested versions. Evidence is recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22), the [ROADMAP handoffs](../ROADMAP.md#fifth-wave-handoff--2026-10-22) and the manifest. The latest continuation request cannot satisfy unresolved policy choices: F01 needs ADR-002/003/004, D01 needs ADR-003, and R01 needs ADR-006. These are the only remaining scheduled tasks with satisfied code prerequisites; none is approval-ready yet. Deferred work remains deferred.
The first five waves are independently reviewed, validated and committed with owner approval. **W04** is committed as `550d8b7`. Evidence is recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22), the [ROADMAP handoffs](../ROADMAP.md#fifth-wave-handoff--2026-10-22) and the manifest. The owner's subsequent explicit approval of ADR-002/003/004 authorizes **F01 + D01** in parallel. R01 still needs ADR-006; other consumers wait for their dependencies. Deferred work remains deferred. No sixth-wave commit/push/PR or trading operation is authorized.

View file

@ -1,37 +1,34 @@
{
"schema_version": 1,
"plan_revision": "2026-10-22.14",
"plan_revision": "2026-10-22.16",
"repository_base": "b7aeca4",
"plan_status": "fifth_wave_committed_awaiting_policy_approval",
"plan_status": "sixth_wave_validated_uncommitted",
"execution_authorized": true,
"execution_scope": {
"authorized_by": "User: commit and continue (2026-10-22); commit validated W03 and continue next-ready W04",
"authorized_by": "User: yes (2026-10-22), explicitly approving ADR-002/003/004 as written and continuation with F01/D01",
"tasks": [
"W04"
"F01",
"D01"
],
"permissions": [
"isolated_implementation",
"local_tests",
"local_integration_review",
"planning_progress_updates",
"fifth_wave_implementation_commit",
"planning_closeout_commit"
"planning_progress_updates"
],
"excluded": [
"sixth_wave_commits_without_further_approval",
"push",
"pull_requests",
"live_or_paper_operations",
"other_backlog_tasks"
],
"pending_policy_decisions": [
"ADR-002",
"ADR-003",
"ADR-004",
"ADR-005",
"ADR-006",
"ADR-007"
],
"commit_authorized_by": "User: commit and continue (2026-10-22), after W04 validated handoff",
"continuation": "Requested; no remaining scheduled task has satisfied code AND ADR prerequisites. Explicit ADR-002/003/004 approval requested before F01/D01. No policy decision or deferred activation inferred."
"ADR-007",
"ADR-008"
]
},
"canonical_metadata": "This manifest alone owns task status, dependency edges, approvals, assignments and write locks. Task Markdown owns scope and acceptance criteria. Index/roadmap are derived views.",
"decisions": [
@ -43,17 +40,23 @@
{
"id": "ADR-002",
"file": "architecture/decisions/002-financial-policy.md",
"status": "approval_required"
"status": "approved",
"approved_by": "Owner explicit yes to ADR-002/003/004 as written",
"approved_on": "2026-10-22"
},
{
"id": "ADR-003",
"file": "architecture/decisions/003-time-and-datasets.md",
"status": "approval_required"
"status": "approved",
"approved_by": "Owner explicit yes to ADR-002/003/004 as written",
"approved_on": "2026-10-22"
},
{
"id": "ADR-004",
"file": "architecture/decisions/004-strategy-boundary.md",
"status": "proposed_for_plan_approval"
"status": "approved",
"approved_by": "Owner explicit yes to ADR-002/003/004 as written",
"approved_on": "2026-10-22"
},
{
"id": "ADR-005",
@ -316,7 +319,7 @@
"epic": "E2",
"priority": "P0",
"severity": "Critical",
"status": "blocked",
"status": "review",
"dependencies": [],
"decision_dependencies": [
"ADR-002",
@ -335,12 +338,28 @@
"financial-contract"
],
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
"assignment": null,
"branch": null,
"assignment": "/root/wave6_f01",
"branch": "wave6/f01-financial-contract",
"pull_request": null,
"completed_commit": null,
"blocker": null,
"release_gates": []
"release_gates": [],
"worktree": "/tmp/stock-bot-wave6.uIuYHz/f01",
"integration_base": "243e9ab43f82a4b467fb90d2bd35c9ada8af41e4",
"concrete_write_scope": [
"apps/stock/engine/src/financial/",
"apps/stock/engine/src/lib.rs",
"apps/stock/engine/Cargo.toml",
"Cargo.lock",
"libs/core/types/src/financial-engine.ts",
"libs/core/types/src/index.ts",
"test/fixtures/economics/",
"test/integration/financial-contract.test.ts"
],
"integration_state": "validated_uncommitted",
"reviewed_by": "/root/wave6_review",
"verification_reference": "ROADMAP.md#sixth-wave-handoff--2026-10-22",
"review_notes": "Independently accepted, integrated, and combined gates passed. No commit authorized in this wave; awaiting owner acceptance/commit before scheduling dependents."
},
{
"id": "F02",
@ -576,7 +595,7 @@
"epic": "E3",
"priority": "P0",
"severity": "Critical",
"status": "blocked",
"status": "review",
"dependencies": [],
"decision_dependencies": [
"ADR-003"
@ -593,12 +612,26 @@
"dataset-contract"
],
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
"assignment": null,
"branch": null,
"assignment": "/root/wave6_d01",
"branch": "wave6/d01-dataset-v2",
"pull_request": null,
"completed_commit": null,
"blocker": null,
"release_gates": []
"release_gates": [],
"worktree": "/tmp/stock-bot-wave6.uIuYHz/d01",
"integration_base": "243e9ab43f82a4b467fb90d2bd35c9ada8af41e4",
"concrete_write_scope": [
"libs/core/types/src/historical-data.ts",
"apps/stock/orchestrator/src/data/historical-dataset-v2.ts",
"apps/stock/orchestrator/src/data/historical-dataset.ts",
"apps/stock/orchestrator/src/contracts/historical.ts",
"test/integration/historical-dataset-v2.test.ts",
"test/fixtures/historical-v2/"
],
"integration_state": "validated_uncommitted",
"reviewed_by": "/root/wave6_review",
"verification_reference": "ROADMAP.md#sixth-wave-handoff--2026-10-22",
"review_notes": "Independently accepted, integrated, and combined gates passed. No commit authorized in this wave; awaiting owner acceptance/commit before scheduling dependents."
},
{
"id": "D02",
@ -1865,7 +1898,7 @@
}
],
"review_note": "Independent skeptical revision: four superseded tasks retain stable IDs; deferred work is not a dependency of scheduled tasks. Release gates are distinct from implementation prerequisites.",
"integration_base": "95842c39d0b26dccd594279f3a632e9afe20186f",
"integration_base": "243e9ab43f82a4b467fb90d2bd35c9ada8af41e4",
"validation": {
"date": "2026-10-22",
"integration_base": "1148673",
@ -2006,6 +2039,38 @@
],
"commit_authorized_by": "User: commit and start the next wave (2026-10-22)"
}
},
{
"wave": "fifth_wave",
"scope": {
"authorized_by": "User: commit and continue (2026-10-22); commit validated W03 and continue next-ready W04",
"tasks": [
"W04"
],
"permissions": [
"isolated_implementation",
"local_tests",
"local_integration_review",
"planning_progress_updates",
"fifth_wave_implementation_commit",
"planning_closeout_commit"
],
"excluded": [
"push",
"pull_requests",
"live_or_paper_operations",
"other_backlog_tasks"
],
"pending_policy_decisions": [
"ADR-002",
"ADR-003",
"ADR-004",
"ADR-006",
"ADR-007"
],
"commit_authorized_by": "User: commit and continue (2026-10-22), after W04 validated handoff",
"continuation": "Requested; no remaining scheduled task has satisfied code AND ADR prerequisites. Explicit ADR-002/003/004 approval requested before F01/D01. No policy decision or deferred activation inferred."
}
}
],
"second_wave": [
@ -2602,6 +2667,7 @@
]
},
"continuation_readiness": {
"historical_note": "This was the fifth-wave closeout readiness check. Superseded by the owner's subsequent explicit approval of ADR-002/003/004 and the sixth-wave F01/D01 execution scope above.",
"date": "2026-10-22",
"after_commit": "550d8b769baae13f60dd22490a4e3ab42abd008b",
"remaining_scheduled_tasks": 32,
@ -2630,5 +2696,95 @@
],
"requested_approval": "ADR-002/003/004 as written before F01 financial contracts/regression fixtures and D01 availability-aware datasets; awaiting explicit owner response",
"notes": "Deferred optimization triggers remain unmet; no alternative task started. Readiness checked independently by /root/next_ready_audit."
},
"sixth_wave": [
"F01",
"D01"
],
"sixth_wave_notes": [
"Owner explicitly approved ADR-002/003/004. No other ADR approved.",
"F01 owns financial contract, Rust dependency/lockfile, types index export and economic fixtures. D01 owns dataset contracts and additive v2 normalizer/fixtures; root integrates D01 type exports to avoid index overlap.",
"Existing financial runtimes and v1 dataset hash/load semantics remain unchanged. No F02 ledger, F06 replay, F07 NAPI sessions, paper cutover or new endpoint is included.",
"Implementation in isolated worktrees; independent review and combined integration gates passed; awaiting owner acceptance/commit."
],
"sixth_wave_validation": {
"result": "passed",
"reviewer": "/root/wave6_review",
"base": "243e9ab43f82a4b467fb90d2bd35c9ada8af41e4",
"repository_check": {
"command": "CARGO_BUILD_JOBS=2 bun run check",
"log": "/tmp/stock-bot-wave6.uIuYHz/check-escalated.log",
"tooling_tests": 60,
"utility_tests": 43,
"calculation_tests": 35,
"integration_tests": 334,
"rust_tests": 44,
"failed": 0,
"note": "Initial sandbox attempt hit native spawn EPERM and worker timeouts; escalated full rerun passed. Full build/typecheck/contracts/lint/secret audit passed."
},
"final_focused": {
"command": "bun test test/integration/financial-contract.test.ts test/integration/historical-dataset-v2.test.ts test/integration/dataset-preparation.test.ts",
"tests": 35,
"assertions": 601,
"failed": 0,
"log": "/tmp/stock-bot-wave6.uIuYHz/focused-final.log",
"rust_recheck": "cargo test -p engine --lib --offline: 44 passed after JSON formatting; /tmp/stock-bot-wave6.uIuYHz/rust-final.log"
},
"author_and_independent_review": {
"financial": "9 TypeScript tests/456 assertions and 44 Rust tests independently passed.",
"dataset": "15 v2 tests/95 assertions independently passed; main-workspace legacy+v2 dataset tests:26/145.",
"native_smoke": "Author rebuilt isolated addon; 69 native compatibility tests/178 assertions passed outside sandbox. Included in combined integration gate, not additional coverage."
},
"scoped_checks": [
"Strict standalone TypeScript on both new source/test groups passed.",
"Explicit ESLint on seven new/changed TypeScript files passed.",
"Prettier check on all changed TypeScript and new economic JSON fixtures passed.",
"git diff --check passed."
],
"source_verification": {
"hashes": {
"Cargo.lock": "21aaf3923c697b0a4e464033f6127a1fffe44ee2b0fc57585f992b7445e3c69f",
"apps/stock/engine/Cargo.toml": "02b6c190ed9ebf2c5d355a3bc36264954d2d2585438da15f0250d34943654aa7",
"apps/stock/engine/src/lib.rs": "671eb892cd0ba321a77851223ccbc9ac18d80a048a30f5f280c7893aea887619",
"apps/stock/engine/src/financial/contract.rs": "67d309f3bbeae57c2744c307c76320e7e75f011f01a9c2ff5364d4668d1749a5",
"apps/stock/engine/src/financial/mod.rs": "c5c7397829043ff09e2471f327a243b7ecece7a270f9c5966466e8c52e23da4e",
"apps/stock/engine/src/financial/scalar.rs": "fdb99264f5570a0f4a8493a4a2636e7f5f2980bdf45e8c2179de3fb5ef1f2034",
"apps/stock/engine/src/financial/tests.rs": "1d3a8fb80133284eaa2aa6fb558fb40c4f563a28d098340752101852b4d9fbf7",
"libs/core/types/src/financial-engine.ts": "0c838d12b09847c4a7e3f6fc56f08f8fcfdadb50ed126106145ed67e188c8652",
"test/fixtures/economics/contracts.json": "f68913d6ca1726fb0bbd2f04391bfca0476edd570d54717225b0a47a4e11939e",
"test/fixtures/economics/ledger-specs.json": "01e174b5f619b92777fb6f735abd630249472150301df6beb9c44d7db9d868bf",
"test/fixtures/economics/scalars.json": "d7bf11525d5f293365271fb8ab47531fd395758d087736715550f53554100d87",
"test/integration/financial-contract.test.ts": "22d99809d0f56e2151975ca6d07555694b115ff8e7a76c5c0831ba63f2ca486d",
"libs/core/types/src/historical-data.ts": "577a453ea1c4f1938deeaeba8746a9a8643d9cbb6d27665347828fade2a72895",
"apps/stock/orchestrator/src/data/historical-dataset-v2.ts": "1ff26166cf1492cfac946145f5f27c2a7f0b5cde188c44cdd6a17a93c5a766fa",
"test/integration/historical-dataset-v2.test.ts": "c8dba1b7a91c8699ef2a8a58f04005666e92eacdb8433af471a9da1b571331d0",
"test/fixtures/historical-v2/dataset.ts": "3559566eee87175ee03042c66ea45c6d0e166b6627de838c96a510d702196b36",
"libs/core/types/src/index.ts": "b2ff7c8d423d3c37379a94d5d1aaa6a80581a19df7f628958b36fe972360527d"
},
"exceptions": [
"types/index.ts intentionally merges financial and v2 dataset exports; build and types tests cover the merged file.",
"Cargo.toml preserves original CRLF/no-terminal-newline formatting; normalized TOML text matches reviewed source.",
"contracts.json and ledger-specs.json are Prettier-normalized; parsed JSON equals reviewed fixtures, followed by Rust/TS reruns."
]
},
"native_artifact": {
"path": "apps/stock/engine/dist/engine.node",
"sha256": "33fafb4ff0d783f3bfd675c6a5d7922e2939dd296f9c63e98bc1eec464e19c7f",
"author_worktree_sha256": "179df84c0e553265e9908086b512a19902a32ff556a3c2a17307645c43e32618",
"note": "Both built locally from their own worktrees; no addon copied across worktrees."
},
"not_run": [
"PostgreSQL/Redis fixture suite and Chromium E2E not rerun in this additive contract-only wave; no SQL/API/UI or active-runtime cutover changed.",
"No throughput certification; optional author synthetic normalizer timing was exploratory, not a repeatable benchmark claim."
],
"limitations": [
"Financial projection is not a restorable session. F02 owns ledger transitions, dedup receipts and operation-specific exact basis arithmetic; F04/F06/F07 own risk/replay/sessions.",
"Dataset v2 remains an additive API, not active storage/replay integration. Explicit calendars are caller-supplied; partial-session intraday bars are unsupported; unknown coverage remains exploratory.",
"Retained v1 datasets and current financial runtimes are unchanged. No full backtest economic-correctness claim follows from these tests.",
"Initial isolated library builds encountered existing browser/logger ordering resolution and stock-config dependency prerequisites; scoped builds/retries passed, no build-system fix claimed.",
"Existing Rust/frontend build warnings remain."
],
"cleanup": "Only verified stale sandbox check/test/worker processes were stopped after the successful escalated run; root session13178 exited143 and author session45451 exited143. No user services, databases, containers or files were removed. Worktrees/logs remain available.",
"handoff": "F01/D01 remain review/validated_uncommitted; F02/D02 await accepted integration and further execution authorization. No sixth-wave commit, push, PR, trading operation or other task started."
}
}

View file

@ -18,6 +18,12 @@ Measurable benefit: Defines point-in-time truth before new replay logic.
Absorb D03 in the same manifest version: record universe/as-of and corporate-action coverage, distinguish signal-adjusted from raw execution prices and retain limitations. Do not build an action feed or a correctness-gate evidence subsystem. Known unsupported action ranges reject executable policy; unknown coverage stays explicitly exploratory, never silently verified.
### Sixth-wave scope clarification
Implement a separate additive v2 normalizer; leave the existing v1 loader, persisted snapshots, SQL, APIs and runtime unchanged. Callers supply source/revision-labelled UTC session tables with an IANA time zone; never infer an exchange from a symbol suffix or weekdays. Initially accept only full-duration intraday bars contained within a session; partial-session bars are unsupported. Explicit availability and interval-end assumptions remain distinct and hash-retained.
Verify the original hash before converting v1 and retain it as the parent hash. Converted VWAP is unknown because v1 cannot distinguish provider VWAP from a synthesized value. Unknown universe/action coverage stays exploratory, including after executable-policy validation; validation is not research certification. Trade-end bars remain available for terminal marking, while later replay enforces the half-open decision window. Prefix tests here prove normalization stability, not the future F06 replay gate.
## Exclusions
No unrelated refactor, new service or broker activation.

View file

@ -14,6 +14,12 @@ Scheduling source of truth: [manifest entry F01](../manifest.json). No task is a
Define only the contracts consumed by the first financial vertical slice: scalar posting rules, owner IDs, account risk-session boundary, commands/effects, snapshot version and stable decision identity. Use a maintained checked decimal implementation, not bespoke arithmetic. Absorb C05: add small hand-derived JSON/table fixtures beside their consumers, without a reference simulator or an expected-failure test campaign. Freeze the TS/Rust command/context shape before consumers implement it.
### Sixth-wave scope clarification
The additive contract separates strategy intents from engine-internal fill/mark/session commands. The snapshot is an economic projection, **not** a complete recoverable session. Full observation contexts, sessions and native bindings remain F06/F07 work; this task must not introduce a second executable engine.
The maintained decimal wrapper provides checked ingress, fixed-8 posting, addition and subtraction. Generic multiplication/division are intentionally absent: intermediate rounding needs operation-specific F02 tests, especially proportional basis release. Remaining-basis and command-conflict fixtures are hand-derived F02 specifications, not claims of implemented ledger or deduplication behavior. TypeScript validates wire shapes and canonical decimal strings only; it does no financial arithmetic.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
@ -37,7 +43,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
## Acceptance criteria
- Financial postings use8 decimal places with explicit round-half-away-from-zero at ties (matching current TS half-up behavior); reject overflow/non-finite/excess-precision external commands. Float observations/features are not converted into money strings on every native crossing.
- Financial postings use 8 decimal places with explicit round-half-away-from-zero at ties (matching current TS half-up behavior); reject overflow/non-finite/excess-precision external commands. Float observations/features are not converted into money strings on every native crossing.
- Authoritative basis is remaining cost amount, not rounded average price. Fixture buys3 shares for total5; partial/final disposals release exactly5 basis in total.
- Stable protocol snapshot/command serialization and unknown-version rejection pass small Rust/TS contract fixtures; scope is one supported version, not a compatibility-negotiation framework.
- Each regression fixture lists economic assumptions, hand calculation and owning task. Each implementation task adds its own passing regression coverage; do not merge a blanket failing suite.

View file

@ -0,0 +1,493 @@
/**
* F01 wire shapes only. Rust owns all financial arithmetic and transitions.
* These validators never calculate fills, fees, basis, reservations or equity.
* Market/feature arrays stay numeric; this string boundary is for postings.
*/
export const FINANCIAL_PROTOCOL_VERSION = 1 as const;
export const MAX_FINANCIAL_POSTING = '792281625142643375935.43950335';
declare const financialDecimal: unique symbol;
export type FinancialDecimal = string & { readonly [financialDecimal]: true };
export interface DecisionIdentity {
ownerId: string;
decisionId: string;
sequence: number;
}
export interface RiskSessionIdentity {
calendarId: string;
calendarRevision: string;
sessionId: string;
/** Unix milliseconds, not an inferred processing-time date. */
startsAt: number;
}
type Side = 'buy' | 'sell';
type TimeInForce = 'GTC' | 'DAY' | 'IOC' | 'FOK';
type EngineCommandBody =
| {
kind: 'applyFill';
decision: DecisionIdentity;
orderId: string;
fillId: string;
instrumentId: string;
side: Side;
quantity: FinancialDecimal;
price: FinancialDecimal;
fee: { feeId: string; amount: FinancialDecimal };
}
| { kind: 'mark'; instrumentId: string; price: FinancialDecimal }
| { kind: 'riskSessionBoundary'; riskSession: RiskSessionIdentity };
/** Engine internal only. NEVER accept this as the strategy submission API. */
export interface EngineFinancialCommand {
version: 1;
sessionId: string;
accountId: string;
/** Scoped to (sessionId, accountId); F02 implements retry/conflict enforcement. */
commandId: string;
eventTime: number;
body: EngineCommandBody;
}
export type FinancialOrderIntent =
| {
kind: 'market';
orderId: string;
instrumentId: string;
side: Side;
quantity: FinancialDecimal;
timeInForce: TimeInForce;
}
| {
kind: 'limit';
orderId: string;
instrumentId: string;
side: Side;
quantity: FinancialDecimal;
price: FinancialDecimal;
timeInForce: TimeInForce;
}
| { kind: 'cancel'; orderId: string };
export type FinancialStrategyIntent =
| { mode: 'target'; targets: { instrumentId: string; quantity: FinancialDecimal }[] }
| { mode: 'orders'; orders: FinancialOrderIntent[] };
/** A member of a shared barrier, never a direct financial mutation. */
export interface FinancialStrategyDecision {
version: 1;
sessionId: string;
barrierId: string;
revision: number;
decision: DecisionIdentity;
intent: FinancialStrategyIntent;
}
/**
* Economic projection ONLY, not a complete restorable session snapshot.
* F02/F04/F07 own receipts, reservations, open orders, risk/replay/strategy/RNG
* state. Remaining cost is authoritative; rounded average cost is absent.
*/
export interface FinancialSnapshot {
version: 1;
sessionId: string;
accountId: string;
revision: number;
baseCurrency: string;
reserveOwnerId: string;
cash: FinancialDecimal;
positions: {
ownerId: string;
instrumentId: string;
quantity: FinancialDecimal;
remainingCost: FinancialDecimal;
realizedGrossPnl: FinancialDecimal;
}[];
fees: { ownerId: string; amount: FinancialDecimal }[];
riskSession: RiskSessionIdentity;
}
export type FinancialEffect =
| {
kind: 'fillApplied';
ownerId: string;
orderId: string;
fillId: string;
instrumentId: string;
price: FinancialDecimal;
cashDelta: FinancialDecimal;
quantityDelta: FinancialDecimal;
releasedBasis: FinancialDecimal;
realizedGrossPnl: FinancialDecimal;
}
| { kind: 'feeApplied'; ownerId: string; fillId: string; feeId: string; amount: FinancialDecimal }
| { kind: 'markUpdated'; instrumentId: string; price: FinancialDecimal }
| { kind: 'riskSessionChanged'; riskSession: RiskSessionIdentity }
| { kind: 'rejected'; code: string };
export interface FinancialEffects {
version: 1;
sessionId: string;
accountId: string;
commandId: string;
eventTime: number;
revision: number;
/** Transition order is authoritative. Do not sort. */
effects: FinancialEffect[];
}
function invalid(message: string): never {
throw new Error(`Invalid financial contract: ${message}`);
}
function object(value: unknown, keys: readonly string[]): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('expected object');
}
const record = value as Record<string, unknown>;
if (Object.keys(record).length !== keys.length || keys.some(key => !Object.hasOwn(record, key))) {
return invalid(`expected exactly ${keys.join(', ')}`);
}
return record;
}
function tag(value: unknown, key: string): unknown {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('expected tagged object');
}
return (value as Record<string, unknown>)[key];
}
function id(value: unknown): string {
// Preserve provider/instrument IDs; dataset membership is checked at admission.
if (
typeof value !== 'string' ||
value.length === 0 ||
Array.from(value).some(character => {
const code = character.charCodeAt(0);
// Array.from keeps valid surrogate pairs together. Lone surrogates cannot
// round-trip through Rust's UTF-8 String.
return (
code < 32 || code === 127 || (character.length === 1 && code >= 0xd800 && code <= 0xdfff)
);
})
) {
return invalid('expected nonempty well-formed identity without control characters');
}
return value;
}
function integer(value: unknown, signed = false): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || (!signed && value < 0)) {
return invalid('expected a safe integer');
}
return value === 0 ? 0 : value;
}
function version(value: unknown): 1 {
if (integer(value) !== FINANCIAL_PROTOCOL_VERSION) {
return invalid('unsupported financial protocol version');
}
return FINANCIAL_PROTOCOL_VERSION;
}
function array<T>(value: unknown, parse: (item: unknown) => T): T[] {
if (!Array.isArray(value)) {
return invalid('expected array');
}
return Array.from(value, parse);
}
function choice<T extends string>(value: unknown, choices: readonly T[]): T {
if (typeof value !== 'string' || !choices.includes(value as T)) {
return invalid(`expected ${choices.join(' | ')}`);
}
return value as T;
}
/** Lexical precision/range validation and padding only: no financial arithmetic. */
export function parseFinancialDecimal(value: unknown): FinancialDecimal {
if (
typeof value !== 'string' ||
value.match(/^-?(0|[1-9][0-9]*)(\.[0-9]{1,8})?$/)?.[0] !== value
) {
return invalid('expected plain decimal string with at most 8 fractional digits');
}
const negative = value.startsWith('-');
const [whole = '', fraction = ''] = (negative ? value.slice(1) : value).split('.');
const magnitude = `${whole}.${fraction.padEnd(8, '0')}`;
const maxWhole = MAX_FINANCIAL_POSTING.slice(0, MAX_FINANCIAL_POSTING.indexOf('.'));
if (
whole.length > maxWhole.length ||
(whole.length === maxWhole.length && magnitude > MAX_FINANCIAL_POSTING)
) {
return invalid('financial posting exceeds the fixed-8 decimal range');
}
return `${negative && magnitude !== '0.00000000' ? '-' : ''}${magnitude}` as FinancialDecimal;
}
function decimal(
value: unknown,
sign: 'any' | 'nonnegative' | 'positive' = 'any'
): FinancialDecimal {
const parsed = parseFinancialDecimal(value);
if (
(sign !== 'any' && parsed.startsWith('-')) ||
(sign === 'positive' && parsed === '0.00000000')
) {
return invalid(`expected ${sign} posting`);
}
return parsed;
}
function decisionIdentity(value: unknown): DecisionIdentity {
const row = object(value, ['ownerId', 'decisionId', 'sequence']);
return {
ownerId: id(row.ownerId),
decisionId: id(row.decisionId),
sequence: integer(row.sequence),
};
}
function riskSession(value: unknown): RiskSessionIdentity {
const row = object(value, ['calendarId', 'calendarRevision', 'sessionId', 'startsAt']);
return {
calendarId: id(row.calendarId),
calendarRevision: id(row.calendarRevision),
sessionId: id(row.sessionId),
startsAt: integer(row.startsAt, true),
};
}
function commandBody(value: unknown): EngineCommandBody {
switch (tag(value, 'kind')) {
case 'applyFill': {
const row = object(value, [
'kind',
'decision',
'orderId',
'fillId',
'instrumentId',
'side',
'quantity',
'price',
'fee',
]);
const fee = object(row.fee, ['feeId', 'amount']);
return {
kind: 'applyFill',
decision: decisionIdentity(row.decision),
orderId: id(row.orderId),
fillId: id(row.fillId),
instrumentId: id(row.instrumentId),
side: choice(row.side, ['buy', 'sell']),
quantity: decimal(row.quantity, 'positive'),
price: decimal(row.price, 'positive'),
fee: { feeId: id(fee.feeId), amount: decimal(fee.amount, 'nonnegative') },
};
}
case 'mark': {
const row = object(value, ['kind', 'instrumentId', 'price']);
return {
kind: 'mark',
instrumentId: id(row.instrumentId),
price: decimal(row.price, 'positive'),
};
}
case 'riskSessionBoundary': {
const row = object(value, ['kind', 'riskSession']);
return { kind: 'riskSessionBoundary', riskSession: riskSession(row.riskSession) };
}
default:
return invalid('unsupported engine command');
}
}
export function parseEngineFinancialCommand(value: unknown): EngineFinancialCommand {
const row = object(value, [
'version',
'sessionId',
'accountId',
'commandId',
'eventTime',
'body',
]);
return {
version: version(row.version),
sessionId: id(row.sessionId),
accountId: id(row.accountId),
commandId: id(row.commandId),
eventTime: integer(row.eventTime, true),
body: commandBody(row.body),
};
}
function orderIntent(value: unknown): FinancialOrderIntent {
const kind = choice(tag(value, 'kind'), ['market', 'limit', 'cancel']);
if (kind === 'cancel') {
const row = object(value, ['kind', 'orderId']);
return { kind, orderId: id(row.orderId) };
}
const row = object(value, [
'kind',
'orderId',
'instrumentId',
'side',
'quantity',
'timeInForce',
...(kind === 'limit' ? ['price'] : []),
]);
const common = {
orderId: id(row.orderId),
instrumentId: id(row.instrumentId),
side: choice(row.side, ['buy', 'sell']),
quantity: decimal(row.quantity, 'positive'),
timeInForce: choice(row.timeInForce, ['GTC', 'DAY', 'IOC', 'FOK']),
};
return kind === 'limit'
? { kind, ...common, price: decimal(row.price, 'positive') }
: { kind, ...common };
}
function strategyIntent(value: unknown): FinancialStrategyIntent {
switch (tag(value, 'mode')) {
case 'target': {
const row = object(value, ['mode', 'targets']);
return {
mode: 'target',
targets: array(row.targets, item => {
const target = object(item, ['instrumentId', 'quantity']);
return {
instrumentId: id(target.instrumentId),
quantity: decimal(target.quantity, 'nonnegative'),
};
}),
};
}
case 'orders': {
const row = object(value, ['mode', 'orders']);
return { mode: 'orders', orders: array(row.orders, orderIntent) };
}
default:
return invalid('unsupported strategy mode');
}
}
export function parseFinancialStrategyDecision(value: unknown): FinancialStrategyDecision {
const row = object(value, [
'version',
'sessionId',
'barrierId',
'revision',
'decision',
'intent',
]);
return {
version: version(row.version),
sessionId: id(row.sessionId),
barrierId: id(row.barrierId),
revision: integer(row.revision),
decision: decisionIdentity(row.decision),
intent: strategyIntent(row.intent),
};
}
export function parseFinancialSnapshot(value: unknown): FinancialSnapshot {
const row = object(value, [
'version',
'sessionId',
'accountId',
'revision',
'baseCurrency',
'reserveOwnerId',
'cash',
'positions',
'fees',
'riskSession',
]);
return {
version: version(row.version),
sessionId: id(row.sessionId),
accountId: id(row.accountId),
revision: integer(row.revision),
baseCurrency: id(row.baseCurrency),
reserveOwnerId: id(row.reserveOwnerId),
cash: decimal(row.cash, 'nonnegative'),
positions: array(row.positions, item => {
const position = object(item, [
'ownerId',
'instrumentId',
'quantity',
'remainingCost',
'realizedGrossPnl',
]);
return {
ownerId: id(position.ownerId),
instrumentId: id(position.instrumentId),
quantity: decimal(position.quantity, 'nonnegative'),
remainingCost: decimal(position.remainingCost, 'nonnegative'),
realizedGrossPnl: decimal(position.realizedGrossPnl),
};
}),
fees: array(row.fees, item => {
const fee = object(item, ['ownerId', 'amount']);
return { ownerId: id(fee.ownerId), amount: decimal(fee.amount, 'nonnegative') };
}),
riskSession: riskSession(row.riskSession),
};
}
function effect(value: unknown): FinancialEffect {
switch (tag(value, 'kind')) {
case 'fillApplied': {
const row = object(value, [
'kind',
'ownerId',
'orderId',
'fillId',
'instrumentId',
'price',
'cashDelta',
'quantityDelta',
'releasedBasis',
'realizedGrossPnl',
]);
return {
kind: 'fillApplied',
ownerId: id(row.ownerId),
orderId: id(row.orderId),
fillId: id(row.fillId),
instrumentId: id(row.instrumentId),
price: decimal(row.price, 'positive'),
cashDelta: decimal(row.cashDelta),
quantityDelta: decimal(row.quantityDelta),
releasedBasis: decimal(row.releasedBasis, 'nonnegative'),
realizedGrossPnl: decimal(row.realizedGrossPnl),
};
}
case 'feeApplied': {
const row = object(value, ['kind', 'ownerId', 'fillId', 'feeId', 'amount']);
return {
kind: 'feeApplied',
ownerId: id(row.ownerId),
fillId: id(row.fillId),
feeId: id(row.feeId),
amount: decimal(row.amount, 'nonnegative'),
};
}
case 'markUpdated': {
const row = object(value, ['kind', 'instrumentId', 'price']);
return {
kind: 'markUpdated',
instrumentId: id(row.instrumentId),
price: decimal(row.price, 'positive'),
};
}
case 'riskSessionChanged': {
const row = object(value, ['kind', 'riskSession']);
return { kind: 'riskSessionChanged', riskSession: riskSession(row.riskSession) };
}
case 'rejected': {
const row = object(value, ['kind', 'code']);
return { kind: 'rejected', code: id(row.code) };
}
default:
return invalid('unsupported financial effect');
}
}
export function parseFinancialEffects(value: unknown): FinancialEffects {
const row = object(value, [
'version',
'sessionId',
'accountId',
'commandId',
'eventTime',
'revision',
'effects',
]);
return {
version: version(row.version),
sessionId: id(row.sessionId),
accountId: id(row.accountId),
commandId: id(row.commandId),
eventTime: integer(row.eventTime, true),
revision: integer(row.revision),
effects: array(row.effects, effect),
};
}

View file

@ -115,3 +115,117 @@ export interface HistoricalDataset {
vwap: number;
}[];
}
/** V2 is additive: legacy snapshots and their hashes retain the v1 contract above. */
export interface HistoricalCalendarV2 {
readonly id: string;
readonly venue: string;
readonly timeZone: string;
readonly revision: string;
readonly source: string;
/** Session-label coverage [startDate, endDate); no inferred holiday/session rules. */
readonly startDate: string;
readonly endDate: string;
readonly sessions: readonly {
readonly date: string;
readonly open: number;
readonly close: number;
}[];
}
export interface HistoricalSeriesV2 {
readonly id: string;
readonly instrumentId: string;
readonly interval: '1m' | '5m' | '15m' | '1h' | '1d';
readonly calendarId: string;
readonly venue: string;
readonly source: { readonly provider: string; readonly revision: string };
readonly timestamp: 'session-date' | 'interval-start' | 'interval-end';
readonly availability: 'explicit' | 'interval-end-assumption';
readonly adjustment: 'raw' | 'provider-adjusted';
}
export interface HistoricalDatasetMetadataV2 {
readonly calendars: readonly HistoricalCalendarV2[];
readonly series: readonly HistoricalSeriesV2[];
/** Exactly one execution feed per included instrument; other series are feature inputs. */
readonly executionSeries: readonly { readonly instrumentId: string; readonly seriesId: string }[];
/** Interval coverage [warmupStart, tradeEnd], with starts strictly before tradeEnd.
* Replay must restrict decisions/fills to [tradeStart, tradeEnd); an observation
* available exactly at tradeEnd may provide a terminal mark, not a new decision.
*/
readonly bounds: {
readonly warmupStart: number;
readonly tradeStart: number;
readonly tradeEnd: number;
};
readonly universe: {
readonly selection: 'point-in-time' | 'current-constituents' | 'unknown';
readonly asOf: number | null;
readonly revision: string;
readonly instrumentIds: readonly string[];
};
readonly corporateActions: readonly {
readonly instrumentId: string;
readonly status: 'unknown' | 'action-free' | 'known-actions';
readonly start: number;
readonly end: number;
readonly revision: string;
readonly actions: readonly {
readonly effectiveAt: number;
readonly kind: 'split' | 'dividend' | 'other';
readonly reference: string;
}[];
}[];
}
export interface HistoricalBarV2 {
readonly seriesId: string;
readonly instrumentId: string;
readonly intervalStart: number;
readonly intervalEnd: number;
readonly eventTime: number;
readonly availableAt: number;
readonly sourceSequence: number;
readonly open: number;
readonly high: number;
readonly low: number;
readonly close: number;
readonly volume: number;
readonly vwap: number | null;
}
export interface HistoricalDatasetManifestV2 extends HistoricalDatasetMetadataV2 {
readonly version: 2;
readonly hash: string;
readonly normalizationRevision: 'historical-normalization-v2';
readonly parentDatasetHash: string | null;
readonly volumePolicy: 'reported';
readonly qualityPolicy: 'reject-invalid-no-interpolation';
readonly intradayPolicy: 'full-duration-session-contained';
readonly eligibility: 'eligible' | 'exploratory' | 'ineligible';
readonly limitations: readonly string[];
readonly barCount: number;
}
export interface HistoricalDatasetV2 {
readonly manifest: HistoricalDatasetManifestV2;
readonly bars: readonly HistoricalBarV2[];
}
export interface HistoricalDatasetInputV2 {
readonly metadata: HistoricalDatasetMetadataV2;
readonly bars: readonly {
readonly seriesId: string;
/** Daily YYYY-MM-DD label, otherwise explicit epoch milliseconds per series policy. */
readonly timestamp: string | number;
readonly availableAt?: number;
readonly sourceSequence: number;
readonly open: number;
readonly high: number;
readonly low: number;
readonly close: number;
readonly volume: number;
readonly vwap?: number | null;
}[];
}

View file

@ -94,6 +94,27 @@ export {
parseReferenceDataResetRequest,
} from './reference-data';
export type { ReferenceDataResetRequest, ReferenceDataResetScope } from './reference-data';
export {
FINANCIAL_PROTOCOL_VERSION,
MAX_FINANCIAL_POSTING,
parseFinancialDecimal,
parseEngineFinancialCommand,
parseFinancialStrategyDecision,
parseFinancialSnapshot,
parseFinancialEffects,
} from './financial-engine';
export type {
FinancialDecimal,
DecisionIdentity,
RiskSessionIdentity,
EngineFinancialCommand,
FinancialOrderIntent,
FinancialStrategyIntent,
FinancialStrategyDecision,
FinancialSnapshot,
FinancialEffect,
FinancialEffects,
} from './financial-engine';
export {
parseInstrumentId,
HistoricalDataRequestError,
@ -105,3 +126,12 @@ export type {
HistoricalDataset,
HistoricalDatasetManifest,
} from './historical-data';
export type {
HistoricalCalendarV2,
HistoricalSeriesV2,
HistoricalDatasetMetadataV2,
HistoricalBarV2,
HistoricalDatasetManifestV2,
HistoricalDatasetV2,
HistoricalDatasetInputV2,
} from './historical-data';

803
test/fixtures/economics/contracts.json vendored Normal file
View file

@ -0,0 +1,803 @@
{
"schemaVersion": 1,
"valid": [
{
"id": "fillCommand",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "command",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
}
},
{
"id": "markCommand",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "command",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-mark-1",
"eventTime": 1704292260000,
"body": {
"kind": "mark",
"instrumentId": "A^P.US",
"price": "2.00000000"
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-mark-1",
"eventTime": 1704292260000,
"body": {
"kind": "mark",
"instrumentId": "A^P.US",
"price": "2.00000000"
}
}
},
{
"id": "boundaryCommand",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "command",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "boundary-1",
"eventTime": 1704292200000,
"body": {
"kind": "riskSessionBoundary",
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "boundary-1",
"eventTime": 1704292200000,
"body": {
"kind": "riskSessionBoundary",
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
}
}
},
{
"id": "targetDecision",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "decision",
"input": {
"version": 1,
"sessionId": "research:run-1",
"barrierId": "barrier-1",
"revision": 0,
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"intent": {
"mode": "target",
"targets": [
{
"instrumentId": "A^P.US",
"quantity": "3.00000000"
},
{
"instrumentId": "B.US",
"quantity": "0.00000000"
}
]
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"barrierId": "barrier-1",
"revision": 0,
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"intent": {
"mode": "target",
"targets": [
{
"instrumentId": "A^P.US",
"quantity": "3.00000000"
},
{
"instrumentId": "B.US",
"quantity": "0.00000000"
}
]
}
}
},
{
"id": "orderDecision",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "decision",
"input": {
"version": 1,
"sessionId": "research:run-1",
"barrierId": "barrier-1",
"revision": 0,
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"intent": {
"mode": "orders",
"orders": [
{
"kind": "market",
"orderId": "order-2",
"instrumentId": "A.US",
"side": "buy",
"quantity": "1.00000000",
"timeInForce": "GTC"
},
{
"kind": "limit",
"orderId": "order-3",
"instrumentId": "B.US",
"side": "sell",
"quantity": "1.00000000",
"price": "2.00000000",
"timeInForce": "DAY"
},
{
"kind": "cancel",
"orderId": "order-4"
}
]
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"barrierId": "barrier-1",
"revision": 0,
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"intent": {
"mode": "orders",
"orders": [
{
"kind": "market",
"orderId": "order-2",
"instrumentId": "A.US",
"side": "buy",
"quantity": "1.00000000",
"timeInForce": "GTC"
},
{
"kind": "limit",
"orderId": "order-3",
"instrumentId": "B.US",
"side": "sell",
"quantity": "1.00000000",
"price": "2.00000000",
"timeInForce": "DAY"
},
{
"kind": "cancel",
"orderId": "order-4"
}
]
}
}
},
{
"id": "snapshot",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Assume100 initial cash;3*2=6 notional,0.06 fee; cash93.94 and remaining basis6. Ordered example includes independent mark/boundary/rejection effects to cover tags.",
"type": "snapshot",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"revision": 1,
"baseCurrency": "USD",
"reserveOwnerId": "reserve",
"cash": "93.94000000",
"positions": [
{
"ownerId": "strategy:A",
"instrumentId": "A^P.US",
"quantity": "3.00000000",
"remainingCost": "6.00000000",
"realizedGrossPnl": "0.00000000"
}
],
"fees": [
{
"ownerId": "strategy:A",
"amount": "0.06000000"
}
],
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"revision": 1,
"baseCurrency": "USD",
"reserveOwnerId": "reserve",
"cash": "93.94000000",
"positions": [
{
"ownerId": "strategy:A",
"instrumentId": "A^P.US",
"quantity": "3.00000000",
"remainingCost": "6.00000000",
"realizedGrossPnl": "0.00000000"
}
],
"fees": [
{
"ownerId": "strategy:A",
"amount": "0.06000000"
}
],
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
}
},
{
"id": "effects",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Assume100 initial cash;3*2=6 notional,0.06 fee; cash93.94 and remaining basis6. Ordered example includes independent mark/boundary/rejection effects to cover tags.",
"type": "effects",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"revision": 1,
"effects": [
{
"kind": "fillApplied",
"ownerId": "strategy:A",
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"price": "2.00000000",
"cashDelta": "-6.00000000",
"quantityDelta": "3.00000000",
"releasedBasis": "0.00000000",
"realizedGrossPnl": "0.00000000"
},
{
"kind": "feeApplied",
"ownerId": "strategy:A",
"fillId": "fill-1",
"feeId": "fee-1",
"amount": "0.06000000"
},
{
"kind": "markUpdated",
"instrumentId": "A^P.US",
"price": "2.00000000"
},
{
"kind": "riskSessionChanged",
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
},
{
"kind": "rejected",
"code": "insufficientCash"
}
]
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"revision": 1,
"effects": [
{
"kind": "fillApplied",
"ownerId": "strategy:A",
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"price": "2.00000000",
"cashDelta": "-6.00000000",
"quantityDelta": "3.00000000",
"releasedBasis": "0.00000000",
"realizedGrossPnl": "0.00000000"
},
{
"kind": "feeApplied",
"ownerId": "strategy:A",
"fillId": "fill-1",
"feeId": "fee-1",
"amount": "0.06000000"
},
{
"kind": "markUpdated",
"instrumentId": "A^P.US",
"price": "2.00000000"
},
{
"kind": "riskSessionChanged",
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
},
{
"kind": "rejected",
"code": "insufficientCash"
}
]
}
},
{
"id": "unicodeIdentity",
"owningTask": "F01",
"assumptions": "Identity text is preserved; instrument is a supported synthetic listing. No actual index execution implied.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "command",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "命令:α",
"eventTime": 1704292260000,
"body": {
"kind": "mark",
"instrumentId": "A^P.US",
"price": "2.00000000"
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "命令:α",
"eventTime": 1704292260000,
"body": {
"kind": "mark",
"instrumentId": "A^P.US",
"price": "2.00000000"
}
}
}
],
"invalid": [
{
"id": "unknown_version",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["version"],
"value": 2
},
{
"id": "unknown_outer_key",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["unexpected"],
"value": true
},
{
"id": "unknown_body_key",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "unexpected"],
"value": true
},
{
"id": "unknown_nested_key",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "fee", "unexpected"],
"value": true
},
{
"id": "empty_owner",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "decision", "ownerId"],
"value": ""
},
{
"id": "control_id",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["commandId"],
"value": "a\nb"
},
{
"id": "zero_fill_quantity",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "quantity"],
"value": "0"
},
{
"id": "negative_fill_quantity",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "quantity"],
"value": "-1"
},
{
"id": "numeric_price",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "price"],
"value": 2
},
{
"id": "zero_price",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "price"],
"value": "0"
},
{
"id": "negative_fee",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "fee", "amount"],
"value": "-0.01"
},
{
"id": "excess_precision",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "quantity"],
"value": "1.000000000"
},
{
"id": "unsafe_sequence",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "decision", "sequence"],
"value": 9007199254740992
},
{
"id": "negative_sequence",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "decision", "sequence"],
"value": -1
},
{
"id": "future_command_kind",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "kind"],
"value": "deposit"
},
{
"id": "negative_cash",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["cash"],
"value": "-1"
},
{
"id": "negative_long_quantity",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["positions", "0", "quantity"],
"value": "-1"
},
{
"id": "negative_basis",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["positions", "0", "remainingCost"],
"value": "-1"
},
{
"id": "mixed_intents",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "targetDecision",
"path": ["intent", "orders"],
"value": []
},
{
"id": "negative_target",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "targetDecision",
"path": ["intent", "targets", "0", "quantity"],
"value": "-1"
},
{
"id": "unsupported_stop",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "orderDecision",
"path": ["intent", "orders", "0", "kind"],
"value": "stop"
},
{
"id": "unsafe_revision",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["revision"],
"value": 9007199254740992
},
{
"id": "unknown_snapshot_version",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["version"],
"value": 2
},
{
"id": "unknown_decision_version",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "targetDecision",
"path": ["version"],
"value": 2
},
{
"id": "unknown_effect_version",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "effects",
"path": ["version"],
"value": 2
},
{
"id": "invalid_effect_price",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "effects",
"path": ["effects", "0", "price"],
"value": "0"
},
{
"id": "negative_release",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "effects",
"path": ["effects", "0", "releasedBasis"],
"value": "-1"
},
{
"id": "null_risk_session",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["riskSession"],
"value": null
},
{
"id": "nul_identity",
"owningTask": "F01",
"assumptions": "Identifiers cannot contain ASCII control characters.",
"handCalculation": "Reject NUL in identity, without restricting legitimate Unicode text.",
"base": "fillCommand",
"path": ["commandId"],
"value": "a\u0000b"
}
],
"numeric": {
"id": "safe_json_number_parity",
"owningTask": "F01",
"assumptions": "Use parsed JSON number semantics across languages; counters nonnegative and timestamps signed; both JS-safe integers.",
"handCalculation": "Integral1.0 and1e0 equal1; abs(value)>9007199254740991, fractional/type-coerced values reject.",
"cases": [
{
"raw": "0",
"counterValid": true,
"timestampValid": true
},
{
"raw": "-0",
"counterValid": true,
"timestampValid": true
},
{
"raw": "1.0",
"counterValid": true,
"timestampValid": true
},
{
"raw": "1e0",
"counterValid": true,
"timestampValid": true
},
{
"raw": "9007199254740991",
"counterValid": true,
"timestampValid": true
},
{
"raw": "9007199254740992",
"counterValid": false,
"timestampValid": false
},
{
"raw": "1.5",
"counterValid": false,
"timestampValid": false
},
{
"raw": "-1",
"counterValid": false,
"timestampValid": true
},
{
"raw": "\"1\"",
"counterValid": false,
"timestampValid": false
},
{
"raw": "true",
"counterValid": false,
"timestampValid": false
},
{
"raw": "null",
"counterValid": false,
"timestampValid": false
},
{
"raw": "-9007199254740991",
"counterValid": false,
"timestampValid": true
},
{
"raw": "-9007199254740992",
"counterValid": false,
"timestampValid": false
}
]
}
}

View file

@ -0,0 +1,118 @@
{
"basis": {
"id": "basis_residual_spec",
"owningTask": "F02",
"assumptions": "Three owned shares have exact remaining cost5, no fees. Sell one share each time; basis rounds half-away at8dp. Final disposal releases exact residue.",
"handCalculation": "First5/3 rounds1.66666667; remaining3.33333333. Second3.33333333/2=1.666666665 rounds1.66666667; remaining1.66666666. Final release1.66666666. Sum exactly5, not3*roundedaverage=5.00000001.",
"initialQuantity": "3.00000000",
"initialCost": "5.00000000",
"releases": ["1.66666667", "1.66666667", "1.66666666"],
"remainingCosts": ["3.33333333", "1.66666666", "0.00000000"]
},
"commandIds": {
"id": "command_id_conflict_spec",
"owningTask": "F02",
"assumptions": "Command identity is tuple(sessionId,accountId,commandId); canonical typed payload comparison ignores object key order and decimal padding. Decision IDs are owner-scoped within session; no concatenated identifier collisions.",
"handCalculation": "Same identity+same canonical payload =>retry; same identity+changed fee=>conflict; different session=>independent. F01 checks this specification, not a runtime dedup store.",
"original": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
},
"retry": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
},
"conflict": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.07000000"
}
}
},
"independent": {
"version": 1,
"sessionId": "research:run-2",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
}
}
}

299
test/fixtures/economics/scalars.json vendored Normal file
View file

@ -0,0 +1,299 @@
{
"schemaVersion": 1,
"grammar": "^-?(0|[1-9][0-9]*)(\\.[0-9]{1,8})?$",
"range": "[-792281625142643375935.43950335, 792281625142643375935.43950335]",
"canonical": "Exactly eight fractional digits; signed zero becomes zero. External excess precision rejects, including trailing zeroes. No exponent, whitespace, plus, leading zeroes or numeric coercion.",
"cases": [
{
"id": "integer",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "3",
"canonical": "3.00000000"
},
{
"id": "fraction",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "-1.25",
"canonical": "-1.25000000"
},
{
"id": "negative_zero",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "-0.00000000",
"canonical": "0.00000000"
},
{
"id": "maximum",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "792281625142643375935.43950335",
"canonical": "792281625142643375935.43950335"
},
{
"id": "minimum",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "-792281625142643375935.43950335",
"canonical": "-792281625142643375935.43950335"
},
{
"id": "near_max_padding",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "792281625142643375935.4",
"canonical": "792281625142643375935.40000000"
},
{
"id": "invalid_0",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1e2",
"canonical": null
},
{
"id": "invalid_1",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1E2",
"canonical": null
},
{
"id": "invalid_2",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "+1",
"canonical": null
},
{
"id": "invalid_3",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": " 1",
"canonical": null
},
{
"id": "invalid_4",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1 ",
"canonical": null
},
{
"id": "invalid_5",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "01",
"canonical": null
},
{
"id": "invalid_6",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1.",
"canonical": null
},
{
"id": "invalid_7",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": ".1",
"canonical": null
},
{
"id": "invalid_8",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1.000000000",
"canonical": null
},
{
"id": "invalid_9",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "NaN",
"canonical": null
},
{
"id": "invalid_10",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "Infinity",
"canonical": null
},
{
"id": "invalid_11",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "-Infinity",
"canonical": null
},
{
"id": "invalid_12",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "792281625142643375935.43950336",
"canonical": null
},
{
"id": "invalid_13",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "-792281625142643375935.43950336",
"canonical": null
},
{
"id": "invalid_14",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "792281625142643375936",
"canonical": null
},
{
"id": "invalid_15",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": 1,
"canonical": null
},
{
"id": "invalid_16",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": null,
"canonical": null
},
{
"id": "invalid_17",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": true,
"canonical": null
},
{
"id": "terminal_line_separator_0",
"owningTask": "F01",
"assumptions": "Strict entire-string decimal ingress; JavaScript dollar-anchor alone is insufficient.",
"handCalculation": "Reject trailing line separators rather than padding malformed text.",
"input": "1\n",
"canonical": null
},
{
"id": "terminal_line_separator_1",
"owningTask": "F01",
"assumptions": "Strict entire-string decimal ingress; JavaScript dollar-anchor alone is insufficient.",
"handCalculation": "Reject trailing line separators rather than padding malformed text.",
"input": "1\r\n",
"canonical": null
},
{
"id": "terminal_line_separator_2",
"owningTask": "F01",
"assumptions": "Strict entire-string decimal ingress; JavaScript dollar-anchor alone is insufficient.",
"handCalculation": "Reject trailing line separators rather than padding malformed text.",
"input": "1
",
"canonical": null
},
{
"id": "terminal_line_separator_3",
"owningTask": "F01",
"assumptions": "Strict entire-string decimal ingress; JavaScript dollar-anchor alone is insufficient.",
"handCalculation": "Reject trailing line separators rather than padding malformed text.",
"input": "1
",
"canonical": null
}
],
"rounding": [
{
"id": "positive_tie",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "1.234567885",
"expected": "1.23456789"
},
{
"id": "negative_tie",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "-1.234567885",
"expected": "-1.23456789"
},
{
"id": "positive_below",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "1.234567884",
"expected": "1.23456788"
},
{
"id": "negative_below",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "-1.234567884",
"expected": "-1.23456788"
},
{
"id": "zero_tie",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "0.000000005",
"expected": "0.00000001"
},
{
"id": "negative_zero_tie",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "-0.000000005",
"expected": "-0.00000001"
},
{
"id": "negative_underflow",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "-0.000000004",
"expected": "0.00000000"
}
],
"overflow": {
"id": "overflow_rejected",
"owningTask": "F01",
"assumptions": "Fixed-eight 96-bit coefficient; calculations must fail rather than saturate or silently rescale.",
"handCalculation": "Max+0.00000001 and Min-0.00000001 overflow. Exact internal magnitude792281625142643375935.5 already exceeds max; reject before quantization.",
"maximum": "792281625142643375935.43950335",
"quantum": "0.00000001",
"roundingOverflow": "792281625142643375935.5"
}
}

85
test/fixtures/historical-v2/dataset.ts vendored Normal file
View file

@ -0,0 +1,85 @@
import type { HistoricalDatasetInputV2 } from '../../../libs/core/types/src/historical-data';
const time = (value: string) => Date.parse(value);
/** Synthetic retained table for regression testing, not a production calendar authority. */
export function datasetInput(): HistoricalDatasetInputV2 {
return {
metadata: {
calendars: [
{
id: 'test-us-equities',
venue: 'XNYS',
timeZone: 'America/New_York',
revision: 'test-sessions-2024-v1',
source: 'synthetic-regression-fixture',
startDate: '2024-03-01',
endDate: '2024-12-01',
sessions: [
{
date: '2024-03-08',
open: time('2024-03-08T14:30:00Z'),
close: time('2024-03-08T21:00:00Z'),
},
{
date: '2024-03-11',
open: time('2024-03-11T13:30:00Z'),
close: time('2024-03-11T20:00:00Z'),
},
{
date: '2024-11-29',
open: time('2024-11-29T14:30:00Z'),
close: time('2024-11-29T18:00:00Z'),
},
],
},
],
series: [
{
id: 'A.US:daily:raw',
instrumentId: 'A.US',
interval: '1d',
calendarId: 'test-us-equities',
venue: 'XNYS',
source: { provider: 'eod', revision: 'historical-normalization-v1' },
timestamp: 'session-date',
availability: 'interval-end-assumption',
adjustment: 'raw',
},
],
executionSeries: [{ instrumentId: 'A.US', seriesId: 'A.US:daily:raw' }],
bounds: {
warmupStart: time('2024-03-08T14:30:00Z'),
tradeStart: time('2024-03-11T13:30:00Z'),
tradeEnd: time('2024-11-29T18:00:00Z'),
},
universe: {
selection: 'point-in-time',
asOf: time('2024-03-01T00:00:00Z'),
revision: 'test-universe-v1',
instrumentIds: ['A.US'],
},
corporateActions: [
{
instrumentId: 'A.US',
status: 'action-free',
start: time('2024-03-01T00:00:00Z'),
end: time('2024-12-01T00:00:00Z'),
revision: 'test-action-coverage-v1',
actions: [],
},
],
},
bars: ['2024-03-08', '2024-03-11', '2024-11-29'].map((timestamp, sourceSequence) => ({
seriesId: 'A.US:daily:raw',
timestamp,
sourceSequence,
open: 100,
high: 110,
low: 90,
close: 105,
volume: 1000,
...(sourceSequence === 1 ? { vwap: 101 } : {}),
})),
};
}

View file

@ -0,0 +1,159 @@
import { expect, test } from 'bun:test';
import {
parseEngineFinancialCommand,
parseFinancialDecimal,
parseFinancialEffects,
parseFinancialSnapshot,
parseFinancialStrategyDecision,
} from '../../libs/core/types/src/financial-engine';
import contracts from '../fixtures/economics/contracts.json';
import ledgerSpecs from '../fixtures/economics/ledger-specs.json';
import scalars from '../fixtures/economics/scalars.json';
function parse(kind: string, value: unknown): unknown {
switch (kind) {
case 'command':
return parseEngineFinancialCommand(value);
case 'decision':
return parseFinancialStrategyDecision(value);
case 'snapshot':
return parseFinancialSnapshot(value);
case 'effects':
return parseFinancialEffects(value);
default:
throw new Error(`Unknown contract fixture ${kind}`);
}
}
function annotate(value: {
id: string;
owningTask: string;
assumptions: string;
handCalculation: string;
}) {
for (const key of ['id', 'owningTask', 'assumptions', 'handCalculation'] as const) {
expect(value[key].length).toBeGreaterThan(0);
}
}
test('rust_ts_fixture_parse_parity: shared scalar and versioned wire fixtures', () => {
for (const fixture of scalars.cases) {
annotate(fixture);
if (fixture.canonical === null) {
expect(() => parseFinancialDecimal(fixture.input)).toThrow();
} else {
expect(String(parseFinancialDecimal(fixture.input))).toBe(fixture.canonical);
}
}
for (const fixture of contracts.valid) {
annotate(fixture);
const result = parse(fixture.type, fixture.input);
expect(result).toEqual(fixture.canonical);
expect(parse(fixture.type, JSON.parse(JSON.stringify(result)))).toEqual(result);
}
for (const fixture of contracts.invalid) {
annotate(fixture);
const base = contracts.valid.find(candidate => candidate.id === fixture.base)!;
const input: unknown = structuredClone(base.input);
let parent = input as Record<string, unknown>;
for (const key of fixture.path.slice(0, -1)) {
parent = parent[key] as Record<string, unknown>;
}
parent[fixture.path.at(-1)!] = fixture.value;
expect(() => parse(base.type, input)).toThrow();
}
});
test('safe_integer_json_number_parity: integral lexical forms and exact boundaries', () => {
annotate(contracts.numeric);
const base = contracts.valid.find(candidate => candidate.id === 'fillCommand')!.input;
const snapshot = contracts.valid.find(candidate => candidate.id === 'snapshot')!.input;
for (const fixture of contracts.numeric.cases) {
const value: unknown = JSON.parse(fixture.raw);
const command = parseEngineFinancialCommand(base);
const timestamp = () => parseEngineFinancialCommand({ ...command, eventTime: value });
const sequence = () =>
parseEngineFinancialCommand({
...command,
body: { ...command.body, decision: { ownerId: 'A', decisionId: 'd', sequence: value } },
});
const revision = () => parseFinancialSnapshot({ ...snapshot, revision: value });
if (fixture.timestampValid) {
expect(value === 0 ? 0 : value).toBe(timestamp().eventTime);
} else {
expect(timestamp).toThrow();
}
for (const counter of [sequence, revision]) {
if (fixture.counterValid) {
expect(counter).not.toThrow();
} else {
expect(counter).toThrow();
}
}
}
});
test('rounding_ties_positive_negative: TypeScript rejects internal-only precision', () => {
for (const fixture of scalars.rounding) {
annotate(fixture);
expect(() => parseFinancialDecimal(fixture.input)).toThrow();
expect(String(parseFinancialDecimal(fixture.expected))).toBe(fixture.expected);
}
});
test('overflow_rejected: exact lexical bound with no floating-point conversion', () => {
annotate(scalars.overflow);
expect(String(parseFinancialDecimal(scalars.overflow.maximum))).toBe(scalars.overflow.maximum);
expect(() => parseFinancialDecimal('792281625142643375935.43950336')).toThrow();
expect(() => parseFinancialDecimal('-792281625142643375935.43950336')).toThrow();
expect(() => parseFinancialDecimal(scalars.overflow.roundingOverflow)).toThrow();
});
test('basis_residual_spec: F02 owns transition behavior, TS validates documented values only', () => {
annotate(ledgerSpecs.basis);
expect(ledgerSpecs.basis.owningTask).toBe('F02');
expect(ledgerSpecs.basis.releases).toEqual(['1.66666667', '1.66666667', '1.66666666']);
expect(ledgerSpecs.basis.remainingCosts).toEqual(['3.33333333', '1.66666666', '0.00000000']);
for (const value of [...ledgerSpecs.basis.releases, ...ledgerSpecs.basis.remainingCosts]) {
expect(String(parseFinancialDecimal(value))).toBe(value);
}
});
test('command_id_conflict_spec: typed canonical payload, not a second dedup engine', () => {
annotate(ledgerSpecs.commandIds);
expect(ledgerSpecs.commandIds.owningTask).toBe('F02');
const original = parseEngineFinancialCommand(ledgerSpecs.commandIds.original);
const retry = parseEngineFinancialCommand(ledgerSpecs.commandIds.retry);
const conflict = parseEngineFinancialCommand(ledgerSpecs.commandIds.conflict);
const independent = parseEngineFinancialCommand(ledgerSpecs.commandIds.independent);
expect(retry).toEqual(original);
expect([conflict.sessionId, conflict.accountId, conflict.commandId]).toEqual([
original.sessionId,
original.accountId,
original.commandId,
]);
expect(conflict.body).not.toEqual(original.body);
expect(independent.sessionId).not.toBe(original.sessionId);
expect(independent.body).toEqual(original.body);
});
test('strategy submission contract cannot accept internal financial mutations', () => {
const command = contracts.valid.find(candidate => candidate.id === 'fillCommand')!.input;
const decision = contracts.valid.find(candidate => candidate.id === 'targetDecision')!.input;
expect(() => parseFinancialStrategyDecision(command)).toThrow();
expect(() => parseEngineFinancialCommand(decision)).toThrow();
});
test('non-JSON sparse arrays cannot become valid wire contracts', () => {
const snapshot = contracts.valid.find(candidate => candidate.id === 'snapshot')!.input;
expect(() => parseFinancialSnapshot({ ...snapshot, positions: Array(1) })).toThrow();
});
test('identity text must round-trip through Rust UTF-8 without losing Unicode identifiers', () => {
const command = contracts.valid.find(candidate => candidate.id === 'markCommand')!.input;
for (const commandId of ['\ud800', '\udfff', 'a\ud800b']) {
expect(() => parseEngineFinancialCommand({ ...command, commandId })).toThrow();
}
expect(parseEngineFinancialCommand({ ...command, commandId: '命令:🧪' }).commandId).toBe(
'命令:🧪'
);
});

View file

@ -0,0 +1,374 @@
import { describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { validateDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
import {
assertDatasetV2Executable,
convertDatasetV1ToV2,
createDatasetV2,
validateDatasetV2,
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import type {
HistoricalDataset,
HistoricalDatasetInputV2,
} from '../../libs/core/types/src/historical-data';
import { datasetInput } from '../fixtures/historical-v2/dataset';
type Mutable<T> = T extends readonly (infer V)[]
? Mutable<V>[]
: T extends object
? { -readonly [K in keyof T]: Mutable<T[K]> }
: T;
const input = () => structuredClone(datasetInput()) as Mutable<HistoricalDatasetInputV2>;
function legacyFixture(): HistoricalDataset {
const bars = datasetInput().bars.map(row => ({
symbol: 'A.US',
timestamp: Date.parse(String(row.timestamp)),
open: row.open,
high: row.high,
low: row.low,
close: row.close,
volume: row.volume,
vwap: 101,
}));
const manifest = {
version: 1 as const,
instruments: [{ id: 'A.US', symbol: 'A', exchange: 'US' }],
startDate: '2024-03-08T00:00:00.000Z',
endDate: '2024-11-30T00:00:00.000Z',
interval: '1d',
policy: { adjustment: 'raw' as const, timestamp: 'utc-session-date' as const },
volumePolicy: 'reported' as const,
qualityPolicy: 'reject-invalid-no-interpolation' as const,
sources: [
{ instrumentId: 'A.US', provider: 'eod' as const, revision: 'historical-normalization-v1' },
],
barCount: bars.length,
};
return {
manifest: {
...manifest,
hash: createHash('sha256').update(JSON.stringify({ manifest, bars })).digest('hex'),
},
bars,
};
}
describe('availability-aware dataset v2', () => {
test('dataset_v1_compatibility: old hashes/read semantics stay unchanged and conversion is explicit', () => {
const old = legacyFixture(),
before = structuredClone(old);
const validated = validateDataset(old);
expect(validated).toEqual(before);
const converted = convertDatasetV1ToV2(old, input().metadata);
expect(converted.manifest.version).toBe(2);
expect(converted.manifest.parentDatasetHash).toBe(old.manifest.hash);
expect(converted.manifest.hash).not.toBe(old.manifest.hash);
expect(converted.bars.every(bar => bar.vwap === null)).toBe(true);
expect(converted.manifest.limitations.some(value => value.includes('VWAP provenance'))).toBe(
true
);
expect(validateDataset(old)).toEqual(before);
expect(old).toEqual(before);
expect(() => validateDataset(converted)).toThrow();
expect(() => validateDatasetV2(old)).toThrow();
const changed = input().metadata;
changed.series[0]!.source.revision = 'different-source';
expect(() => convertDatasetV1ToV2(old, changed)).toThrow('matching');
});
test('dataset_v2_hash: stable canonical serialization includes calendar and policy provenance', () => {
const first = createDatasetV2(input());
const reordered = JSON.parse(JSON.stringify(input()), (_key, value) =>
value && typeof value === 'object' && !Array.isArray(value)
? Object.fromEntries(Object.entries(value).reverse())
: value
);
reordered.bars.reverse();
expect(createDatasetV2(reordered)).toEqual(first);
expect(validateDatasetV2(JSON.parse(JSON.stringify(first)))).toEqual(first);
const { hash, ...manifest } = first.manifest;
expect(
createHash('sha256')
.update(JSON.stringify({ manifest, bars: first.bars }))
.digest('hex')
).toBe(hash);
for (const change of [
(value: ReturnType<typeof input>) => {
value.metadata.calendars[0]!.revision = 'v2';
},
(value: ReturnType<typeof input>) => {
value.metadata.calendars[0]!.source = 'another-retained-source';
},
(value: ReturnType<typeof input>) => {
value.metadata.universe.revision = 'new-universe';
},
(value: ReturnType<typeof input>) => {
value.metadata.bounds.tradeStart++;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.volume++;
},
]) {
const changed = input();
change(changed);
expect(createDatasetV2(changed).manifest.hash).not.toBe(hash);
}
});
test('DST_half_day: labels map only through retained session boundaries', () => {
const dataset = createDatasetV2(input());
expect(dataset.bars.map(b => new Date(b.availableAt).toISOString())).toEqual([
'2024-03-08T21:00:00.000Z',
'2024-03-11T20:00:00.000Z',
'2024-11-29T18:00:00.000Z',
]);
expect(dataset.bars.map(b => new Date(b.intervalStart).toISOString())).toEqual([
'2024-03-08T14:30:00.000Z',
'2024-03-11T13:30:00.000Z',
'2024-11-29T14:30:00.000Z',
]);
const bad = input();
bad.bars[0]!.timestamp = '2024-03-09';
expect(() => createDatasetV2(bad)).toThrow('session mapping');
bad.bars[0]!.timestamp = '2024-02-30';
expect(() => createDatasetV2(bad)).toThrow();
const wrongDate = input();
wrongDate.metadata.calendars[0]!.sessions[0]!.open = Date.parse('2024-03-08T01:00:00Z');
expect(() => createDatasetV2(wrongDate)).toThrow('calendar session');
});
test('missing_vwap: preserve missingness and genuine supplied values without interpolation', () => {
const result = createDatasetV2(input());
expect(result.bars.map(b => b.vwap)).toEqual([null, 101, null]);
expect(result.bars).toHaveLength(3);
expect(result.manifest.qualityPolicy).toBe('reject-invalid-no-interpolation');
});
test('conflicting_duplicate: interval identity cannot be evaded through availability or sequence', () => {
const duplicate = input();
duplicate.bars.push({ ...duplicate.bars[0]!, sourceSequence: 99 });
expect(() => createDatasetV2(duplicate)).toThrow('Duplicate or conflicting');
const conflicting = input();
conflicting.metadata.series[0]!.availability = 'explicit';
conflicting.bars = conflicting.bars.map((bar, i) => ({
...bar,
availableAt: conflicting.metadata.calendars[0]!.sessions[i]!.close,
}));
conflicting.bars.push({
...conflicting.bars[0]!,
volume: 7,
availableAt: conflicting.bars[0]!.availableAt! + 1,
sourceSequence: 100,
});
expect(() => createDatasetV2(conflicting)).toThrow('Duplicate or conflicting');
const sequence = input();
sequence.bars[1]!.sourceSequence = 0;
expect(() => createDatasetV2(sequence)).toThrow('source sequence');
});
test('future_suffix_mutation: prior available observations and per-series sequence stay identical', () => {
const first = input();
first.metadata.series[0]!.availability = 'explicit';
first.bars = first.bars.map((bar, i) => ({
...bar,
availableAt: first.metadata.calendars[0]!.sessions[i]!.close + 1000,
}));
const last = input().metadata.calendars[0]!.sessions[1]!.close + 1000;
const before = createDatasetV2(first);
const changed = structuredClone(first);
changed.bars[2]!.volume = 9_000_000;
changed.bars[2]!.close = 109;
const after = createDatasetV2(changed);
expect(after.manifest.hash).not.toBe(before.manifest.hash);
expect(after.bars.filter(bar => bar.availableAt <= last)).toEqual(
before.bars.filter(bar => bar.availableAt <= last)
);
expect(before.bars.filter(bar => bar.availableAt <= last - 1)).toHaveLength(1);
expect(before.manifest.bounds.warmupStart).toBeLessThan(before.manifest.bounds.tradeStart);
expect(
before.bars.filter(bar => bar.availableAt < before.manifest.bounds.tradeStart)
).toHaveLength(1);
});
test('detaches and deeply freezes every nested value; untrusted mutation never uses cached validation', () => {
const source = input(),
dataset = createDatasetV2(source);
function frozen(value: unknown): void {
if (value && typeof value === 'object') {
expect(Object.isFrozen(value)).toBe(true);
for (const child of Object.values(value)) {
frozen(child);
}
}
}
frozen(dataset);
expect(validateDatasetV2(dataset)).toBe(dataset);
source.bars[0]!.volume = 999;
expect(dataset.bars[0]!.volume).toBe(1000);
const tampered = structuredClone(dataset) as Mutable<typeof dataset>;
tampered.bars[0]!.volume++;
expect(() => validateDatasetV2(tampered)).toThrow('hash/content');
expect(() => {
(dataset.bars[0] as Mutable<(typeof dataset.bars)[number]>).volume++;
}).toThrow();
});
test('canonical validation rechecks timing and derived eligibility even with recomputed hash', () => {
const tampered = structuredClone(createDatasetV2(input())) as Mutable<
ReturnType<typeof createDatasetV2>
>;
tampered.bars[0]!.availableAt = tampered.bars[0]!.intervalStart;
const { hash: _hash, ...manifest } = tampered.manifest;
tampered.manifest.hash = createHash('sha256')
.update(JSON.stringify({ manifest, bars: tampered.bars }))
.digest('hex');
expect(() => assertDatasetV2Executable(tampered)).toThrow('availability');
const changed = structuredClone(createDatasetV2(input())) as Mutable<
ReturnType<typeof createDatasetV2>
>;
changed.manifest.eligibility = 'ineligible';
expect(() => validateDatasetV2(changed)).toThrow('derived policy');
});
test('parent hash rejects trailing newline even when the current hash is recomputed', () => {
const tampered = structuredClone(
convertDatasetV1ToV2(legacyFixture(), input().metadata)
) as Mutable<ReturnType<typeof createDatasetV2>>;
tampered.manifest.parentDatasetHash += '\n';
const { hash: _hash, ...manifest } = tampered.manifest;
tampered.manifest.hash = createHash('sha256')
.update(JSON.stringify({ manifest, bars: tampered.bars }))
.digest('hex');
expect(tampered.bars.every(bar => bar.vwap === null)).toBe(true);
expect(() => validateDatasetV2(tampered)).toThrow();
});
test('availability assumptions are retained; explicit input cannot silently default to the close', () => {
const assumed = createDatasetV2(input());
expect(assumed.manifest.limitations.some(s => s.includes('zero data delay'))).toBe(true);
const explicit = input();
explicit.metadata.series[0]!.availability = 'explicit';
expect(() => createDatasetV2(explicit)).toThrow('requires availableAt');
const early = input();
early.bars[0]!.availableAt = early.metadata.calendars[0]!.sessions[0]!.close - 1;
expect(() => createDatasetV2(early)).toThrow('availability');
const lateAssumption = input();
lateAssumption.bars[0]!.availableAt =
lateAssumption.metadata.calendars[0]!.sessions[0]!.close + 1;
expect(() => createDatasetV2(lateAssumption)).toThrow('availability');
});
test('unknown coverage is exploratory; known unsupported actions and adjusted execution fail closed', () => {
expect(assertDatasetV2Executable(createDatasetV2(input())).manifest.eligibility).toBe(
'eligible'
);
const unknown = input();
unknown.metadata.corporateActions[0]!.status = 'unknown';
expect(assertDatasetV2Executable(createDatasetV2(unknown)).manifest.eligibility).toBe(
'exploratory'
);
const action = input();
action.metadata.corporateActions[0]!.status = 'known-actions';
action.metadata.corporateActions[0]!.actions.push({
effectiveAt: action.metadata.bounds.tradeStart,
kind: 'split',
reference: 'test-split',
});
expect(() => assertDatasetV2Executable(createDatasetV2(action))).toThrow(
'Unsupported corporate actions'
);
const adjusted = input();
adjusted.metadata.series[0]!.adjustment = 'provider-adjusted';
expect(() => assertDatasetV2Executable(createDatasetV2(adjusted))).toThrow('Adjusted prices');
const universe = input();
universe.metadata.universe.selection = 'current-constituents';
expect(createDatasetV2(universe).manifest.eligibility).toBe('exploratory');
const future = input();
future.metadata.universe.asOf = future.metadata.bounds.tradeEnd;
expect(() => createDatasetV2(future)).toThrow('universe/as-of');
});
test('one execution series per instrument; adjusted feature series cannot duplicate liquidity selection', () => {
const value = input();
value.metadata.series.push({
...value.metadata.series[0]!,
id: 'feature',
adjustment: 'provider-adjusted',
});
value.bars.push(...value.bars.map(bar => ({ ...bar, seriesId: 'feature' })));
const dataset = createDatasetV2(value);
expect(dataset.manifest.executionSeries).toHaveLength(1);
expect(dataset.manifest.eligibility).toBe('eligible');
value.metadata.executionSeries.push({ instrumentId: 'A.US', seriesId: 'feature' });
expect(() => createDatasetV2(value)).toThrow('execution instrument');
const missing = input();
missing.metadata.executionSeries[0]!.seriesId = 'missing';
expect(() => createDatasetV2(missing)).toThrow('exactly one');
});
test('intraday explicit start/end semantics agree, partial session bars reject', () => {
const start = input();
start.metadata.series[0]!.interval = '1h';
start.metadata.series[0]!.timestamp = 'interval-start';
start.bars = start.bars.map((bar, i) => ({
...bar,
timestamp: start.metadata.calendars[0]!.sessions[i]!.open,
}));
const end = structuredClone(start);
end.metadata.series[0]!.timestamp = 'interval-end';
end.bars = end.bars.map(bar => ({ ...bar, timestamp: Number(bar.timestamp) + 3_600_000 }));
expect(createDatasetV2(start).bars).toEqual(createDatasetV2(end).bars);
const overlapping = structuredClone(start);
overlapping.bars.push({
...overlapping.bars[0]!,
sourceSequence: 99,
timestamp: Number(overlapping.bars[0]!.timestamp) + 30_000,
});
expect(() => createDatasetV2(overlapping)).toThrow('Overlapping intervals');
start.bars[2]!.timestamp = start.metadata.calendars[0]!.sessions[2]!.close - 30 * 60_000;
expect(() => createDatasetV2(start)).toThrow('session interval');
});
test('terminal boundary retains the completed interval, not a new interval or decision permission', () => {
const value = input(),
dataset = createDatasetV2(value);
expect(dataset.bars.at(-1)!.intervalEnd).toBe(dataset.manifest.bounds.tradeEnd);
expect(dataset.bars.at(-1)!.availableAt).toBe(dataset.manifest.bounds.tradeEnd);
value.metadata.bounds.tradeEnd--;
expect(() => createDatasetV2(value)).toThrow('session interval');
});
test('rejects invalid bars, uncovered ranges, identity mappings and malformed metadata', () => {
for (const change of [
(value: ReturnType<typeof input>) => {
value.metadata.series[0]!.calendarId = 'unknown';
},
(value: ReturnType<typeof input>) => {
value.metadata.series[0]!.venue = 'guessed';
},
(value: ReturnType<typeof input>) => {
value.metadata.calendars[0]!.endDate = '2024-11-01';
},
(value: ReturnType<typeof input>) => {
value.metadata.bounds.tradeEnd = value.metadata.bounds.tradeStart;
},
(value: ReturnType<typeof input>) => {
value.metadata.corporateActions[0]!.end = value.metadata.bounds.tradeStart;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.close = NaN;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.volume = -1;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.sourceSequence = Number.MAX_SAFE_INTEGER + 1;
},
]) {
const value = input();
change(value);
expect(() => createDatasetV2(value)).toThrow();
}
});
});