diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index c6632a03..b7d77a50 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -240,6 +240,9 @@ jobs: node tests/sa1_demo_validation.mjs node tests/sa1_sizing_contracts_validation.mjs node tests/naming_canonical_validation.mjs + node tests/sa2_demo_validation.mjs + node tests/sa2_orders_fills_validation.mjs + node tests/sa2_deployable_capital_validation.mjs node tests/strategy_health_snapshot_extract_validation.mjs node tests/adaptive_selection_snapshot_extract_validation.mjs node tests/binance_private_scope_extract_validation.mjs diff --git a/schemas/qsl-authoritative-orders-fills.v1.schema.json b/schemas/qsl-authoritative-orders-fills.v1.schema.json new file mode 100644 index 00000000..0a858e01 --- /dev/null +++ b/schemas/qsl-authoritative-orders-fills.v1.schema.json @@ -0,0 +1,729 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://quantstrategylab.github.io/QuantRuntimeSettings/schemas/qsl-authoritative-orders-fills.v1.schema.json", + "title": "QSL Authoritative Orders, Fills, Cutoff Open Orders & ORDER-UNKNOWN v1 (C-SA-25)", + "description": "Broker-agnostic authoritative order submission, fill/execution, cutoff open-order, and restart-persistent ORDER-UNKNOWN symbol lock contract (C-SA-25). Strictly separates broker from paper/live environment, binds keys to (broker, environment, account), enforces 256/512/2048 caps and proven completeness for empty domains/K_pend release, preserves null fees and non-USD unavailability, and blocks raw brokerage account IDs and private locators.", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "status", + "reason", + "broker", + "environment", + "account", + "account_binding", + "as_of", + "evaluated_at", + "domains", + "orders", + "executions", + "order_unknown_locks", + "order_unknown_symbols", + "summary", + "origin", + "source_class", + "evidence_ref" + ], + "properties": { + "schema_version": { "const": "qsl.authoritative_orders_fills.v1" }, + "status": { "enum": ["ok", "blocked", "unavailable"] }, + "reason": { "$ref": "#/$defs/nullableSafeString" }, + "broker": { "$ref": "#/$defs/brokerSlug" }, + "environment": { "$ref": "#/$defs/orderEnvironment" }, + "account": { "$ref": "#/$defs/safeAccountRef" }, + "account_binding": { + "type": "object", + "additionalProperties": false, + "required": ["broker", "environment", "account", "binding_key"], + "properties": { + "broker": { "$ref": "#/$defs/brokerSlug" }, + "environment": { "$ref": "#/$defs/orderEnvironment" }, + "account": { "$ref": "#/$defs/safeAccountRef" }, + "binding_key": { "$ref": "#/$defs/safeBindingKey" } + } + }, + "as_of": { "$ref": "#/$defs/nullableUtcTime" }, + "evaluated_at": { "$ref": "#/$defs/utcTime" }, + "domains": { + "type": "object", + "additionalProperties": false, + "required": ["submissions", "executions", "cutoff_open_orders"], + "properties": { + "submissions": { + "allOf": [ + { "$ref": "#/$defs/domainEnvelopeBase" }, + { + "properties": { + "domain": { "const": "submissions" }, + "records": { + "type": "array", + "maxItems": 2048, + "items": { "$ref": "#/$defs/submissionRecord" } + } + } + } + ] + }, + "executions": { + "allOf": [ + { "$ref": "#/$defs/domainEnvelopeBase" }, + { + "properties": { + "domain": { "const": "executions" }, + "records": { + "type": "array", + "maxItems": 2048, + "items": { "$ref": "#/$defs/executionRecord" } + } + } + } + ] + }, + "cutoff_open_orders": { + "allOf": [ + { "$ref": "#/$defs/domainEnvelopeBase" }, + { + "properties": { + "domain": { "const": "cutoff_open_orders" }, + "records": { + "type": "array", + "maxItems": 2048, + "items": { "$ref": "#/$defs/cutoffOpenOrderRecord" } + } + } + } + ] + } + } + }, + "orders": { + "type": "array", + "maxItems": 4096, + "items": { "$ref": "#/$defs/reconciledOrder" } + }, + "executions": { + "type": "array", + "maxItems": 4096, + "items": { "$ref": "#/$defs/executionRecord" } + }, + "order_unknown_locks": { + "type": "array", + "maxItems": 512, + "items": { "$ref": "#/$defs/orderUnknownLock" } + }, + "order_unknown_symbols": { + "type": "array", + "maxItems": 512, + "items": { "$ref": "#/$defs/symbol" } + }, + "summary": { + "type": "object", + "additionalProperties": false, + "required": [ + "k_pend_usd", + "k_pend_release_allowed", + "empty_open_orders_proven", + "order_unknown_active", + "currencies_present", + "currency_coercion", + "fx_inferred" + ], + "properties": { + "k_pend_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "k_pend_release_allowed": { "type": "boolean" }, + "empty_open_orders_proven": { "type": "boolean" }, + "order_unknown_active": { "type": "boolean" }, + "currencies_present": { + "type": "array", + "items": { "$ref": "#/$defs/currency" } + }, + "currency_coercion": { "const": "prohibited" }, + "fx_inferred": { "const": false } + } + }, + "origin": { "enum": ["synthetic", "production"] }, + "source_class": { "$ref": "#/$defs/sourceClass" }, + "evidence_ref": { "$ref": "#/$defs/evidenceRef" } + }, + "allOf": [ + { + "if": { + "properties": { + "summary": { + "properties": { "order_unknown_active": { "const": true } }, + "required": ["order_unknown_active"] + } + }, + "required": ["summary"] + }, + "then": { + "properties": { + "summary": { + "properties": { "k_pend_release_allowed": { "const": false } } + } + } + } + }, + { + "if": { + "properties": { + "summary": { + "properties": { "k_pend_release_allowed": { "const": true } }, + "required": ["k_pend_release_allowed"] + } + }, + "required": ["summary"] + }, + "then": { + "properties": { + "order_unknown_locks": { "maxItems": 0 }, + "order_unknown_symbols": { "maxItems": 0 }, + "domains": { + "properties": { + "cutoff_open_orders": { + "properties": { + "domain_capability": { "const": "supported" }, + "k_pend_release_allowed": { "const": true }, + "truncated": { "const": false }, + "completeness": { "const": "complete" } + } + } + } + } + } + } + } + ], + "$defs": { + "brokerSlug": { + "type": "string", + "enum": ["schwab", "firstrade", "ibkr", "longbridge", "binance"] + }, + "orderEnvironment": { + "type": "string", + "enum": ["live", "paper"] + }, + "orderState": { + "type": "string", + "enum": [ + "SUBMITTED", + "ACCEPTED", + "PARTIAL_FILL", + "FILLED", + "PARTIAL_CANCEL", + "CANCELED", + "REJECTED", + "ORDER_UNKNOWN" + ] + }, + "orderSide": { + "type": "string", + "enum": ["BUY", "SELL"] + }, + "domainName": { + "type": "string", + "enum": ["submissions", "executions", "cutoff_open_orders"] + }, + "domainCapability": { + "type": "string", + "enum": ["supported", "unsupported"] + }, + "completenessStatus": { + "type": "string", + "enum": ["complete", "incomplete", "unknown", "unsupported"] + }, + "sourceClass": { + "type": "string", + "enum": [ + "synthetic", + "historical_reconstruction", + "decision_time_market", + "operator_declared", + "authorized_operational", + "paper_broker", + "authorized_live_broker" + ] + }, + "currency": { + "type": "string", + "pattern": "^[A-Z]{3,10}$", + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" } + ] + } + }, + "nullableCurrency": { + "anyOf": [{ "$ref": "#/$defs/currency" }, { "type": "null" }] + }, + "symbol": { + "type": "string", + "pattern": "^[A-Z0-9][A-Z0-9./_-]{0,63}$", + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" } + ] + } + }, + "utcTime": { + "type": "string", + "format": "date-time", + "pattern": "Z$" + }, + "nullableUtcTime": { + "anyOf": [{ "$ref": "#/$defs/utcTime" }, { "type": "null" }] + }, + "decimal": { + "type": "string", + "pattern": "^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$" + }, + "nullableDecimal": { + "anyOf": [{ "$ref": "#/$defs/decimal" }, { "type": "null" }] + }, + "nonNegativeDecimal": { + "type": "string", + "pattern": "^(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$" + }, + "nullableNonNegativeDecimal": { + "anyOf": [{ "$ref": "#/$defs/nonNegativeDecimal" }, { "type": "null" }] + }, + "positiveDecimal": { + "type": "string", + "pattern": "^(?:0\\.[0-9]*[1-9][0-9]*|[1-9][0-9]*(?:\\.[0-9]+)?)$" + }, + "nullablePositiveDecimal": { + "anyOf": [{ "$ref": "#/$defs/positiveDecimal" }, { "type": "null" }] + }, + "safeString": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "\\S", + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" }, + { "pattern": "(?:://|^[A-Za-z][A-Za-z0-9+.-]*:/|(?:^|[\\s:(\\[\"'(])(?:[A-Za-z]:\\\\|~/|/(?:[Uu]sers|[Hh]ome|[Tt]mp|[Vv]ar|[Ee]tc|[Oo]pt|[Mm]nt)/)|\\.\\.[/\\\\]|[?#]|&(?:[Xx]-[Gg]oog-|[Ss]ignature|[Ee]xpires|[Aa][Ww][Ss][Aa]ccess[Kk]ey[Ii]d|token|sig|auth)=)" } + ] + } + }, + "nullableSafeString": { + "anyOf": [{ "$ref": "#/$defs/safeString" }, { "type": "null" }] + }, + "safeId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$", + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" }, + { "pattern": "(?:://|^[A-Za-z][A-Za-z0-9+.-]*:/)" } + ] + } + }, + "nullableSafeId": { + "anyOf": [{ "$ref": "#/$defs/safeId" }, { "type": "null" }] + }, + "safeAccountRef": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "anyOf": [ + { "pattern": "^(schwab|firstrade|ibkr|longbridge|binance):(live|paper):[a-z0-9][a-z0-9_-]{0,31}$" }, + { "pattern": "^[a-z0-9][a-z0-9_-]{0,31}$" } + ], + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" }, + { "pattern": "(?:://|^[A-Za-z][A-Za-z0-9+.-]*:/)" } + ] + } + }, + "safeBindingKey": { + "type": "string", + "pattern": "^(schwab|firstrade|ibkr|longbridge|binance)\\|(live|paper)\\|[a-z0-9][a-z0-9:_-]{0,63}$", + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" } + ] + } + }, + "executionRef": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "anyOf": [ + { "pattern": "^[a-f0-9]{64}$" }, + { "$ref": "#/$defs/safeId" } + ] + }, + "nullableExecutionRef": { + "anyOf": [{ "$ref": "#/$defs/executionRef" }, { "type": "null" }] + }, + "evidenceRef": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "anyOf": [ + { "pattern": "^sha256:[a-f0-9]{64}$" }, + { "$ref": "#/$defs/safeId" } + ] + }, + "queryTarget": { + "type": "object", + "additionalProperties": false, + "required": ["by", "broker", "environment", "account", "client_order_id", "broker_order_id"], + "properties": { + "by": { "enum": ["broker_order_id", "client_order_tuple"] }, + "broker": { "$ref": "#/$defs/brokerSlug" }, + "environment": { "$ref": "#/$defs/orderEnvironment" }, + "account": { "$ref": "#/$defs/safeAccountRef" }, + "client_order_id": { "$ref": "#/$defs/safeId" }, + "broker_order_id": { "$ref": "#/$defs/nullableSafeId" } + }, + "allOf": [ + { + "if": { "properties": { "by": { "const": "broker_order_id" } }, "required": ["by"] }, + "then": { "properties": { "broker_order_id": { "$ref": "#/$defs/safeId" } } } + }, + { + "if": { "properties": { "by": { "const": "client_order_tuple" } }, "required": ["by"] }, + "then": { "properties": { "broker_order_id": { "type": "null" } } } + } + ] + }, + "domainEnvelopeBase": { + "type": "object", + "additionalProperties": false, + "required": [ + "domain", + "domain_capability", + "as_of", + "source", + "scope", + "native_currency", + "currencies_present", + "cap", + "count", + "truncated", + "completeness", + "empty_domain_proven", + "k_pend_release_allowed", + "records" + ], + "properties": { + "domain": { "$ref": "#/$defs/domainName" }, + "domain_capability": { "$ref": "#/$defs/domainCapability" }, + "as_of": { "$ref": "#/$defs/nullableUtcTime" }, + "source": { "$ref": "#/$defs/safeString" }, + "scope": { "$ref": "#/$defs/safeString" }, + "native_currency": { "$ref": "#/$defs/nullableCurrency" }, + "currencies_present": { + "type": "array", + "items": { "$ref": "#/$defs/currency" } + }, + "cap": { + "anyOf": [ + { "enum": [256, 512, 2048] }, + { "type": "null" } + ] + }, + "count": { "type": ["integer", "null"], "minimum": 0 }, + "truncated": { "type": ["boolean", "null"] }, + "completeness": { "$ref": "#/$defs/completenessStatus" }, + "empty_domain_proven": { "type": "boolean" }, + "k_pend_release_allowed": { "type": "boolean" }, + "records": { "type": "array" } + }, + "allOf": [ + { + "if": { "properties": { "domain_capability": { "const": "unsupported" } }, "required": ["domain_capability"] }, + "then": { + "properties": { + "cap": { "type": "null" }, + "count": { "type": "null" }, + "truncated": { "type": "null" }, + "completeness": { "enum": ["unsupported", "unknown"] }, + "empty_domain_proven": { "const": false }, + "k_pend_release_allowed": { "const": false }, + "records": { "maxItems": 0 } + } + } + }, + { + "if": { "properties": { "domain_capability": { "const": "supported" } }, "required": ["domain_capability"] }, + "then": { + "properties": { + "as_of": { "$ref": "#/$defs/utcTime" }, + "cap": { "enum": [256, 512, 2048] }, + "count": { "type": "integer", "minimum": 0 }, + "truncated": { "type": "boolean" }, + "completeness": { "enum": ["complete", "incomplete", "unknown"] } + } + } + }, + { + "if": { "properties": { "empty_domain_proven": { "const": true } }, "required": ["empty_domain_proven"] }, + "then": { + "properties": { + "domain_capability": { "const": "supported" }, + "truncated": { "const": false }, + "completeness": { "const": "complete" }, + "count": { "const": 0 }, + "records": { "maxItems": 0 } + } + } + }, + { + "if": { + "anyOf": [ + { "properties": { "truncated": { "const": true } }, "required": ["truncated"] }, + { "properties": { "completeness": { "enum": ["incomplete", "unknown", "unsupported"] } }, "required": ["completeness"] } + ] + }, + "then": { + "properties": { + "empty_domain_proven": { "const": false }, + "k_pend_release_allowed": { "const": false } + } + } + } + ] + }, + "submissionRecord": { + "type": "object", + "additionalProperties": false, + "required": [ + "broker", + "environment", + "account", + "client_order_id", + "broker_order_id", + "symbol", + "side", + "state", + "qty_submitted", + "limit_price", + "currency", + "notional_usd", + "fee_native", + "fee_currency", + "fee_usd", + "usd_basis_qualified", + "submitted_at", + "evidence_ref" + ], + "properties": { + "broker": { "$ref": "#/$defs/brokerSlug" }, + "environment": { "$ref": "#/$defs/orderEnvironment" }, + "account": { "$ref": "#/$defs/safeAccountRef" }, + "client_order_id": { "$ref": "#/$defs/safeId" }, + "broker_order_id": { "$ref": "#/$defs/nullableSafeId" }, + "symbol": { "$ref": "#/$defs/symbol" }, + "side": { "$ref": "#/$defs/orderSide" }, + "state": { "$ref": "#/$defs/orderState" }, + "qty_submitted": { "$ref": "#/$defs/positiveDecimal" }, + "limit_price": { "$ref": "#/$defs/nullablePositiveDecimal" }, + "currency": { "$ref": "#/$defs/currency" }, + "notional_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "fee_native": { "$ref": "#/$defs/nullableDecimal" }, + "fee_currency": { "$ref": "#/$defs/nullableCurrency" }, + "fee_usd": { "$ref": "#/$defs/nullableDecimal" }, + "usd_basis_qualified": { "type": "boolean" }, + "submitted_at": { "$ref": "#/$defs/utcTime" }, + "evidence_ref": { "$ref": "#/$defs/evidenceRef" } + } + }, + "executionRecord": { + "type": "object", + "additionalProperties": false, + "required": [ + "broker", + "environment", + "account", + "execution_ref", + "report_ref", + "client_order_id", + "broker_order_id", + "symbol", + "side", + "qty", + "price", + "currency", + "notional_usd", + "fee_native", + "fee_currency", + "fee_usd", + "usd_basis_qualified", + "executed_at", + "evidence_ref" + ], + "properties": { + "broker": { "$ref": "#/$defs/brokerSlug" }, + "environment": { "$ref": "#/$defs/orderEnvironment" }, + "account": { "$ref": "#/$defs/safeAccountRef" }, + "execution_ref": { "$ref": "#/$defs/executionRef" }, + "report_ref": { "$ref": "#/$defs/nullableExecutionRef" }, + "client_order_id": { "$ref": "#/$defs/nullableSafeId" }, + "broker_order_id": { "$ref": "#/$defs/nullableSafeId" }, + "symbol": { "$ref": "#/$defs/symbol" }, + "side": { "$ref": "#/$defs/orderSide" }, + "qty": { "$ref": "#/$defs/positiveDecimal" }, + "price": { "$ref": "#/$defs/nonNegativeDecimal" }, + "currency": { "$ref": "#/$defs/currency" }, + "notional_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "fee_native": { "$ref": "#/$defs/nullableDecimal" }, + "fee_currency": { "$ref": "#/$defs/nullableCurrency" }, + "fee_usd": { "$ref": "#/$defs/nullableDecimal" }, + "usd_basis_qualified": { "type": "boolean" }, + "executed_at": { "$ref": "#/$defs/nullableUtcTime" }, + "evidence_ref": { "$ref": "#/$defs/evidenceRef" } + } + }, + "cutoffOpenOrderRecord": { + "type": "object", + "additionalProperties": false, + "required": [ + "broker", + "environment", + "account", + "client_order_id", + "broker_order_id", + "symbol", + "side", + "state", + "qty_submitted", + "qty_filled", + "qty_canceled", + "qty_remaining", + "limit_price", + "currency", + "k_pend_usd", + "reserved_fee_usd", + "usd_basis_qualified", + "as_of", + "evidence_ref" + ], + "properties": { + "broker": { "$ref": "#/$defs/brokerSlug" }, + "environment": { "$ref": "#/$defs/orderEnvironment" }, + "account": { "$ref": "#/$defs/safeAccountRef" }, + "client_order_id": { "$ref": "#/$defs/safeId" }, + "broker_order_id": { "$ref": "#/$defs/nullableSafeId" }, + "symbol": { "$ref": "#/$defs/symbol" }, + "side": { "$ref": "#/$defs/orderSide" }, + "state": { "$ref": "#/$defs/orderState" }, + "qty_submitted": { "$ref": "#/$defs/positiveDecimal" }, + "qty_filled": { "$ref": "#/$defs/nonNegativeDecimal" }, + "qty_canceled": { "$ref": "#/$defs/nonNegativeDecimal" }, + "qty_remaining": { "$ref": "#/$defs/nonNegativeDecimal" }, + "limit_price": { "$ref": "#/$defs/nullablePositiveDecimal" }, + "currency": { "$ref": "#/$defs/currency" }, + "k_pend_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "reserved_fee_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "usd_basis_qualified": { "type": "boolean" }, + "as_of": { "$ref": "#/$defs/utcTime" }, + "evidence_ref": { "$ref": "#/$defs/evidenceRef" } + } + }, + "reconciledOrder": { + "type": "object", + "additionalProperties": false, + "required": [ + "broker", + "environment", + "account", + "client_order_id", + "broker_order_id", + "symbol", + "side", + "state", + "currency", + "qty_submitted", + "qty_filled", + "qty_canceled", + "qty_remaining", + "limit_price", + "avg_fill_price", + "fee_native", + "fee_currency", + "fee_usd", + "notional_usd", + "k_pend_usd", + "usd_basis_qualified", + "query_target", + "updated_at", + "evidence_ref" + ], + "properties": { + "broker": { "$ref": "#/$defs/brokerSlug" }, + "environment": { "$ref": "#/$defs/orderEnvironment" }, + "account": { "$ref": "#/$defs/safeAccountRef" }, + "client_order_id": { "$ref": "#/$defs/safeId" }, + "broker_order_id": { "$ref": "#/$defs/nullableSafeId" }, + "symbol": { "$ref": "#/$defs/symbol" }, + "side": { "$ref": "#/$defs/orderSide" }, + "state": { "$ref": "#/$defs/orderState" }, + "currency": { "$ref": "#/$defs/currency" }, + "qty_submitted": { "$ref": "#/$defs/positiveDecimal" }, + "qty_filled": { "$ref": "#/$defs/nonNegativeDecimal" }, + "qty_canceled": { "$ref": "#/$defs/nonNegativeDecimal" }, + "qty_remaining": { "$ref": "#/$defs/nonNegativeDecimal" }, + "limit_price": { "$ref": "#/$defs/nullablePositiveDecimal" }, + "avg_fill_price": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "fee_native": { "$ref": "#/$defs/nullableDecimal" }, + "fee_currency": { "$ref": "#/$defs/nullableCurrency" }, + "fee_usd": { "$ref": "#/$defs/nullableDecimal" }, + "notional_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "k_pend_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "usd_basis_qualified": { "type": "boolean" }, + "query_target": { + "anyOf": [{ "$ref": "#/$defs/queryTarget" }, { "type": "null" }] + }, + "updated_at": { "$ref": "#/$defs/utcTime" }, + "evidence_ref": { "$ref": "#/$defs/evidenceRef" } + } + }, + "orderUnknownLock": { + "type": "object", + "additionalProperties": false, + "required": [ + "broker", + "environment", + "account", + "symbol", + "client_order_id", + "broker_order_id", + "query_target", + "k_pend_usd", + "locked_at", + "status", + "allow_new_orders", + "query_before_retry_required", + "clear_condition" + ], + "properties": { + "broker": { "$ref": "#/$defs/brokerSlug" }, + "environment": { "$ref": "#/$defs/orderEnvironment" }, + "account": { "$ref": "#/$defs/safeAccountRef" }, + "symbol": { "$ref": "#/$defs/symbol" }, + "client_order_id": { "$ref": "#/$defs/safeId" }, + "broker_order_id": { "$ref": "#/$defs/nullableSafeId" }, + "query_target": { "$ref": "#/$defs/queryTarget" }, + "k_pend_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "locked_at": { "$ref": "#/$defs/utcTime" }, + "status": { "const": "locked" }, + "allow_new_orders": { "const": false }, + "query_before_retry_required": { "const": true }, + "clear_condition": { "const": "definitive_terminal_broker_evidence" } + } + } + } +} diff --git a/schemas/qsl-deployable-capital-sizing.v1.schema.json b/schemas/qsl-deployable-capital-sizing.v1.schema.json new file mode 100644 index 00000000..f8d2c5b7 --- /dev/null +++ b/schemas/qsl-deployable-capital-sizing.v1.schema.json @@ -0,0 +1,437 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://quantstrategylab.github.io/QuantRuntimeSettings/schemas/qsl-deployable-capital-sizing.v1.schema.json", + "title": "QSL Deployable Capital & Whole-Share Order Sizing v1 (C-SA-Q21)", + "description": "Exact-decimal deployable capital (C_inv, C_avail, R_cash, K_pend), whole-share ideal targets, fee-and-collar-constrained buyable share rounding, unblocked reductions, ORDER-UNKNOWN symbol buy blocks, B_min,tier workable bankroll checks, and rho_order diagnostics (C-SA-Q21).", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "status", + "reason", + "account_id", + "broker", + "environment", + "currency", + "currency_coercion", + "fx_inferred", + "margin_enabled", + "h_usd", + "kelly_applied", + "live_trading_enabled", + "stop_loss_return_enabled", + "fractional_shares", + "evaluated_at", + "capital", + "fee_schedule", + "order_unknown_symbols", + "orders", + "b_min_tier", + "origin", + "source_class", + "evidence_ref" + ], + "properties": { + "schema_version": { "const": "qsl.deployable_capital_sizing.v1" }, + "status": { "enum": ["available", "unavailable"] }, + "reason": { "$ref": "#/$defs/nullableSafeString" }, + "account_id": { + "anyOf": [{ "$ref": "#/$defs/safeAccountRef" }, { "type": "null" }] + }, + "broker": { + "anyOf": [{ "$ref": "#/$defs/brokerSlug" }, { "type": "null" }] + }, + "environment": { "enum": ["live", "paper", null] }, + "currency": { "const": "USD" }, + "currency_coercion": { "const": "prohibited" }, + "fx_inferred": { "const": false }, + "margin_enabled": { "const": false }, + "h_usd": { "const": "0" }, + "kelly_applied": { "const": false }, + "live_trading_enabled": { "const": false }, + "stop_loss_return_enabled": { "const": false }, + "fractional_shares": { "const": "prohibited" }, + "evaluated_at": { "$ref": "#/$defs/utcTime" }, + "capital": { + "type": "object", + "additionalProperties": false, + "required": [ + "equity_usd", + "c_inv_usd", + "cash_settled_usd", + "proceeds_eligible_usd", + "r_cash_usd", + "k_pend_usd", + "k_pend_release_allowed", + "raw_deployable_cash_usd", + "c_avail_usd", + "total_buy_commit_usd", + "remaining_deployable_cash_usd" + ], + "properties": { + "equity_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "c_inv_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "cash_settled_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "proceeds_eligible_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "r_cash_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "k_pend_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "k_pend_release_allowed": { "type": "boolean" }, + "raw_deployable_cash_usd": { "$ref": "#/$defs/nullableDecimal" }, + "c_avail_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "total_buy_commit_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "remaining_deployable_cash_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" } + } + }, + "fee_schedule": { + "type": "object", + "additionalProperties": false, + "required": [ + "status", + "provenance", + "c_min_usd", + "c_per_share_usd", + "c_reg", + "b_exec_usd", + "oi_cost_3_resolved", + "oi_cost_4_resolved" + ], + "properties": { + "status": { "enum": ["available", "unavailable"] }, + "provenance": { + "enum": ["synthetic_fixture", "research_prereg_amended", "venue_observed", null] + }, + "c_min_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "c_per_share_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "c_reg": { + "anyOf": [ + { "$ref": "#/$defs/nonNegativeDecimal" }, + { + "type": "object", + "additionalProperties": false, + "required": ["fixed_usd", "per_share_usd", "notional_rate"], + "properties": { + "fixed_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "per_share_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "notional_rate": { "$ref": "#/$defs/nonNegativeDecimal" } + } + }, + { "type": "null" } + ] + }, + "b_exec_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "oi_cost_3_resolved": { "type": "boolean" }, + "oi_cost_4_resolved": { "type": "boolean" } + } + }, + "order_unknown_symbols": { + "type": "array", + "maxItems": 512, + "items": { "$ref": "#/$defs/symbol" } + }, + "orders": { + "type": "array", + "maxItems": 128, + "items": { "$ref": "#/$defs/orderSizingItem" } + }, + "b_min_tier": { + "type": "object", + "additionalProperties": false, + "required": [ + "status", + "workable", + "bankroll_w_usd", + "c_fixed_ann_usd", + "expected_excess_growth_ann_usd", + "threshold_ratio", + "friction_ratio", + "reason" + ], + "properties": { + "status": { "enum": ["available", "unavailable"] }, + "workable": { "type": ["boolean", "null"] }, + "bankroll_w_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "c_fixed_ann_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "expected_excess_growth_ann_usd": { "$ref": "#/$defs/nullableDecimal" }, + "threshold_ratio": { "const": "0.1" }, + "friction_ratio": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "reason": { "$ref": "#/$defs/nullableSafeString" } + } + }, + "origin": { "enum": ["synthetic", "production"] }, + "source_class": { "$ref": "#/$defs/sourceClass" }, + "evidence_ref": { "$ref": "#/$defs/evidenceRef" } + }, + "allOf": [ + { + "if": { "properties": { "status": { "const": "available" } }, "required": ["status"] }, + "then": { + "properties": { + "capital": { + "properties": { + "equity_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "c_inv_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "cash_settled_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "proceeds_eligible_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "r_cash_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "k_pend_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "raw_deployable_cash_usd": { "$ref": "#/$defs/nullableDecimal" }, + "c_avail_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "total_buy_commit_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "remaining_deployable_cash_usd": { "$ref": "#/$defs/nonNegativeDecimal" } + } + }, + "fee_schedule": { + "properties": { + "status": { "const": "available" }, + "provenance": { "enum": ["synthetic_fixture", "research_prereg_amended", "venue_observed"] }, + "oi_cost_3_resolved": { "const": true } + } + } + } + } + }, + { + "if": { + "properties": { + "status": { "const": "available" }, + "capital": { + "properties": { "k_pend_usd": { "type": "string" } }, + "required": ["k_pend_usd"] + } + }, + "required": ["status", "capital"] + }, + "then": { + "properties": { + "capital": { + "properties": { + "raw_deployable_cash_usd": { "$ref": "#/$defs/decimal" } + } + } + } + } + }, + { + "if": { + "properties": { + "status": { "const": "available" }, + "capital": { + "properties": { "k_pend_usd": { "type": "null" } }, + "required": ["k_pend_usd"] + } + }, + "required": ["status", "capital"] + }, + "then": { + "properties": { + "capital": { + "properties": { + "k_pend_release_allowed": { "const": false }, + "raw_deployable_cash_usd": { "type": "null" }, + "c_avail_usd": { "const": "0" }, + "total_buy_commit_usd": { "const": "0" }, + "remaining_deployable_cash_usd": { "const": "0" } + } + } + } + } + }, + { + "if": { "properties": { "status": { "const": "unavailable" } }, "required": ["status"] }, + "then": { + "properties": { + "capital": { + "properties": { + "c_avail_usd": { "type": "null" } + } + }, + "orders": { "maxItems": 0 } + } + } + } + ], + "$defs": { + "brokerSlug": { + "type": "string", + "enum": ["schwab", "firstrade", "ibkr", "longbridge", "binance"] + }, + "sourceClass": { + "type": "string", + "enum": [ + "synthetic", + "historical_reconstruction", + "decision_time_market", + "operator_declared", + "authorized_operational", + "paper_broker", + "authorized_live_broker" + ] + }, + "symbol": { + "type": "string", + "pattern": "^[A-Z0-9][A-Z0-9./_-]{0,63}$", + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" } + ] + } + }, + "utcTime": { + "type": "string", + "format": "date-time", + "pattern": "Z$" + }, + "decimal": { + "type": "string", + "pattern": "^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$" + }, + "nullableDecimal": { + "anyOf": [{ "$ref": "#/$defs/decimal" }, { "type": "null" }] + }, + "nonNegativeDecimal": { + "type": "string", + "pattern": "^(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$" + }, + "nullableNonNegativeDecimal": { + "anyOf": [{ "$ref": "#/$defs/nonNegativeDecimal" }, { "type": "null" }] + }, + "positiveDecimal": { + "type": "string", + "pattern": "^(?:0\\.[0-9]*[1-9][0-9]*|[1-9][0-9]*(?:\\.[0-9]+)?)$" + }, + "nullablePositiveDecimal": { + "anyOf": [{ "$ref": "#/$defs/positiveDecimal" }, { "type": "null" }] + }, + "nonNegativeIntegerDecimal": { + "type": "string", + "pattern": "^(?:0|[1-9][0-9]*)$" + }, + "integerDecimal": { + "type": "string", + "pattern": "^-?(?:0|[1-9][0-9]*)$" + }, + "safeString": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "\\S", + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" }, + { "pattern": "(?:://|^[A-Za-z][A-Za-z0-9+.-]*:/|(?:^|[\\s:(\\[\"'(])(?:[A-Za-z]:\\\\|~/|/(?:[Uu]sers|[Hh]ome|[Tt]mp|[Vv]ar|[Ee]tc|[Oo]pt|[Mm]nt)/)|\\.\\.[/\\\\]|[?#]|&(?:[Xx]-[Gg]oog-|[Ss]ignature|[Ee]xpires|[Aa][Ww][Ss][Aa]ccess[Kk]ey[Ii]d|token|sig|auth)=)" } + ] + } + }, + "nullableSafeString": { + "anyOf": [{ "$ref": "#/$defs/safeString" }, { "type": "null" }] + }, + "safeAccountRef": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "anyOf": [ + { "pattern": "^(schwab|firstrade|ibkr|longbridge|binance):(live|paper):[a-z0-9][a-z0-9_-]{0,31}$" }, + { "pattern": "^[a-z0-9][a-z0-9_-]{0,31}$" } + ], + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" }, + { "pattern": "(?:://|^[A-Za-z][A-Za-z0-9+.-]*:/)" } + ] + } + }, + "evidenceRef": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "anyOf": [ + { "pattern": "^sha256:[a-f0-9]{64}$" }, + { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$", + "not": { + "anyOf": [ + { "pattern": "(?:^|[^A-Za-z0-9])[dD]?[uU][0-9]{5,}(?:$|[^A-Za-z0-9])" }, + { "pattern": "[0-9](?:[-_. ]*[0-9]){5}" }, + { "pattern": "(?:://|^[A-Za-z][A-Za-z0-9+.-]*:/)" } + ] + } + } + ] + }, + "orderSizingItem": { + "type": "object", + "additionalProperties": false, + "required": [ + "symbol", + "price_ref", + "price_lim", + "w_target", + "w_cur", + "q_pre", + "q_ideal", + "delta_q_raw", + "delta_q_final", + "delta_q_buy", + "delta_q_sell", + "q_target", + "action", + "band_suppressed", + "emergency_bypass_applied", + "buy_blocked_reason", + "est_notional_ref_usd", + "est_worst_case_notional_usd", + "est_commission_usd", + "est_b_exec_usd", + "est_total_buy_commit_usd", + "rho_order" + ], + "properties": { + "symbol": { "$ref": "#/$defs/symbol" }, + "price_ref": { "$ref": "#/$defs/positiveDecimal" }, + "price_lim": { "$ref": "#/$defs/nullablePositiveDecimal" }, + "w_target": { "$ref": "#/$defs/nonNegativeDecimal" }, + "w_cur": { "$ref": "#/$defs/nonNegativeDecimal" }, + "q_pre": { "$ref": "#/$defs/nonNegativeIntegerDecimal" }, + "q_ideal": { "$ref": "#/$defs/nonNegativeIntegerDecimal" }, + "delta_q_raw": { "$ref": "#/$defs/integerDecimal" }, + "delta_q_final": { "$ref": "#/$defs/integerDecimal" }, + "delta_q_buy": { "$ref": "#/$defs/nonNegativeIntegerDecimal" }, + "delta_q_sell": { "$ref": "#/$defs/nonNegativeIntegerDecimal" }, + "q_target": { "$ref": "#/$defs/nonNegativeIntegerDecimal" }, + "action": { "enum": ["BUY", "SELL", "HOLD", "BLOCKED_BUY"] }, + "band_suppressed": { "type": "boolean" }, + "emergency_bypass_applied": { "type": "boolean" }, + "buy_blocked_reason": { "$ref": "#/$defs/nullableSafeString" }, + "est_notional_ref_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "est_worst_case_notional_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "est_commission_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "est_b_exec_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "est_total_buy_commit_usd": { "$ref": "#/$defs/nonNegativeDecimal" }, + "rho_order": { + "type": "object", + "additionalProperties": false, + "required": [ + "value", + "threshold", + "status", + "numerator_usd", + "denominator_usd", + "rounding_friction_usd" + ], + "properties": { + "value": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "threshold": { "type": "null" }, + "status": { "enum": ["diagnostic_only_threshold_unset", "not_applicable_zero_order"] }, + "numerator_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "denominator_usd": { "$ref": "#/$defs/nullableNonNegativeDecimal" }, + "rounding_friction_usd": { "$ref": "#/$defs/nonNegativeDecimal" } + } + } + } + } + } +} diff --git a/tests/fixtures/sa2/sa2_demo_cases.json b/tests/fixtures/sa2/sa2_demo_cases.json new file mode 100644 index 00000000..fd65172a --- /dev/null +++ b/tests/fixtures/sa2/sa2_demo_cases.json @@ -0,0 +1,661 @@ +{ + "schema_version": "qsl.sa2_demo_cases.v1", + "frozen_phase": "SA2-W1", + "origin": "synthetic", + "cases": { + "SA2-D1": { + "id": "SA2-D1", + "title": "C-SA-Q21 Zero deployable cash blocks buys, never reductions", + "zero_cash_case": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "2000.00", + "k_pend_usd": "3000.00", + "k_pend_release_allowed": false, + "b_band": "0.20", + "emergency_bypass": true, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { + "symbol": "TQQQ", + "q_pre": "10", + "price_ref": "50.00", + "price_lim": "50.50", + "w_target": "0.10" + }, + { + "symbol": "SOXL", + "q_pre": "20", + "price_ref": "25.00", + "price_lim": "25.25", + "w_target": "0.045" + } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:demo:d1-zero-cash" + }, + "expected": { + "status": "available", + "c_inv_usd": "1000.00", + "c_avail_usd": "0", + "total_buy_commit_usd": "0", + "tqqq": { + "q_ideal": "20", + "delta_q_raw": "10", + "delta_q_buy": "0", + "delta_q_final": "0", + "action": "BLOCKED_BUY", + "buy_blocked_reason": "zero_deployable_cash" + }, + "soxl": { + "q_ideal": "18", + "delta_q_raw": "-2", + "delta_q_buy": "0", + "delta_q_sell": "2", + "delta_q_final": "-2", + "action": "SELL", + "band_suppressed": false, + "emergency_bypass_applied": true + } + } + }, + "positive_control": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "2000.00", + "k_pend_usd": "1000.00", + "k_pend_release_allowed": true, + "b_band": "0.20", + "emergency_bypass": true, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { + "symbol": "TQQQ", + "q_pre": "10", + "price_ref": "50.00", + "price_lim": "50.50", + "w_target": "0.10" + }, + { + "symbol": "SOXL", + "q_pre": "20", + "price_ref": "25.00", + "price_lim": "25.25", + "w_target": "0.045" + } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:demo:d1-positive" + }, + "expected": { + "status": "available", + "c_avail_usd": "2000.00", + "total_buy_commit_usd": "506.25", + "tqqq_delta_q_buy": "10", + "tqqq_action": "BUY", + "soxl_delta_q_sell": "2", + "soxl_action": "SELL" + } + } + }, + "SA2-D2": { + "id": "SA2-D2", + "title": "C-SA-Q21 Fee-and-collar whole-share rounding boundary", + "boundary_case": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "2000.00", + "cash_settled_usd": "1000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { + "symbol": "TQQQ", + "q_pre": "0", + "price_ref": "100.00", + "price_lim": "101.00", + "w_target": "0.50" + } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:demo:d2-boundary" + }, + "expected": { + "status": "available", + "c_avail_usd": "1000.00", + "q_ideal": "10", + "naive_shares_by_p_ref": "10", + "delta_q_buy": "9", + "q_target": "9", + "est_worst_case_notional_usd": "909.00", + "est_commission_usd": "1.25", + "est_total_buy_commit_usd": "910.25", + "remaining_deployable_cash_usd": "89.75", + "fractional_shares": "prohibited", + "rho_order_value": "0.001388888889", + "rho_order_threshold": null + } + }, + "positive_control": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "2000.00", + "cash_settled_usd": "1011.25", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { + "symbol": "TQQQ", + "q_pre": "0", + "price_ref": "100.00", + "price_lim": "101.00", + "w_target": "0.50" + } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:demo:d2-positive" + }, + "expected": { + "status": "available", + "delta_q_buy": "10", + "est_total_buy_commit_usd": "1011.25", + "remaining_deployable_cash_usd": "0" + } + } + }, + "SA2-D3": { + "id": "SA2-D3", + "title": "C-SA-25 + O4 Restart-persistent ORDER-UNKNOWN lock", + "timeout_submission": { + "broker": "longbridge", + "environment": "paper", + "account": "longbridge:paper:pilot", + "client_order_id": "ord-lb-paper-tqqq-001", + "broker_order_id": null, + "symbol": "TQQQ", + "side": "BUY", + "state": "ORDER_UNKNOWN", + "qty_submitted": "10", + "limit_price": "50.00", + "currency": "USD", + "fee_native": null, + "fee_currency": null, + "estimated_fee_usd": "1.25", + "usd_basis_qualified": true, + "submitted_at": "2026-11-24T14:55:00.000Z", + "evidence_ref": "sa2:demo:d3-timeout" + }, + "non_terminal_followup": { + "broker": "longbridge", + "environment": "paper", + "account": "longbridge:paper:pilot", + "client_order_id": "ord-lb-paper-tqqq-001", + "broker_order_id": "brk-lb-paper-001", + "symbol": "TQQQ", + "side": "BUY", + "state": "ACCEPTED", + "qty_submitted": "10", + "qty_filled": "0", + "qty_canceled": "0", + "qty_remaining": "10", + "limit_price": "50.00", + "currency": "USD", + "reserved_fee_usd": "1.25", + "usd_basis_qualified": true, + "as_of": "2026-11-24T14:56:00.000Z", + "evidence_ref": "sa2:demo:d3-accepted" + }, + "terminal_resolution": { + "broker": "longbridge", + "environment": "paper", + "account": "longbridge:paper:pilot", + "client_order_id": "ord-lb-paper-tqqq-001", + "broker_order_id": "brk-lb-paper-001", + "symbol": "TQQQ", + "side": "BUY", + "state": "CANCELED", + "qty_submitted": "10", + "qty_filled": "0", + "qty_canceled": "10", + "qty_remaining": "0", + "currency": "USD", + "resolved_at": "2026-11-24T14:57:00.000Z", + "evidence_ref": "sa2:demo:d3-canceled" + }, + "expected": { + "k_pend_locked_usd": "501.25", + "query_target_pre_ack_by": "client_order_tuple", + "locked_symbols": ["TQQQ"], + "tqqq_buy_blocked_while_locked": "0", + "soxl_buy_unblocked_while_tqqq_locked": "4", + "k_pend_after_terminal_with_complete_coverage": "0" + } + }, + "SA2-D4": { + "id": "SA2-D4", + "title": "C-SA-25 (broker, environment, account) isolation", + "paper_account": { + "broker": "longbridge", + "environment": "paper", + "account": "longbridge:paper:pilot", + "as_of": "2026-11-24T15:00:00.000Z", + "evaluated_at": "2026-11-24T15:00:05.000Z", + "origin": "synthetic", + "source_class": "paper_broker", + "evidence_ref": "sa2:demo:d4-paper", + "domains": { + "submissions": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_paper_orders", + "scope": "account_submissions", + "cap": 512, + "completeness": "complete", + "truncated": false, + "records": [ + { + "client_order_id": "ord-shared-001", + "broker_order_id": "brk-paper-1", + "symbol": "TQQQ", + "side": "BUY", + "state": "FILLED", + "qty_submitted": "10", + "limit_price": "50.00", + "currency": "USD", + "fee_native": "1.25", + "fee_currency": "USD", + "submitted_at": "2026-11-24T14:50:00.000Z", + "evidence_ref": "sa2:demo:d4-paper-sub" + } + ] + }, + "executions": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_paper_fills", + "scope": "account_executions", + "cap": 512, + "completeness": "complete", + "truncated": false, + "records": [ + { + "execution_ref": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "report_ref": "1111111111111111111111111111111111111111111111111111111111111111", + "client_order_id": "ord-shared-001", + "broker_order_id": "brk-paper-1", + "symbol": "TQQQ", + "side": "BUY", + "qty": "10", + "price": "49.50", + "currency": "USD", + "fee_native": "1.25", + "fee_currency": "USD", + "executed_at": "2026-11-24T14:51:00.000Z", + "evidence_ref": "sa2:demo:d4-paper-exec" + } + ] + }, + "cutoff_open_orders": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_paper_open", + "scope": "cutoff_open_orders", + "cap": 512, + "completeness": "complete", + "truncated": false, + "records": [] + } + } + }, + "live_account": { + "broker": "longbridge", + "environment": "live", + "account": "longbridge:live:sg", + "as_of": "2026-11-24T15:00:00.000Z", + "evaluated_at": "2026-11-24T15:00:05.000Z", + "origin": "synthetic", + "source_class": "authorized_live_broker", + "evidence_ref": "sa2:demo:d4-live", + "domains": { + "submissions": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_live_orders", + "scope": "account_submissions", + "cap": 512, + "completeness": "complete", + "truncated": false, + "records": [ + { + "client_order_id": "ord-shared-001", + "broker_order_id": "brk-live-9", + "symbol": "SOXL", + "side": "SELL", + "state": "FILLED", + "qty_submitted": "20", + "limit_price": "25.00", + "currency": "USD", + "fee_native": "2.00", + "fee_currency": "USD", + "submitted_at": "2026-11-24T14:52:00.000Z", + "evidence_ref": "sa2:demo:d4-live-sub" + } + ] + }, + "executions": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_live_fills", + "scope": "account_executions", + "cap": 512, + "completeness": "complete", + "truncated": false, + "records": [ + { + "execution_ref": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "report_ref": "2222222222222222222222222222222222222222222222222222222222222222", + "client_order_id": "ord-shared-001", + "broker_order_id": "brk-live-9", + "symbol": "SOXL", + "side": "SELL", + "qty": "20", + "price": "25.10", + "currency": "USD", + "fee_native": "2.00", + "fee_currency": "USD", + "executed_at": "2026-11-24T14:53:00.000Z", + "evidence_ref": "sa2:demo:d4-live-exec" + } + ] + }, + "cutoff_open_orders": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_live_open", + "scope": "cutoff_open_orders", + "cap": 512, + "completeness": "complete", + "truncated": false, + "records": [] + } + } + }, + "invalid_conflated_broker": { + "broker": "longbridge_paper", + "environment": "paper", + "account": "longbridge:paper:pilot" + }, + "expected": { + "paper_binding_key": "longbridge|paper|longbridge:paper:pilot", + "live_binding_key": "longbridge|live|longbridge:live:sg", + "isolated_distinct_orders": 2, + "isolated_distinct_executions": 2 + } + }, + "SA2-D5": { + "id": "SA2-D5", + "title": "C-SA-25 Dedup vs conflicting duplicate & partial fill/cancel", + "partial_fill_cancel_input": { + "broker": "ibkr", + "environment": "live", + "account": "ibkr:live:a1", + "as_of": "2026-11-24T15:00:00.000Z", + "evaluated_at": "2026-11-24T15:00:05.000Z", + "origin": "synthetic", + "source_class": "authorized_live_broker", + "evidence_ref": "sa2:demo:d5", + "domains": { + "submissions": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "ibkr_oms", + "scope": "account_submissions", + "cap": 256, + "completeness": "complete", + "truncated": false, + "records": [ + { + "client_order_id": "ord-ibkr-pf-001", + "broker_order_id": "brk-ibkr-101", + "symbol": "TQQQ", + "side": "BUY", + "state": "PARTIAL_CANCEL", + "qty_submitted": "10", + "qty_canceled": "6", + "limit_price": "50.00", + "currency": "USD", + "fee_native": null, + "fee_currency": null, + "submitted_at": "2026-11-24T14:40:00.000Z", + "evidence_ref": "sa2:demo:d5-sub" + } + ] + }, + "executions": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "ibkr_flex", + "scope": "account_executions", + "cap": 256, + "completeness": "complete", + "truncated": false, + "records": [ + { + "execution_ref": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "report_ref": "1111111111111111111111111111111111111111111111111111111111111111", + "client_order_id": "ord-ibkr-pf-001", + "broker_order_id": "brk-ibkr-101", + "symbol": "TQQQ", + "side": "BUY", + "qty": "4", + "price": "49.80", + "currency": "USD", + "fee_native": "-1.00", + "fee_currency": "USD", + "executed_at": "2026-11-24T14:41:00.000Z", + "evidence_ref": "sa2:demo:d5-exec-1" + }, + { + "execution_ref": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "report_ref": "2222222222222222222222222222222222222222222222222222222222222222", + "client_order_id": "ord-ibkr-pf-001", + "broker_order_id": "brk-ibkr-101", + "symbol": "TQQQ", + "side": "BUY", + "qty": "4", + "price": "49.80", + "currency": "USD", + "fee_native": "-1.00", + "fee_currency": "USD", + "executed_at": "2026-11-24T14:41:00.000Z", + "evidence_ref": "sa2:demo:d5-exec-dup" + } + ] + }, + "cutoff_open_orders": { + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "ibkr_open", + "scope": "cutoff_open_orders", + "cap": 256, + "completeness": "complete", + "truncated": false, + "records": [] + } + } + }, + "conflicting_duplicate_execution": { + "execution_ref": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "report_ref": "3333333333333333333333333333333333333333333333333333333333333333", + "client_order_id": "ord-ibkr-pf-001", + "broker_order_id": "brk-ibkr-101", + "symbol": "TQQQ", + "side": "BUY", + "qty": "5", + "price": "49.80", + "currency": "USD", + "fee_native": "-1.00", + "fee_currency": "USD", + "executed_at": "2026-11-24T14:41:00.000Z", + "evidence_ref": "sa2:demo:d5-conflict" + }, + "expected": { + "executions_count": 1, + "qty_submitted": "10", + "qty_filled": "4", + "qty_canceled": "6", + "qty_remaining": "0", + "state": "PARTIAL_CANCEL", + "k_pend_usd": "0", + "k_pend_release_allowed": true + } + }, + "SA2-D6": { + "id": "SA2-D6", + "title": "C-SA-25 Explicit cap & completeness proof across 256/512/2048 & unsupported", + "truncated_512_case": { + "domain": "cutoff_open_orders", + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_paper_open", + "scope": "cutoff_open_orders", + "cap": 512, + "count": 512, + "truncated": true, + "completeness": "incomplete", + "prior_k_pend_usd": "2500.00" + }, + "incomplete_zero_case": { + "domain": "cutoff_open_orders", + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_paper_open", + "scope": "cutoff_open_orders", + "cap": 2048, + "count": 0, + "truncated": false, + "completeness": "incomplete", + "prior_k_pend_usd": "2500.00" + }, + "proven_empty_512_case": { + "domain": "cutoff_open_orders", + "domain_capability": "supported", + "as_of": "2026-11-24T15:00:00.000Z", + "source": "longbridge_paper_open", + "scope": "cutoff_open_orders", + "cap": 512, + "count": 0, + "truncated": false, + "completeness": "complete", + "prior_k_pend_usd": "2500.00" + }, + "unsupported_domain_case": { + "domain": "cutoff_open_orders", + "domain_capability": "unsupported", + "as_of": null, + "source": "firstrade_unsupported", + "scope": "cutoff_open_orders" + }, + "expected": { + "truncated_512_empty_proven": false, + "truncated_512_release_allowed": false, + "incomplete_zero_empty_proven": false, + "incomplete_zero_release_allowed": false, + "proven_empty_512_empty_proven": true, + "proven_empty_512_release_allowed": true, + "unsupported_capability": "unsupported", + "unsupported_count": null, + "unsupported_empty_proven": false, + "unsupported_release_allowed": false + } + }, + "SA2-D7": { + "id": "SA2-D7", + "title": "SA-A19 Zero B0 read-path writes", + "expected": { + "storage_writes": 0, + "kv_writes": 0 + } + } + } +} diff --git a/tests/fixtures/sa2/sa2_orders_fills_matrix.json b/tests/fixtures/sa2/sa2_orders_fills_matrix.json new file mode 100644 index 00000000..5077b55f --- /dev/null +++ b/tests/fixtures/sa2/sa2_orders_fills_matrix.json @@ -0,0 +1,341 @@ +{ + "schema_version": "qsl.sa2_orders_fills_matrix.v1", + "frozen_phase": "SA2-W1", + "origin": "synthetic", + "cases": { + "multi_broker_separation": { + "description": "Separate broker from paper/live environment across all 5 canonical brokers and bind keys to (broker, environment, account)", + "accounts": [ + { + "broker": "longbridge", + "environment": "paper", + "account": "longbridge:paper:pilot", + "source_class": "paper_broker", + "symbol": "TQQQ", + "price": "50.00" + }, + { + "broker": "longbridge", + "environment": "live", + "account": "longbridge:live:sg", + "source_class": "authorized_live_broker", + "symbol": "TQQQ", + "price": "50.25" + }, + { + "broker": "ibkr", + "environment": "live", + "account": "ibkr:live:a1", + "source_class": "authorized_live_broker", + "symbol": "SOXL", + "price": "25.00" + }, + { + "broker": "schwab", + "environment": "live", + "account": "schwab:live:main", + "source_class": "authorized_live_broker", + "symbol": "QQQ", + "price": "500.00" + }, + { + "broker": "firstrade", + "environment": "live", + "account": "firstrade:live:main", + "source_class": "authorized_live_broker", + "symbol": "SOXX", + "price": "220.00" + }, + { + "broker": "binance", + "environment": "live", + "account": "binance:live:dormant", + "source_class": "authorized_live_broker", + "symbol": "BTCUSDT", + "price": "90000.00" + } + ], + "invalid_inputs": [ + { "name": "conflated_longbridge_paper", "broker": "longbridge_paper", "environment": "paper", "account": "longbridge:paper:pilot" }, + { "name": "research_env_disallowed", "broker": "binance", "environment": "research", "account": "binance:research:archive" }, + { "name": "account_prefix_broker_mismatch", "broker": "ibkr", "environment": "live", "account": "longbridge:live:sg" }, + { "name": "account_prefix_env_mismatch", "broker": "longbridge", "environment": "live", "account": "longbridge:paper:pilot" } + ] + }, + "dedup_and_lifecycle": { + "identical_and_supplemental_dedup": { + "broker": "longbridge", + "environment": "paper", + "account": "longbridge:paper:pilot", + "submissions": [ + { + "client_order_id": "ord-lb-p-100", + "broker_order_id": "brk-lb-p-100", + "symbol": "TQQQ", + "side": "BUY", + "state": "PARTIAL_FILL", + "qty_submitted": "10", + "limit_price": "50.00", + "currency": "USD", + "fee_native": null, + "fee_currency": null, + "submitted_at": "2026-11-24T14:35:00.000Z", + "evidence_ref": "sa2:a12:sub-100" + } + ], + "executions": [ + { + "execution_ref": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "report_ref": "1111111111111111111111111111111111111111111111111111111111111111", + "client_order_id": "ord-lb-p-100", + "broker_order_id": "brk-lb-p-100", + "symbol": "TQQQ", + "side": "BUY", + "qty": "4", + "price": "49.75", + "currency": "USD", + "fee_native": null, + "fee_currency": null, + "executed_at": "2026-11-24T14:36:00.000Z", + "evidence_ref": "sa2:a12:exec-100a" + }, + { + "execution_ref": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "report_ref": "2222222222222222222222222222222222222222222222222222222222222222", + "client_order_id": "ord-lb-p-100", + "broker_order_id": "brk-lb-p-100", + "symbol": "TQQQ", + "side": "BUY", + "qty": "4", + "price": "49.75", + "currency": "USD", + "fee_native": "0.99", + "fee_currency": "USD", + "executed_at": "2026-11-24T14:36:00.000Z", + "evidence_ref": "sa2:a12:exec-100b" + } + ], + "cutoff_open_orders": [ + { + "client_order_id": "ord-lb-p-100", + "broker_order_id": "brk-lb-p-100", + "symbol": "TQQQ", + "side": "BUY", + "state": "PARTIAL_FILL", + "qty_submitted": "10", + "qty_filled": "4", + "qty_canceled": "0", + "qty_remaining": "6", + "limit_price": "50.00", + "currency": "USD", + "reserved_fee_usd": "1.00", + "as_of": "2026-11-24T15:00:00.000Z", + "evidence_ref": "sa2:a12:open-100" + } + ], + "expected": { + "executions_count": 1, + "fee_usd": "0.99", + "qty_submitted": "10", + "qty_filled": "4", + "qty_remaining": "6", + "k_pend_usd": "301.00" + } + }, + "conflicting_execution_cases": [ + { + "name": "qty_mismatch", + "patch": { "qty": "5" } + }, + { + "name": "price_mismatch", + "patch": { "price": "50.00" } + }, + { + "name": "conflicting_non_null_fee", + "patch": { "fee_native": "2.50" } + } + ] + }, + "order_unknown_recovery": { + "pre_ack_timeout": { + "broker": "longbridge", + "environment": "paper", + "account": "longbridge:paper:pilot", + "client_order_id": "ord-timeout-preack", + "broker_order_id": null, + "symbol": "TQQQ", + "side": "BUY", + "state": "ORDER_UNKNOWN", + "qty_submitted": "8", + "limit_price": "50.00", + "currency": "USD", + "estimated_fee_usd": "1.00", + "submitted_at": "2026-11-24T14:50:00.000Z", + "evidence_ref": "sa2:a12:timeout-preack" + }, + "post_ack_timeout": { + "broker": "ibkr", + "environment": "live", + "account": "ibkr:live:a1", + "client_order_id": "ord-timeout-postack", + "broker_order_id": "brk-ibkr-901", + "symbol": "SOXL", + "side": "BUY", + "state": "ORDER_UNKNOWN", + "qty_submitted": "12", + "limit_price": "25.00", + "currency": "USD", + "estimated_fee_usd": "1.50", + "submitted_at": "2026-11-24T14:51:00.000Z", + "evidence_ref": "sa2:a12:timeout-postack" + }, + "expected": { + "pre_ack_k_pend_usd": "401.00", + "pre_ack_query_by": "client_order_tuple", + "post_ack_k_pend_usd": "301.50", + "post_ack_query_by": "broker_order_id" + } + }, + "caps_and_completeness_matrix": [ + { + "name": "cap_256_truncated", + "cap": 256, + "count": 256, + "truncated": true, + "completeness": "complete", + "domain_capability": "supported", + "prior_k_pend_usd": "1000.00", + "expected": { "empty_domain_proven": false, "k_pend_release_allowed": false, "k_pend_usd": "1000.00" } + }, + { + "name": "cap_512_truncated", + "cap": 512, + "count": 512, + "truncated": true, + "completeness": "incomplete", + "domain_capability": "supported", + "prior_k_pend_usd": "1000.00", + "expected": { "empty_domain_proven": false, "k_pend_release_allowed": false, "k_pend_usd": "1000.00" } + }, + { + "name": "cap_2048_truncated", + "cap": 2048, + "count": 2048, + "truncated": true, + "completeness": "complete", + "domain_capability": "supported", + "prior_k_pend_usd": "1000.00", + "expected": { "empty_domain_proven": false, "k_pend_release_allowed": false, "k_pend_usd": "1000.00" } + }, + { + "name": "cap_512_proven_empty", + "cap": 512, + "count": 0, + "truncated": false, + "completeness": "complete", + "domain_capability": "supported", + "prior_k_pend_usd": "1000.00", + "expected": { "empty_domain_proven": true, "k_pend_release_allowed": true, "k_pend_usd": "0" } + }, + { + "name": "cap_2048_proven_empty", + "cap": 2048, + "count": 0, + "truncated": false, + "completeness": "complete", + "domain_capability": "supported", + "prior_k_pend_usd": "1000.00", + "expected": { "empty_domain_proven": true, "k_pend_release_allowed": true, "k_pend_usd": "0" } + }, + { + "name": "unsupported_firstrade_open_orders", + "cap": null, + "count": null, + "truncated": null, + "completeness": "unsupported", + "domain_capability": "unsupported", + "prior_k_pend_usd": "1000.00", + "expected": { "empty_domain_proven": false, "k_pend_release_allowed": false, "count": null, "k_pend_usd": "1000.00" } + }, + { + "name": "unsupported_binance_submissions", + "cap": null, + "count": null, + "truncated": null, + "completeness": "unsupported", + "domain_capability": "unsupported", + "prior_k_pend_usd": "1000.00", + "expected": { "empty_domain_proven": false, "k_pend_release_allowed": false, "count": null, "k_pend_usd": "1000.00" } + } + ], + "null_fee_and_non_usd_cases": { + "null_fee_usd_execution": { + "broker": "longbridge", + "environment": "paper", + "account": "longbridge:paper:pilot", + "execution_ref": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", + "report_ref": "4444444444444444444444444444444444444444444444444444444444444444", + "client_order_id": "ord-null-fee-1", + "broker_order_id": "brk-null-fee-1", + "symbol": "TQQQ", + "side": "BUY", + "qty": "5", + "price": "50.00", + "currency": "USD", + "fee_native": null, + "fee_currency": null, + "executed_at": "2026-11-24T14:45:00.000Z", + "evidence_ref": "sa2:a12:null-fee" + }, + "non_usd_hkd_execution": { + "broker": "longbridge", + "environment": "live", + "account": "longbridge:live:hk", + "execution_ref": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + "report_ref": "5555555555555555555555555555555555555555555555555555555555555555", + "client_order_id": "ord-hkd-1", + "broker_order_id": "brk-hkd-1", + "symbol": "2800.HK", + "side": "BUY", + "qty": "500", + "price": "20.10", + "currency": "HKD", + "fee_native": "15.00", + "fee_currency": "HKD", + "executed_at": "2026-11-24T06:30:00.000Z", + "evidence_ref": "sa2:a12:hkd-exec" + }, + "legacy_ibkr_flex_payload": { + "schema_version": "broker_executions.v1", + "target_id": "synthetic-target", + "source_binding_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "account_scope": "synthetic-live", + "account_selector": "synthetic-selector", + "period": { "from": "2026-10-01", "to": "2026-10-23" }, + "observed_at": "2026-10-23T16:00:00.000Z", + "source": "ibkr_flex", + "source_ref": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "coverage": "reported_executions", + "records": [ + { + "execution_ref": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "report_ref": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "trade_date": "2026-10-23", + "local_time": "2026-10-23T09:31:00", + "time_zone": null, + "symbol": "SYNTH", + "asset_category": "STK", + "side": "SELL", + "quantity": "-1.5", + "price": "100.25", + "currency": "USD", + "commission": "-0.123456789000000001", + "commission_currency": "EUR", + "taxes": "0" + } + ] + } + } + } +} diff --git a/tests/fixtures/sa2/sa2_q21_matrix.json b/tests/fixtures/sa2/sa2_q21_matrix.json new file mode 100644 index 00000000..b7f47f63 --- /dev/null +++ b/tests/fixtures/sa2/sa2_q21_matrix.json @@ -0,0 +1,501 @@ +{ + "schema_version": "qsl.sa2_q21_matrix.v1", + "frozen_phase": "SA2-W1", + "origin": "synthetic", + "cases": { + "negative_raw_avail_clamped": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "1000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "800.00", + "k_pend_usd": "500.00", + "k_pend_release_allowed": false, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { "symbol": "TQQQ", "q_pre": "10", "price_ref": "50.00", "price_lim": "50.50", "w_target": "0.10" }, + { "symbol": "SOXL", "q_pre": "20", "price_ref": "25.00", "price_lim": "25.25", "w_target": "0.025" } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:neg-avail" + }, + "expected": { + "status": "available", + "c_inv_usd": "1000.00", + "raw_deployable_cash_usd": "-300.00", + "c_avail_usd": "0", + "tqqq_delta_q_buy": "0", + "soxl_delta_q_sell": "10" + } + }, + "portfolio_concurrent_buy_budget": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "2000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { "symbol": "TQQQ", "q_pre": "0", "price_ref": "50.00", "price_lim": "50.50", "w_target": "0.20" }, + { "symbol": "SOXL", "q_pre": "0", "price_ref": "25.00", "price_lim": "25.25", "w_target": "0.10" } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:multi-buy" + }, + "expected": { + "status": "available", + "c_avail_usd": "2000.00", + "tqqq_delta_q_buy": "26", + "soxl_delta_q_buy": "26", + "total_buy_commit_usd": "1972.00", + "remaining_deployable_cash_usd": "28.00", + "tqqq_rho_order_value": "0.000961538462", + "tqqq_rho_order_threshold": null + } + }, + "one_share_exceeds_budget": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "101.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { "symbol": "TQQQ", "q_pre": "0", "price_ref": "100.00", "price_lim": "100.50", "w_target": "0.05" } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:one-share-fail" + }, + "expected": { + "status": "available", + "delta_q_buy": "0", + "buy_blocked_reason": "budget_insufficient_for_one_share", + "total_buy_commit_usd": "0" + } + }, + "rounding_friction_and_b_exec": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { + "provenance": "research_prereg_amended", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0.50" + }, + "order_unknown_symbols": [], + "targets": [ + { "symbol": "TQQQ", "q_pre": "0", "price_ref": "47.00", "price_lim": "47.47", "w_target": "0.15" } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:rounding-friction" + }, + "expected": { + "status": "available", + "q_ideal": "31", + "delta_q_buy": "31", + "est_commission_usd": "1.25", + "est_b_exec_usd": "0.50", + "est_total_buy_commit_usd": "1473.32", + "rounding_friction_usd": "43.00", + "rho_order_value": "0.030370624571", + "rho_order_threshold": null + } + }, + "order_unknown_symbol_block": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "501.25", + "k_pend_release_allowed": false, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": ["TQQQ"], + "targets": [ + { "symbol": "TQQQ", "q_pre": "0", "price_ref": "50.00", "price_lim": "50.50", "w_target": "0.10" }, + { "symbol": "SOXL", "q_pre": "0", "price_ref": "25.00", "price_lim": "25.25", "w_target": "0.05" } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:order-unknown" + }, + "expected": { + "status": "available", + "c_avail_usd": "4498.75", + "tqqq_delta_q_buy": "0", + "tqqq_buy_blocked_reason": "order_unknown_lock", + "soxl_delta_q_buy": "20" + } + }, + "b_band_suppression_vs_emergency_bypass": { + "discretionary_suppressed": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "b_band": "0.20", + "emergency_bypass": false, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { "symbol": "SOXL", "q_pre": "20", "price_ref": "25.00", "price_lim": "25.25", "w_target": "0.045" } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:band-suppress" + }, + "expected": { "band_suppressed": true, "delta_q_final": "0", "action": "HOLD" } + }, + "emergency_bypass_executes_sell": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "live_trading_enabled": false, + "stop_loss_return_enabled": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "0", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "b_band": "0.20", + "emergency_bypass": true, + "fee_schedule": { + "provenance": "synthetic_fixture", + "c_min_usd": "1.00", + "c_per_share_usd": "0.01", + "c_reg": "0.25", + "b_exec_usd": "0" + }, + "order_unknown_symbols": [], + "targets": [ + { "symbol": "SOXL", "q_pre": "20", "price_ref": "25.00", "price_lim": "25.25", "w_target": "0.045" } + ], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:emergency-bypass" + }, + "expected": { "band_suppressed": false, "emergency_bypass_applied": true, "delta_q_final": "-2", "action": "SELL" } + } + }, + "b_min_tier_boundaries": { + "workable_below_10pct": { + "bankroll_w_usd": "50000.00", + "c_fixed_ann_usd": "499.99", + "expected_excess_growth_ann_usd": "5000.00", + "expected": { "status": "available", "workable": true, "friction_ratio": "0.099998" } + }, + "unworkable_exact_10pct": { + "bankroll_w_usd": "50000.00", + "c_fixed_ann_usd": "500.00", + "expected_excess_growth_ann_usd": "5000.00", + "expected": { "status": "available", "workable": false, "friction_ratio": "0.1" } + }, + "unworkable_above_10pct": { + "bankroll_w_usd": "10000.00", + "c_fixed_ann_usd": "200.00", + "expected_excess_growth_ann_usd": "1000.00", + "expected": { "status": "available", "workable": false, "friction_ratio": "0.2" } + }, + "unset_growth_unavailable": { + "bankroll_w_usd": "50000.00", + "c_fixed_ann_usd": "200.00", + "expected_excess_growth_ann_usd": null, + "expected": { "status": "unavailable", "workable": null, "friction_ratio": null } + } + }, + "unset_oi_cost_and_safety_rejections": { + "unset_fee_schedule": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": null, + "order_unknown_symbols": [], + "targets": [{ "symbol": "TQQQ", "q_pre": "0", "price_ref": "50.00", "price_lim": "50.50", "w_target": "0.10" }], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:unset-fee" + }, + "expected": { "status": "unavailable", "reason": "oi_cost_3_fee_schedule_unavailable", "oi_cost_3_resolved": false } + }, + "null_c_min_fee": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { "provenance": "synthetic_fixture", "c_min_usd": null, "c_per_share_usd": "0.01", "c_reg": "0.25" }, + "order_unknown_symbols": [], + "targets": [{ "symbol": "TQQQ", "q_pre": "0", "price_ref": "50.00", "price_lim": "50.50", "w_target": "0.10" }], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:null-c-min" + }, + "expected": { "status": "unavailable", "reason": "oi_cost_3_fee_schedule_unavailable", "oi_cost_3_resolved": false } + }, + "unset_o5_collar": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { "provenance": "synthetic_fixture", "c_min_usd": "1.00", "c_per_share_usd": "0.01", "c_reg": "0.25", "b_exec_usd": "0" }, + "order_unknown_symbols": [], + "targets": [{ "symbol": "TQQQ", "q_pre": "0", "price_ref": "50.00", "price_lim": null, "w_target": "0.10" }], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:unset-collar" + }, + "expected": { "status": "unavailable", "reason": "oi_cost_4_price_collar_unavailable", "oi_cost_4_resolved": false } + }, + "fractional_q_pre_rejected": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { "provenance": "synthetic_fixture", "c_min_usd": "1.00", "c_per_share_usd": "0.01", "c_reg": "0.25", "b_exec_usd": "0" }, + "order_unknown_symbols": [], + "targets": [{ "symbol": "TQQQ", "q_pre": "1.5", "price_ref": "50.00", "price_lim": "50.50", "w_target": "0.10" }], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:fractional-prohibited" + }, + "expected": { "status": "unavailable", "reason": "fractional_shares_prohibited" } + }, + "margin_enabled_rejected": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": true, + "h_usd": "0", + "kelly_applied": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { "provenance": "synthetic_fixture", "c_min_usd": "1.00", "c_per_share_usd": "0.01", "c_reg": "0.25", "b_exec_usd": "0" }, + "order_unknown_symbols": [], + "targets": [], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:margin-prohibited" + }, + "expected": { "status": "unavailable", "reason": "margin_prohibited" } + }, + "nonzero_h_rejected": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "1000.00", + "kelly_applied": false, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { "provenance": "synthetic_fixture", "c_min_usd": "1.00", "c_per_share_usd": "0.01", "c_reg": "0.25", "b_exec_usd": "0" }, + "order_unknown_symbols": [], + "targets": [], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:nonzero-h" + }, + "expected": { "status": "unavailable", "reason": "nonzero_h_prohibited_in_pilot" } + }, + "kelly_applied_rejected": { + "input": { + "account_id": "longbridge:paper:pilot", + "broker": "longbridge", + "environment": "paper", + "currency": "USD", + "margin_enabled": false, + "h_usd": "0", + "kelly_applied": true, + "evaluated_at": "2026-11-24T15:00:00.000Z", + "equity_usd": "10000.00", + "cash_settled_usd": "5000.00", + "proceeds_eligible_usd": "0", + "r_cash_usd": "0", + "k_pend_usd": "0", + "k_pend_release_allowed": true, + "fee_schedule": { "provenance": "synthetic_fixture", "c_min_usd": "1.00", "c_per_share_usd": "0.01", "c_reg": "0.25", "b_exec_usd": "0" }, + "order_unknown_symbols": [], + "targets": [], + "origin": "synthetic", + "source_class": "synthetic", + "evidence_ref": "sa2:a13:kelly-prohibited" + }, + "expected": { "status": "unavailable", "reason": "kelly_prohibited" } + } + } + } +} diff --git a/tests/sa2_demo_validation.mjs b/tests/sa2_demo_validation.mjs new file mode 100644 index 00000000..6e5758f5 --- /dev/null +++ b/tests/sa2_demo_validation.mjs @@ -0,0 +1,407 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; + +const require = createRequire(new URL("../web/strategy-switch-console/package.json", import.meta.url)); +const Ajv2020 = require("ajv/dist/2020").default; +const addFormats = require("ajv-formats"); + +const loadJson = (relPath) => JSON.parse(readFileSync(new URL(relPath, import.meta.url), "utf8")); + +const ordersFillsSchema = loadJson("../schemas/qsl-authoritative-orders-fills.v1.schema.json"); +const deployableCapitalSchema = loadJson("../schemas/qsl-deployable-capital-sizing.v1.schema.json"); +const demoFixture = loadJson("./fixtures/sa2/sa2_demo_cases.json"); + +const ajv = new Ajv2020({ allErrors: true, strict: true, strictTypes: false }); +addFormats(ajv); +const validateOrdersFillsSchema = ajv.compile(ordersFillsSchema); +const validateDeployableCapitalSchema = ajv.compile(deployableCapitalSchema); + +const PRIVATE_LOCATOR_RE = new RegExp( + "(?:source_ref|kv_key|do_key|kv://|do://|/" + "Users/|/" + "home/|broker_account_hash|broker_account_id)", +); + +const caseArgIndex = process.argv.indexOf("--case"); +const requestedCase = caseArgIndex >= 0 ? process.argv[caseArgIndex + 1] : null; + +const handlers = { + async "SA2-D1"() { + const { evaluateDeployableCapitalSizing } = await import( + "../web/strategy-switch-console/application/sizing_unit/deployable_capital.js" + ); + const spec = demoFixture.cases["SA2-D1"]; + const zeroCash = evaluateDeployableCapitalSizing(spec.zero_cash_case.input); + assert.ok( + validateDeployableCapitalSchema(zeroCash), + `SA2-D1 zero_cash schema: ${ajv.errorsText(validateDeployableCapitalSchema.errors)}`, + ); + assert.equal(zeroCash.status, spec.zero_cash_case.expected.status); + assert.equal(zeroCash.capital.c_inv_usd, spec.zero_cash_case.expected.c_inv_usd); + assert.equal(zeroCash.capital.c_avail_usd, spec.zero_cash_case.expected.c_avail_usd); + assert.equal(zeroCash.capital.total_buy_commit_usd, spec.zero_cash_case.expected.total_buy_commit_usd); + const tqqq = zeroCash.orders.find((o) => o.symbol === "TQQQ"); + const soxl = zeroCash.orders.find((o) => o.symbol === "SOXL"); + assert.ok(tqqq && soxl); + for (const [k, v] of Object.entries(spec.zero_cash_case.expected.tqqq)) { + assert.equal(tqqq[k], v, `SA2-D1 zero_cash.tqqq.${k}`); + } + for (const [k, v] of Object.entries(spec.zero_cash_case.expected.soxl)) { + assert.equal(soxl[k], v, `SA2-D1 zero_cash.soxl.${k}`); + } + assert.equal(PRIVATE_LOCATOR_RE.test(JSON.stringify(zeroCash)), false); + + const pos = evaluateDeployableCapitalSizing(spec.positive_control.input); + assert.ok( + validateDeployableCapitalSchema(pos), + `SA2-D1 positive schema: ${ajv.errorsText(validateDeployableCapitalSchema.errors)}`, + ); + assert.equal(pos.status, spec.positive_control.expected.status); + assert.equal(pos.capital.c_avail_usd, spec.positive_control.expected.c_avail_usd); + assert.equal(pos.capital.total_buy_commit_usd, spec.positive_control.expected.total_buy_commit_usd); + const posTqqq = pos.orders.find((o) => o.symbol === "TQQQ"); + const posSoxl = pos.orders.find((o) => o.symbol === "SOXL"); + assert.equal(posTqqq.delta_q_buy, spec.positive_control.expected.tqqq_delta_q_buy); + assert.equal(posTqqq.action, spec.positive_control.expected.tqqq_action); + assert.equal(posSoxl.delta_q_sell, spec.positive_control.expected.soxl_delta_q_sell); + assert.equal(posSoxl.action, spec.positive_control.expected.soxl_action); + }, + + async "SA2-D2"() { + const { evaluateDeployableCapitalSizing } = await import( + "../web/strategy-switch-console/application/sizing_unit/deployable_capital.js" + ); + const spec = demoFixture.cases["SA2-D2"]; + const res = evaluateDeployableCapitalSizing(spec.boundary_case.input); + assert.ok( + validateDeployableCapitalSchema(res), + `SA2-D2 boundary schema: ${ajv.errorsText(validateDeployableCapitalSchema.errors)}`, + ); + assert.equal(res.status, spec.boundary_case.expected.status); + assert.equal(res.fractional_shares, spec.boundary_case.expected.fractional_shares); + assert.equal(res.capital.c_avail_usd, spec.boundary_case.expected.c_avail_usd); + assert.equal(res.capital.remaining_deployable_cash_usd, spec.boundary_case.expected.remaining_deployable_cash_usd); + const ord = res.orders[0]; + assert.equal(ord.q_ideal, spec.boundary_case.expected.q_ideal); + assert.equal(ord.delta_q_buy, spec.boundary_case.expected.delta_q_buy); + assert.equal(ord.q_target, spec.boundary_case.expected.q_target); + assert.equal(ord.est_worst_case_notional_usd, spec.boundary_case.expected.est_worst_case_notional_usd); + assert.equal(ord.est_commission_usd, spec.boundary_case.expected.est_commission_usd); + assert.equal(ord.est_total_buy_commit_usd, spec.boundary_case.expected.est_total_buy_commit_usd); + assert.equal(ord.rho_order.value, spec.boundary_case.expected.rho_order_value); + assert.equal(ord.rho_order.threshold, spec.boundary_case.expected.rho_order_threshold); + + const pos = evaluateDeployableCapitalSizing(spec.positive_control.input); + assert.ok(validateDeployableCapitalSchema(pos)); + assert.equal(pos.orders[0].delta_q_buy, spec.positive_control.expected.delta_q_buy); + assert.equal(pos.orders[0].est_total_buy_commit_usd, spec.positive_control.expected.est_total_buy_commit_usd); + assert.equal(pos.capital.remaining_deployable_cash_usd, spec.positive_control.expected.remaining_deployable_cash_usd); + }, + + async "SA2-D3"() { + const { + applyOrderUnknownObservation, + checkSymbolOrderAllowed, + createOrderUnknownLockStore, + deserializeOrderUnknownLockStore, + lockedSymbolsForAccount, + serializeOrderUnknownLockStore, + } = await import( + "../web/strategy-switch-console/application/orders_fills/order_unknown_lock.js" + ); + const { evaluateAuthoritativeOrdersAndFills } = await import( + "../web/strategy-switch-console/application/orders_fills/helpers.js" + ); + const { evaluateDeployableCapitalSizing } = await import( + "../web/strategy-switch-console/application/sizing_unit/deployable_capital.js" + ); + + const spec = demoFixture.cases["SA2-D3"]; + let store = createOrderUnknownLockStore(); + store = applyOrderUnknownObservation(store, spec.timeout_submission); + const serialized = JSON.stringify(serializeOrderUnknownLockStore(store)); + // Simulate DO/store process restart + const reloaded = deserializeOrderUnknownLockStore(JSON.parse(serialized)); + + const identity = { + broker: spec.timeout_submission.broker, + environment: spec.timeout_submission.environment, + account: spec.timeout_submission.account, + }; + const tqqqCheck = checkSymbolOrderAllowed(reloaded, { ...identity, symbol: "TQQQ" }); + assert.equal(tqqqCheck.allowed, false); + assert.equal(tqqqCheck.query_target.by, spec.expected.query_target_pre_ack_by); + assert.equal(tqqqCheck.query_target.client_order_id, spec.timeout_submission.client_order_id); + assert.equal(tqqqCheck.query_target.broker_order_id, null); + + // Non-terminal update must NOT clear the ORDER-UNKNOWN lock + const stillLocked = applyOrderUnknownObservation(reloaded, spec.non_terminal_followup); + assert.deepEqual(lockedSymbolsForAccount(stillLocked, identity), spec.expected.locked_symbols); + + const ordersState = evaluateAuthoritativeOrdersAndFills( + { + ...identity, + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:demo:d3-eval", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "longbridge_paper_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [spec.timeout_submission], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "longbridge_paper_fills", + scope: "account_executions", + cap: 512, + completeness: "complete", + truncated: false, + records: [], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "longbridge_paper_open", + scope: "cutoff_open_orders", + cap: 512, + completeness: "complete", + truncated: false, + records: [spec.non_terminal_followup], + }, + }, + }, + { lockStore: stillLocked }, + ); + assert.ok(validateOrdersFillsSchema(ordersState), ajv.errorsText(validateOrdersFillsSchema.errors)); + assert.deepEqual(ordersState.order_unknown_symbols, spec.expected.locked_symbols); + assert.equal(ordersState.summary.k_pend_usd, spec.expected.k_pend_locked_usd); + assert.equal(ordersState.summary.k_pend_release_allowed, false); + + const sized = evaluateDeployableCapitalSizing({ + account_id: identity.account, + broker: identity.broker, + environment: identity.environment, + currency: "USD", + margin_enabled: false, + h_usd: "0", + kelly_applied: false, + evaluated_at: "2026-11-24T15:00:05.000Z", + equity_usd: "5000.00", + cash_settled_usd: "5000.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + orders_fills: ordersState, + fee_schedule: { + provenance: "synthetic_fixture", + c_min_usd: "1.00", + c_per_share_usd: "0.01", + c_reg: "0.25", + b_exec_usd: "0", + }, + targets: [ + { symbol: "TQQQ", q_pre: "0", price_ref: "50.00", price_lim: "50.50", w_target: "0.20" }, + { symbol: "SOXL", q_pre: "0", price_ref: "25.00", price_lim: "25.25", w_target: "0.02" }, + ], + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:demo:d3-sizing", + }); + assert.ok(validateDeployableCapitalSchema(sized), ajv.errorsText(validateDeployableCapitalSchema.errors)); + assert.equal(sized.orders.find((o) => o.symbol === "TQQQ").delta_q_buy, spec.expected.tqqq_buy_blocked_while_locked); + assert.equal(sized.orders.find((o) => o.symbol === "SOXL").delta_q_buy, spec.expected.soxl_buy_unblocked_while_tqqq_locked); + + // Terminal broker evidence clears lock and allows release when cutoff open orders are complete & empty + const clearedStore = applyOrderUnknownObservation(stillLocked, spec.terminal_resolution); + assert.deepEqual(lockedSymbolsForAccount(clearedStore, identity), []); + const afterTerminal = evaluateAuthoritativeOrdersAndFills( + { + ...identity, + as_of: "2026-11-24T15:01:00.000Z", + evaluated_at: "2026-11-24T15:01:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:demo:d3-cleared", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:01:00.000Z", + source: "longbridge_paper_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [spec.terminal_resolution], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:01:00.000Z", + source: "longbridge_paper_fills", + scope: "account_executions", + cap: 512, + completeness: "complete", + truncated: false, + records: [], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:01:00.000Z", + source: "longbridge_paper_open", + scope: "cutoff_open_orders", + cap: 512, + completeness: "complete", + truncated: false, + records: [], + }, + }, + }, + { lockStore: clearedStore }, + ); + assert.ok(validateOrdersFillsSchema(afterTerminal)); + assert.equal(afterTerminal.summary.k_pend_usd, spec.expected.k_pend_after_terminal_with_complete_coverage); + assert.equal(afterTerminal.summary.k_pend_release_allowed, true); + }, + + async "SA2-D4"() { + const { evaluateAuthoritativeOrdersAndFills } = await import( + "../web/strategy-switch-console/application/orders_fills/helpers.js" + ); + const { deduplicateExecutions } = await import( + "../web/strategy-switch-console/application/orders_fills/dedup_state.js" + ); + const spec = demoFixture.cases["SA2-D4"]; + const paperRes = evaluateAuthoritativeOrdersAndFills(spec.paper_account); + const liveRes = evaluateAuthoritativeOrdersAndFills(spec.live_account); + assert.ok(validateOrdersFillsSchema(paperRes), ajv.errorsText(validateOrdersFillsSchema.errors)); + assert.ok(validateOrdersFillsSchema(liveRes), ajv.errorsText(validateOrdersFillsSchema.errors)); + assert.equal(paperRes.account_binding.binding_key, spec.expected.paper_binding_key); + assert.equal(liveRes.account_binding.binding_key, spec.expected.live_binding_key); + + // Same execution_ref across (longbridge, paper) vs (longbridge, live) must NEVER collide or merge + const combinedExecs = deduplicateExecutions( + [...paperRes.executions, ...liveRes.executions], + [], + ); + assert.equal(combinedExecs.length, spec.expected.isolated_distinct_executions); + assert.throws(() => evaluateAuthoritativeOrdersAndFills({ + ...spec.paper_account, + ...spec.invalid_conflated_broker, + })); + }, + + async "SA2-D5"() { + const { evaluateAuthoritativeOrdersAndFills } = await import( + "../web/strategy-switch-console/application/orders_fills/helpers.js" + ); + const spec = demoFixture.cases["SA2-D5"]; + const res = evaluateAuthoritativeOrdersAndFills(spec.partial_fill_cancel_input); + assert.ok(validateOrdersFillsSchema(res), ajv.errorsText(validateOrdersFillsSchema.errors)); + assert.equal(res.executions.length, spec.expected.executions_count); + assert.equal(res.orders.length, 1); + const ord = res.orders[0]; + assert.equal(ord.qty_submitted, spec.expected.qty_submitted); + assert.equal(ord.qty_filled, spec.expected.qty_filled); + assert.equal(ord.qty_canceled, spec.expected.qty_canceled); + assert.equal(ord.qty_remaining, spec.expected.qty_remaining); + assert.equal(ord.state, spec.expected.state); + assert.equal(res.summary.k_pend_usd, spec.expected.k_pend_usd); + assert.equal(res.summary.k_pend_release_allowed, spec.expected.k_pend_release_allowed); + + const conflictInput = structuredClone(spec.partial_fill_cancel_input); + conflictInput.domains.executions.records.push(spec.conflicting_duplicate_execution); + assert.throws(() => evaluateAuthoritativeOrdersAndFills(conflictInput), /conflicting_duplicate_execution/); + }, + + async "SA2-D6"() { + const { evaluateDomainCoverage } = await import( + "../web/strategy-switch-console/application/orders_fills/coverage.js" + ); + const spec = demoFixture.cases["SA2-D6"]; + + const trunc512 = evaluateDomainCoverage(spec.truncated_512_case); + assert.equal(trunc512.empty_domain_proven, spec.expected.truncated_512_empty_proven); + assert.equal(trunc512.k_pend_release_allowed, spec.expected.truncated_512_release_allowed); + + const incZero = evaluateDomainCoverage(spec.incomplete_zero_case); + assert.equal(incZero.empty_domain_proven, spec.expected.incomplete_zero_empty_proven); + assert.equal(incZero.k_pend_release_allowed, spec.expected.incomplete_zero_release_allowed); + + const empty512 = evaluateDomainCoverage(spec.proven_empty_512_case); + assert.equal(empty512.empty_domain_proven, spec.expected.proven_empty_512_empty_proven); + assert.equal(empty512.k_pend_release_allowed, spec.expected.proven_empty_512_release_allowed); + + const unsup = evaluateDomainCoverage(spec.unsupported_domain_case); + assert.equal(unsup.domain_capability, spec.expected.unsupported_capability); + assert.equal(unsup.count, spec.expected.unsupported_count); + assert.equal(unsup.empty_domain_proven, spec.expected.unsupported_empty_proven); + assert.equal(unsup.k_pend_release_allowed, spec.expected.unsupported_release_allowed); + }, + + async "SA2-D7"() { + const { buildConsoleOrdersFillsReadModel } = await import( + "../web/strategy-switch-console/application/console_api/executions.js" + ); + const { evaluateAuthoritativeOrdersAndFills } = await import( + "../web/strategy-switch-console/application/orders_fills/helpers.js" + ); + const { evaluateDeployableCapitalSizing } = await import( + "../web/strategy-switch-console/application/sizing_unit/deployable_capital.js" + ); + let storageWrites = 0; + let kvWrites = 0; + const spyDeps = { + kv: { + async get() { return null; }, + async put() { kvWrites++; throw new Error("forbidden_kv_write_on_read"); }, + async delete() { kvWrites++; throw new Error("forbidden_kv_delete_on_read"); }, + }, + sql: { + exec(query) { + if (!/^\s*SELECT\b/i.test(String(query))) { + storageWrites++; + throw new Error("forbidden_sql_write_on_read"); + } + return { toArray: () => [] }; + }, + }, + }; + const rm = buildConsoleOrdersFillsReadModel(demoFixture.cases["SA2-D4"].paper_account, spyDeps); + assert.ok(validateOrdersFillsSchema(rm)); + const direct = evaluateAuthoritativeOrdersAndFills(demoFixture.cases["SA2-D5"].partial_fill_cancel_input); + assert.ok(validateOrdersFillsSchema(direct)); + const sized = evaluateDeployableCapitalSizing(demoFixture.cases["SA2-D1"].zero_cash_case.input); + assert.ok(validateDeployableCapitalSchema(sized)); + assert.equal(storageWrites, demoFixture.cases["SA2-D7"].expected.storage_writes); + assert.equal(kvWrites, demoFixture.cases["SA2-D7"].expected.kv_writes); + }, +}; + +const ids = requestedCase ? [requestedCase] : Object.keys(handlers); +let failures = 0; +for (const id of ids) { + const fn = handlers[id]; + if (!fn) { + console.error(`[FAIL] ${id}: unknown demo case`); + failures++; + continue; + } + try { + await fn(); + console.log(`[PASS] ${id}: ${demoFixture.cases[id].title}`); + } catch (err) { + failures++; + console.error(`[FAIL] ${id}: ${err?.code || err?.name || "Error"}: ${err?.message || err}`); + } +} +if (failures > 0) { + console.error(`sa2_demo_validation: FAILED (${failures}/${ids.length} cases failed)`); + process.exit(1); +} +console.log(`sa2_demo_validation: PASS (${ids.length}/${ids.length} cases passed)`); diff --git a/tests/sa2_deployable_capital_validation.mjs b/tests/sa2_deployable_capital_validation.mjs new file mode 100644 index 00000000..1c51b73a --- /dev/null +++ b/tests/sa2_deployable_capital_validation.mjs @@ -0,0 +1,984 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; + +const require = createRequire(new URL("../web/strategy-switch-console/package.json", import.meta.url)); +const Ajv2020 = require("ajv/dist/2020").default; +const addFormats = require("ajv-formats"); + +const loadJson = (relPath) => JSON.parse(readFileSync(new URL(relPath, import.meta.url), "utf8")); + +const deployableCapitalSchema = loadJson("../schemas/qsl-deployable-capital-sizing.v1.schema.json"); +const pinnedCalendar = loadJson("./fixtures/sa1/csa22_pinned_vectors_2025.json"); +const matrix = loadJson("./fixtures/sa2/sa2_q21_matrix.json"); + +const ajv = new Ajv2020({ allErrors: true, strict: true, strictTypes: false }); +addFormats(ajv); +const validateSchema = ajv.compile(deployableCapitalSchema); + +const PRIVATE_LOCATOR_RE = new RegExp( + "(?:source_ref|kv_key|do_key|kv://|do://|/" + "Users/|/" + "home/|broker_account_hash|broker_account_id)", +); + +// Verify pure leaf boundary (zero Worker/runtime_support/storage/network imports) +const stripJsComments = (src) => src.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ""); +const moduleSource = stripJsComments( + readFileSync(new URL("../web/strategy-switch-console/application/sizing_unit/deployable_capital.js", import.meta.url), "utf8"), +); +assert.equal(/runtime_support|worker\.js|\bfetch\s*\(/.test(moduleSource), false); + +const { + DEPLOYABLE_CAPITAL_SCHEMA, + evaluateDeployableCapitalSizing, + evaluateWorkableBankrollBminTier, +} = await import("../web/strategy-switch-console/application/sizing_unit/deployable_capital.js"); +const { evaluateSizingUnitNav } = await import( + "../web/strategy-switch-console/application/sizing_unit/nav.js" +); +const { createPinnedCalendarProvider } = await import( + "../web/strategy-switch-console/application/sizing_unit/freshness.js" +); +const { evaluateAuthoritativeOrdersAndFills } = await import( + "../web/strategy-switch-console/application/orders_fills/helpers.js" +); + +assert.equal(DEPLOYABLE_CAPITAL_SCHEMA, "qsl.deployable_capital_sizing.v1"); + +// 1. Negative raw avail clamped to 0 + zero-cash blocks buy but not reduction +{ + const spec = matrix.cases.negative_raw_avail_clamped; + const res = evaluateDeployableCapitalSizing(spec.input); + assert.ok(validateSchema(res), ajv.errorsText(validateSchema.errors)); + assert.equal(res.status, spec.expected.status); + assert.equal(res.capital.c_inv_usd, spec.expected.c_inv_usd); + assert.equal(res.capital.raw_deployable_cash_usd, spec.expected.raw_deployable_cash_usd); + assert.equal(res.capital.c_avail_usd, spec.expected.c_avail_usd); + assert.equal(res.orders.find((o) => o.symbol === "TQQQ").delta_q_buy, spec.expected.tqqq_delta_q_buy); + assert.equal(res.orders.find((o) => o.symbol === "SOXL").delta_q_sell, spec.expected.soxl_delta_q_sell); +} + +// 2. Portfolio-level concurrent buy budget allocation with collar + fees +{ + const spec = matrix.cases.portfolio_concurrent_buy_budget; + const res = evaluateDeployableCapitalSizing(spec.input); + assert.ok(validateSchema(res), ajv.errorsText(validateSchema.errors)); + assert.equal(res.status, spec.expected.status); + assert.equal(res.capital.c_avail_usd, spec.expected.c_avail_usd); + const tqqq = res.orders.find((o) => o.symbol === "TQQQ"); + const soxl = res.orders.find((o) => o.symbol === "SOXL"); + assert.equal(tqqq.delta_q_buy, spec.expected.tqqq_delta_q_buy); + assert.equal(soxl.delta_q_buy, spec.expected.soxl_delta_q_buy); + assert.equal(res.capital.total_buy_commit_usd, spec.expected.total_buy_commit_usd); + assert.equal(res.capital.remaining_deployable_cash_usd, spec.expected.remaining_deployable_cash_usd); + assert.equal(tqqq.rho_order.value, spec.expected.tqqq_rho_order_value); + assert.equal(tqqq.rho_order.threshold, spec.expected.tqqq_rho_order_threshold); +} + +// 3. 1 share + min fee > C_avail yields 0 shares +{ + const spec = matrix.cases.one_share_exceeds_budget; + const res = evaluateDeployableCapitalSizing(spec.input); + assert.ok(validateSchema(res), ajv.errorsText(validateSchema.errors)); + assert.equal(res.orders[0].delta_q_buy, spec.expected.delta_q_buy); + assert.equal(res.orders[0].buy_blocked_reason, spec.expected.buy_blocked_reason); + assert.equal(res.capital.total_buy_commit_usd, spec.expected.total_buy_commit_usd); +} + +// 4. Rounding friction + explicit b_exec + rho_order diagnostic (threshold: null) +{ + const spec = matrix.cases.rounding_friction_and_b_exec; + const res = evaluateDeployableCapitalSizing(spec.input); + assert.ok(validateSchema(res), ajv.errorsText(validateSchema.errors)); + const ord = res.orders[0]; + assert.equal(ord.q_ideal, spec.expected.q_ideal); + assert.equal(ord.delta_q_buy, spec.expected.delta_q_buy); + assert.equal(ord.est_commission_usd, spec.expected.est_commission_usd); + assert.equal(ord.est_b_exec_usd, spec.expected.est_b_exec_usd); + assert.equal(ord.est_total_buy_commit_usd, spec.expected.est_total_buy_commit_usd); + assert.equal(ord.rho_order.rounding_friction_usd, spec.expected.rounding_friction_usd); + assert.equal(ord.rho_order.value, spec.expected.rho_order_value); + assert.equal(ord.rho_order.threshold, spec.expected.rho_order_threshold); +} + +// 5. ORDER-UNKNOWN per-symbol buy block +{ + const spec = matrix.cases.order_unknown_symbol_block; + const res = evaluateDeployableCapitalSizing(spec.input); + assert.ok(validateSchema(res), ajv.errorsText(validateSchema.errors)); + assert.equal(res.capital.c_avail_usd, spec.expected.c_avail_usd); + const tqqq = res.orders.find((o) => o.symbol === "TQQQ"); + const soxl = res.orders.find((o) => o.symbol === "SOXL"); + assert.equal(tqqq.delta_q_buy, spec.expected.tqqq_delta_q_buy); + assert.equal(tqqq.buy_blocked_reason, spec.expected.tqqq_buy_blocked_reason); + assert.equal(soxl.delta_q_buy, spec.expected.soxl_delta_q_buy); +} + +// 6. b_band suppression vs emergency_bypass +{ + const spec = matrix.cases.b_band_suppression_vs_emergency_bypass; + const suppressed = evaluateDeployableCapitalSizing(spec.discretionary_suppressed.input); + assert.ok(validateSchema(suppressed)); + assert.equal(suppressed.orders[0].band_suppressed, spec.discretionary_suppressed.expected.band_suppressed); + assert.equal(suppressed.orders[0].delta_q_final, spec.discretionary_suppressed.expected.delta_q_final); + assert.equal(suppressed.orders[0].action, spec.discretionary_suppressed.expected.action); + + const bypassed = evaluateDeployableCapitalSizing(spec.emergency_bypass_executes_sell.input); + assert.ok(validateSchema(bypassed)); + assert.equal(bypassed.orders[0].band_suppressed, spec.emergency_bypass_executes_sell.expected.band_suppressed); + assert.equal(bypassed.orders[0].emergency_bypass_applied, spec.emergency_bypass_executes_sell.expected.emergency_bypass_applied); + assert.equal(bypassed.orders[0].delta_q_final, spec.emergency_bypass_executes_sell.expected.delta_q_final); + assert.equal(bypassed.orders[0].action, spec.emergency_bypass_executes_sell.expected.action); +} + +// 7. B_min,tier < 10% vs >= 10% exact boundaries +{ + for (const [name, row] of Object.entries(matrix.cases.b_min_tier_boundaries)) { + const out = evaluateWorkableBankrollBminTier({ + bankroll_w_usd: row.bankroll_w_usd, + c_fixed_ann_usd: row.c_fixed_ann_usd, + expected_excess_growth_ann_usd: row.expected_excess_growth_ann_usd, + }); + assert.equal(out.status, row.expected.status, `${name}.status`); + assert.equal(out.workable, row.expected.workable, `${name}.workable`); + assert.equal(out.friction_ratio, row.expected.friction_ratio, `${name}.friction_ratio`); + assert.equal(out.threshold_ratio, "0.1"); + } +} + +// 8. Unset OI-COST-3 / OI-COST-4 & safety locks fail closed +{ + for (const [name, row] of Object.entries(matrix.cases.unset_oi_cost_and_safety_rejections)) { + const res = evaluateDeployableCapitalSizing(row.input); + assert.ok(validateSchema(res), `${name} schema: ${ajv.errorsText(validateSchema.errors)}`); + assert.equal(res.status, row.expected.status, `${name}.status`); + assert.equal(res.reason, row.expected.reason, `${name}.reason`); + if (row.expected.oi_cost_3_resolved !== undefined) { + assert.equal(res.fee_schedule.oi_cost_3_resolved, row.expected.oi_cost_3_resolved, `${name}.oi_cost_3_resolved`); + } + if (row.expected.oi_cost_4_resolved !== undefined) { + assert.equal(res.fee_schedule.oi_cost_4_resolved, row.expected.oi_cost_4_resolved, `${name}.oi_cost_4_resolved`); + } + assert.equal(res.margin_enabled, false); + assert.equal(res.h_usd, "0"); + assert.equal(res.kelly_applied, false); + assert.equal(PRIVATE_LOCATOR_RE.test(JSON.stringify(res)), false); + } +} + +// 9. Composition with C-SA-14 (nav.js) + C-SA-25 (orders_fills) +{ + const provider = createPinnedCalendarProvider(pinnedCalendar); + const nav = evaluateSizingUnitNav( + { + account_id: "ibkr:live:a1", + platform: "ibkr", + broker_environment: "live", + management_status: "managed", + evidence_state: "known", + currency: "USD", + nav_usd: "10000.00", + settled_cash_usd: "4000.00", + unsettled_cash_usd: "0", + tbill_nav_usd: "5000.00", + etf_market_value_usd: "1000.00", + accrued_fees_usd: "0", + margin_debt_usd: "0", + margin_enabled: false, + positions: [{ symbol: "TQQQ", qty: "20", market_value_usd: "1000.00", price_ref: "50.00" }], + observed_at: "2025-01-08T21:00:00.000Z", + fetched_at: "2025-01-08T21:00:05.000Z", + evaluated_at: "2025-01-08T21:01:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:a13:sa1-nav", + }, + { calendarProvider: provider, require_live_cohort: true }, + ); + assert.equal(nav.status, "available"); + + const ordersFills = evaluateAuthoritativeOrdersAndFills({ + broker: "ibkr", + environment: "live", + account: "ibkr:live:a1", + as_of: "2025-01-08T21:00:30.000Z", + evaluated_at: "2025-01-08T21:01:00.000Z", + origin: "synthetic", + source_class: "authorized_live_broker", + evidence_ref: "sa2:a13:sa2-of", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2025-01-08T21:00:30.000Z", + source: "ibkr_open", + scope: "cutoff_open_orders", + cap: 256, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-ibkr-open-1", + broker_order_id: "brk-ibkr-1", + symbol: "SOXL", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "25.00", + currency: "USD", + reserved_fee_usd: "1.25", + as_of: "2025-01-08T21:00:30.000Z", + evidence_ref: "sa2:a13:open-soxl", + }, + ], + }, + }, + }); + assert.equal(ordersFills.summary.k_pend_usd, "251.25"); + + const composed = evaluateDeployableCapitalSizing({ + sizing_unit_nav: nav, + orders_fills: ordersFills, + r_cash_usd: "100.00", + proceeds_eligible_usd: "0", + fee_schedule: { + provenance: "synthetic_fixture", + c_min_usd: "1.00", + c_per_share_usd: "0.01", + c_reg: "0.25", + b_exec_usd: "0", + }, + targets: [{ symbol: "TQQQ", q_pre: "20", price_ref: "50.00", price_lim: "50.50", w_target: "0.30" }], + evaluated_at: "2025-01-08T21:01:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:a13:composed", + }); + assert.ok(validateSchema(composed), ajv.errorsText(validateSchema.errors)); + assert.equal(composed.capital.c_inv_usd, "1000.00"); + assert.equal(composed.capital.k_pend_usd, "251.25"); + assert.equal(composed.capital.c_avail_usd, "3648.75"); + assert.equal(composed.orders[0].delta_q_buy, "40"); +} + +// 10. P1 regression guards for C-SA-Q21 (#1, #8-#14) +{ + // #1 (Q21): Unsupported/incomplete open-orders (k_pend_usd: null) blocks buys while keeping reductions unblocked. + const unprovenOrdersFills = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:q21:p1:unproven-of", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + }, + }); + assert.equal(unprovenOrdersFills.summary.k_pend_usd, null); + const q21UnknownKPend = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + currency: "USD", + margin_enabled: false, + h_usd: "0", + kelly_applied: false, + evaluated_at: "2026-11-24T15:00:05.000Z", + equity_usd: "10000.00", + cash_settled_usd: "5000.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + orders_fills: unprovenOrdersFills, + fee_schedule: { + provenance: "synthetic_fixture", + c_min_usd: "1.00", + c_per_share_usd: "0.01", + c_reg: "0.25", + b_exec_usd: "0", + }, + targets: [ + { symbol: "TQQQ", q_pre: "0", price_ref: "50.00", price_lim: "50.50", w_target: "0.10" }, + { symbol: "SOXL", q_pre: "20", price_ref: "25.00", price_lim: "25.25", w_target: "0.025" }, + ], + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:q21:p1:unknown-kpend", + }); + assert.ok(validateSchema(q21UnknownKPend), ajv.errorsText(validateSchema.errors)); + assert.equal(q21UnknownKPend.status, "available"); + assert.equal(q21UnknownKPend.capital.k_pend_usd, null); + assert.equal(q21UnknownKPend.capital.k_pend_release_allowed, false); + assert.equal(q21UnknownKPend.capital.c_avail_usd, "0"); + assert.equal(q21UnknownKPend.orders.find((o) => o.symbol === "TQQQ").action, "BLOCKED_BUY"); + assert.equal(q21UnknownKPend.orders.find((o) => o.symbol === "TQQQ").delta_q_buy, "0"); + assert.equal(q21UnknownKPend.orders.find((o) => o.symbol === "SOXL").action, "SELL"); + assert.equal(q21UnknownKPend.orders.find((o) => o.symbol === "SOXL").delta_q_sell, "10"); + + // #8: Invalid order_unknown_symbols returns structured unavailable without TDZ ReferenceError. + const badUnknownList = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + evaluated_at: "2026-11-24T15:00:00.000Z", + order_unknown_symbols: "TQQQ", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [], + }); + assert.ok(validateSchema(badUnknownList)); + assert.equal(badUnknownList.status, "unavailable"); + assert.equal(badUnknownList.reason, "invalid_order_unknown_symbols"); + + const badUnknownSym = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + evaluated_at: "2026-11-24T15:00:00.000Z", + order_unknown_symbols: ["U" + "1234567"], + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [], + }); + assert.ok(validateSchema(badUnknownSym)); + assert.equal(badUnknownSym.status, "unavailable"); + assert.equal(badUnknownSym.reason, "invalid_order_unknown_symbol"); + + // #9a: Top-level account vs orders_fills mismatch (without nav) must fail closed. + const crossAccountRelabel = evaluateDeployableCapitalSizing({ + account_id: "ibkr:live:a1", + broker: "ibkr", + environment: "live", + evaluated_at: "2026-11-24T15:00:05.000Z", + equity_usd: "10000.00", + cash_settled_usd: "5000.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + orders_fills: unprovenOrdersFills, + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [], + }); + assert.ok(validateSchema(crossAccountRelabel)); + assert.equal(crossAccountRelabel.status, "unavailable"); + assert.equal(crossAccountRelabel.reason, "raw_orders_broker_mismatch"); + + // #10: Omitting b_exec_usd must fail closed as oi_cost_3_fee_schedule_unavailable. + const missingBExec = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + evaluated_at: "2026-11-24T15:00:00.000Z", + equity_usd: "10000.00", + cash_settled_usd: "5000.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + k_pend_usd: "0", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25" }, + targets: [{ symbol: "TQQQ", q_pre: "0", price_ref: "50.00", price_lim: "50.50", w_target: "0.10" }], + }); + assert.ok(validateSchema(missingBExec)); + assert.equal(missingBExec.status, "unavailable"); + assert.equal(missingBExec.reason, "oi_cost_3_fee_schedule_unavailable"); + assert.equal(missingBExec.fee_schedule.oi_cost_3_resolved, false); + + // #11: Buy missing O5 collar in a mixed portfolio with C_avail = 0 keeps reduction SELL unblocked. + const mixedBuyNoCollarPlusSell = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + evaluated_at: "2026-11-24T15:00:00.000Z", + equity_usd: "10000.00", + cash_settled_usd: "0", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + k_pend_usd: "0", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [ + { symbol: "TQQQ", q_pre: "0", price_ref: "50.00", price_lim: null, w_target: "0.10" }, + { symbol: "SOXL", q_pre: "20", price_ref: "25.00", price_lim: null, w_target: "0.025" }, + ], + }); + assert.ok(validateSchema(mixedBuyNoCollarPlusSell), ajv.errorsText(validateSchema.errors)); + assert.equal(mixedBuyNoCollarPlusSell.status, "available"); + assert.equal(mixedBuyNoCollarPlusSell.fee_schedule.oi_cost_4_resolved, false); + const blockedBuy = mixedBuyNoCollarPlusSell.orders.find((o) => o.symbol === "TQQQ"); + const unblockedSell = mixedBuyNoCollarPlusSell.orders.find((o) => o.symbol === "SOXL"); + assert.equal(blockedBuy.action, "BLOCKED_BUY"); + assert.equal(blockedBuy.delta_q_buy, "0"); + assert.equal(blockedBuy.buy_blocked_reason, "oi_cost_4_price_collar_unavailable"); + assert.equal(unblockedSell.action, "SELL"); + assert.equal(unblockedSell.delta_q_sell, "10"); + + // #12: emergency_bypass rejects string "false" / non-boolean and enforces strict boolean precedence. + const stringBypass = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + evaluated_at: "2026-11-24T15:00:00.000Z", + equity_usd: "10000.00", + cash_settled_usd: "5000.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + k_pend_usd: "0", + b_band: "0.20", + emergency_bypass: "false", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "SOXL", q_pre: "20", price_ref: "25.00", price_lim: "25.25", w_target: "0.045" }], + }); + assert.ok(validateSchema(stringBypass)); + assert.equal(stringBypass.status, "unavailable"); + assert.equal(stringBypass.reason, "invalid_emergency_bypass"); + + const precedenceBypass = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + evaluated_at: "2026-11-24T15:00:00.000Z", + equity_usd: "10000.00", + cash_settled_usd: "0", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + k_pend_usd: "0", + b_band: "0.20", + emergency_bypass: true, + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [ + { symbol: "SOXL", q_pre: "20", price_ref: "25.00", price_lim: "25.25", w_target: "0.045", emergency_bypass: false }, + { symbol: "TQQQ", q_pre: "10", price_ref: "50.00", price_lim: "50.50", w_target: "0.045" }, + ], + }); + assert.ok(validateSchema(precedenceBypass)); + assert.equal(precedenceBypass.orders.find((o) => o.symbol === "SOXL").action, "HOLD"); + assert.equal(precedenceBypass.orders.find((o) => o.symbol === "SOXL").emergency_bypass_applied, false); + assert.equal(precedenceBypass.orders.find((o) => o.symbol === "TQQQ").action, "SELL"); + assert.equal(precedenceBypass.orders.find((o) => o.symbol === "TQQQ").emergency_bypass_applied, true); + + // #13a: Held non-zero position without valuation fails closed instead of C_inv = 0. + const unpricedPosition = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + evaluated_at: "2026-11-24T15:00:00.000Z", + equity_usd: "10000.00", + cash_settled_usd: "5000.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + k_pend_usd: "0", + positions: [{ symbol: "QQQ", qty: "10" }], + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [], + }); + assert.ok(validateSchema(unpricedPosition)); + assert.equal(unpricedPosition.status, "unavailable"); + assert.equal(unpricedPosition.reason, "held_position_valuation_unavailable"); + assert.equal(unpricedPosition.capital.c_inv_usd, null); + + // #13b: B_min,tier missing annual_rounding_friction_usd or annual_passthrough_usd fails closed as unavailable. + const feeModelResolved = { ok: true, cMinRat: { n: 1n, d: 1n }, cRegSpec: { fixed: { n: 1n, d: 4n } } }; + const incompleteBmin = evaluateWorkableBankrollBminTier({ + bankroll_w_usd: "50000.00", + annual_ticket_count: 10, + fee_schedule_resolved: feeModelResolved, + expected_excess_growth_ann_usd: "5000.00", + }); + assert.equal(incompleteBmin.status, "unavailable"); + assert.equal(incompleteBmin.workable, null); + assert.equal(incompleteBmin.reason, "incomplete_fixed_annual_cost_inputs"); + + const completeBmin = evaluateWorkableBankrollBminTier({ + bankroll_w_usd: "50000.00", + annual_ticket_count: 10, + annual_rounding_friction_usd: "50.00", + annual_passthrough_usd: "10.00", + fee_schedule_resolved: feeModelResolved, + expected_excess_growth_ann_usd: "5000.00", + }); + assert.equal(completeBmin.status, "available"); + assert.equal(completeBmin.c_fixed_ann_usd, "72.50"); + assert.equal(completeBmin.workable, true); + + // #14: sizing_unit_nav.reason containing raw account / token / private locator is sanitized, never echoed. + const leakyNavRes = evaluateDeployableCapitalSizing({ + account_id: "ibkr:live:a1", + broker: "ibkr", + environment: "live", + evaluated_at: "2026-11-24T15:00:00.000Z", + sizing_unit_nav: { + account_id: "ibkr:live:a1", + platform: "ibkr", + broker_environment: "live", + status: "unavailable", + reason: "account token " + "U" + "1234567 kv:" + "//bucket/secret", + currency: "USD", + freshness: { data_status: "unavailable" }, + }, + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [], + }); + assert.ok(validateSchema(leakyNavRes), ajv.errorsText(validateSchema.errors)); + assert.equal(leakyNavRes.status, "unavailable"); + assert.equal(leakyNavRes.reason, "sizing_unit_nav_unavailable"); + assert.equal(JSON.stringify(leakyNavRes).includes("account token"), false); + assert.equal(JSON.stringify(leakyNavRes).includes("U" + "1234567"), false); + assert.equal(PRIVATE_LOCATOR_RE.test(JSON.stringify(leakyNavRes)), false); + + const unsafeEvidence = evaluateDeployableCapitalSizing({ + account_id: "longbridge:paper:pilot", + broker: "longbridge", + environment: "paper", + evaluated_at: "2026-11-24T15:00:00.000Z", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [], + evidence_ref: "kv:" + "//bucket/secret", + }); + assert.ok(validateSchema(unsafeEvidence)); + assert.equal(unsafeEvidence.status, "unavailable"); + assert.equal(unsafeEvidence.reason, "unsafe_evidence_ref"); + assert.equal(PRIVATE_LOCATOR_RE.test(JSON.stringify(unsafeEvidence)), false); +} + +// 11. Codex review regression (#3 PRRT_kwDOSZeN-M67n_nm: stale nonzero target q_pre absent from complete nav.positions) +{ + const provider = createPinnedCalendarProvider(pinnedCalendar); + const allCashNav = evaluateSizingUnitNav( + { + account_id: "ibkr:live:a1", + platform: "ibkr", + broker_environment: "live", + management_status: "managed", + evidence_state: "known", + currency: "USD", + nav_usd: "10000.00", + settled_cash_usd: "10000.00", + unsettled_cash_usd: "0", + tbill_nav_usd: "0", + etf_market_value_usd: "0", + accrued_fees_usd: "0", + margin_debt_usd: "0", + margin_enabled: false, + positions: [], + observed_at: "2025-01-08T21:00:00.000Z", + fetched_at: "2025-01-08T21:00:05.000Z", + evaluated_at: "2025-01-08T21:01:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex:all-cash-nav", + }, + { calendarProvider: provider, require_live_cohort: true }, + ); + assert.equal(allCashNav.status, "available"); + + // Stale nonzero q_pre on symbol absent from nav.positions: [] must fail closed instead of selling unheld shares. + const oversellBlocked = evaluateDeployableCapitalSizing({ + sizing_unit_nav: allCashNav, + r_cash_usd: "0", + proceeds_eligible_usd: "0", + k_pend_usd: "0", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "ABC", q_pre: "10", price_ref: "50.00", price_lim: "50.50", w_target: "0" }], + evaluated_at: "2025-01-08T21:01:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex:oversell-blocked", + }); + assert.ok(validateSchema(oversellBlocked), ajv.errorsText(validateSchema.errors)); + assert.equal(oversellBlocked.status, "unavailable"); + assert.equal(oversellBlocked.reason, "positions_target_q_pre_mismatch"); + assert.equal(oversellBlocked.orders.length, 0); + + // Target absent from nav.positions: [] with q_pre === "0" is genuinely zero-held and allowed to BUY cleanly. + const freshBuyAllowed = evaluateDeployableCapitalSizing({ + sizing_unit_nav: allCashNav, + r_cash_usd: "0", + proceeds_eligible_usd: "0", + k_pend_usd: "0", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "ABC", q_pre: "0", price_ref: "50.00", price_lim: "50.50", w_target: "0.05" }], + evaluated_at: "2025-01-08T21:01:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex:fresh-buy-ok", + }); + assert.ok(validateSchema(freshBuyAllowed), ajv.errorsText(validateSchema.errors)); + assert.equal(freshBuyAllowed.status, "available"); + assert.equal(freshBuyAllowed.orders[0].action, "BUY"); + assert.equal(freshBuyAllowed.orders[0].delta_q_buy, "10"); + + // Codex round-3 #2 (PRRT_kwDOSZeN-M67o1UW): Reject orders_fills evaluated after sizing boundary (no look-ahead cash release). + const ofAt1602 = evaluateAuthoritativeOrdersAndFills({ + broker: "ibkr", + environment: "live", + account: "ibkr:live:a1", + as_of: "2026-11-24T16:02:00.000Z", + evaluated_at: "2026-11-24T16:02:00.000Z", + origin: "synthetic", + source_class: "authorized_live_broker", + evidence_ref: "sa2:codex-r3:of-1602", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T16:02:00.000Z", + source: "ibkr_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-fill-1600", + broker_order_id: "brk-fill-1600", + symbol: "AAPL", + side: "BUY", + state: "FILLED", + qty_submitted: "10", + limit_price: "50", + currency: "USD", + fee_native: null, + fee_currency: null, + submitted_at: "2026-11-24T14:55:00.000Z", + resolved_at: "2026-11-24T16:00:00.000Z", + evidence_ref: "sa2:codex-r3:sub-1600", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T16:02:00.000Z", + source: "ibkr_execs", + scope: "account_executions", + cap: 512, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + execution_ref: "exec-fill-1600", + client_order_id: "ord-fill-1600", + broker_order_id: "brk-fill-1600", + symbol: "AAPL", + side: "BUY", + qty: "10", + price: "50", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: "2026-11-24T16:00:00.000Z", + evidence_ref: "sa2:codex-r3:ex-1600", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T16:02:00.000Z", + source: "ibkr_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }); + assert.equal(ofAt1602.summary.k_pend_usd, "0"); + + const lookaheadRejectedRawEval = evaluateDeployableCapitalSizing({ + broker: "ibkr", + environment: "live", + account_id: "ibkr:live:a1", + evaluated_at: "2026-11-24T15:02:00.000Z", + equity_usd: "1000.00", + cash_settled_usd: "500.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + orders_fills: ofAt1602, + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "AAPL", q_pre: "0", price_ref: "50.00", price_lim: "50.50", w_target: "1" }], + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r3:lookahead-raw", + }); + assert.ok(validateSchema(lookaheadRejectedRawEval), ajv.errorsText(validateSchema.errors)); + assert.equal(lookaheadRejectedRawEval.status, "unavailable"); + assert.equal(lookaheadRejectedRawEval.reason, "orders_fills_evaluated_after_sizing_boundary"); + assert.equal(lookaheadRejectedRawEval.orders.length, 0); + + const lookaheadRejectedOptEval = evaluateDeployableCapitalSizing({ + broker: "ibkr", + environment: "live", + account_id: "ibkr:live:a1", + equity_usd: "1000.00", + cash_settled_usd: "500.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + orders_fills: ofAt1602, + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "AAPL", q_pre: "0", price_ref: "50.00", price_lim: "50.50", w_target: "1" }], + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r3:lookahead-opt", + }, { evaluated_at: "2026-11-24T15:02:00.000Z" }); + assert.ok(validateSchema(lookaheadRejectedOptEval), ajv.errorsText(validateSchema.errors)); + assert.equal(lookaheadRejectedOptEval.status, "unavailable"); + assert.equal(lookaheadRejectedOptEval.reason, "orders_fills_evaluated_after_sizing_boundary"); + assert.equal(lookaheadRejectedOptEval.orders.length, 0); + + // Positive control: orders_fills evaluated at 16:02 composed into sizing at 16:02 succeeds cleanly. + const sameBoundaryOk = evaluateDeployableCapitalSizing({ + broker: "ibkr", + environment: "live", + account_id: "ibkr:live:a1", + evaluated_at: "2026-11-24T16:02:00.000Z", + equity_usd: "1000.00", + cash_settled_usd: "500.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + orders_fills: ofAt1602, + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "AAPL", q_pre: "0", price_ref: "50.00", price_lim: "50.50", w_target: "0.5" }], + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r3:same-boundary-ok", + }); + assert.ok(validateSchema(sameBoundaryOk), ajv.errorsText(validateSchema.errors)); + assert.equal(sameBoundaryOk.status, "available"); + + // Compose Codex round-3 #1 into sizing: untimed execution without cutoff keeps $500 reserved so other buys cannot spend it. + const untimedOrdersFills = evaluateAuthoritativeOrdersAndFills({ + broker: "ibkr", + environment: "live", + account: "ibkr:live:a1", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "authorized_live_broker", + evidence_ref: "sa2:codex-r3:untimed-sizing", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "ibkr_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-untimed-sz", + broker_order_id: "brk-untimed-sz", + symbol: "MSFT", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + limit_price: "50", + estimated_fee_usd: "0", + currency: "USD", + fee_native: null, + fee_currency: null, + submitted_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r3:sub-untimed-sz", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "ibkr_execs", + scope: "account_executions", + cap: 512, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + execution_ref: "exec-untimed-sz", + client_order_id: "ord-untimed-sz", + broker_order_id: "brk-untimed-sz", + symbol: "MSFT", + side: "BUY", + qty: "10", + price: "50", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: null, + evidence_ref: "sa2:codex-r3:ex-untimed-sz", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "ibkr_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }); + const untimedBuyBlocked = evaluateDeployableCapitalSizing({ + broker: "ibkr", + environment: "live", + account_id: "ibkr:live:a1", + evaluated_at: "2026-11-24T15:02:00.000Z", + equity_usd: "1000.00", + cash_settled_usd: "500.00", + proceeds_eligible_usd: "0", + r_cash_usd: "0", + orders_fills: untimedOrdersFills, + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "AAPL", q_pre: "0", price_ref: "50.00", price_lim: "50.50", w_target: "0.5" }], + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r3:untimed-buy-blocked", + }); + assert.ok(validateSchema(untimedBuyBlocked), ajv.errorsText(validateSchema.errors)); + assert.equal(untimedBuyBlocked.capital.k_pend_usd, "500.00"); + assert.equal(untimedBuyBlocked.capital.k_pend_release_allowed, false); + assert.equal(untimedBuyBlocked.capital.c_avail_usd, "0"); + assert.equal(untimedBuyBlocked.orders[0].delta_q_buy, "0"); + assert.equal(untimedBuyBlocked.orders[0].buy_blocked_reason, "zero_deployable_cash"); + + // Codex round-4 #1 (PRRT_kwDOSZeN-M67pKBv): Reject NAV observed/evaluated after sizing boundary & re-check freshness. + const providerR4 = createPinnedCalendarProvider(pinnedCalendar); + const futureNav2100 = evaluateSizingUnitNav( + { + account_id: "ibkr:live:a1", + platform: "ibkr", + broker_environment: "live", + management_status: "managed", + evidence_state: "known", + currency: "USD", + nav_usd: "5000.00", + settled_cash_usd: "5000.00", + unsettled_cash_usd: "0", + tbill_nav_usd: "0", + etf_market_value_usd: "0", + accrued_fees_usd: "0", + margin_debt_usd: "0", + margin_enabled: false, + positions: [], + observed_at: "2025-01-08T21:00:00.000Z", + fetched_at: "2025-01-08T21:00:05.000Z", + evaluated_at: "2025-01-08T21:01:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r4:nav-2100", + }, + { calendarProvider: providerR4, require_live_cohort: true }, + ); + assert.equal(futureNav2100.status, "available"); + + const earlyBoundarySizing = evaluateDeployableCapitalSizing({ + sizing_unit_nav: futureNav2100, + r_cash_usd: "0", + proceeds_eligible_usd: "0", + k_pend_usd: "0", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "AAPL", q_pre: "0", price_ref: "50.00", price_lim: "50.00", w_target: "1" }], + evaluated_at: "2025-01-08T20:00:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r4:early-sizing", + }); + assert.ok(validateSchema(earlyBoundarySizing), ajv.errorsText(validateSchema.errors)); + assert.equal(earlyBoundarySizing.status, "unavailable"); + assert.equal(earlyBoundarySizing.reason, "nav_observed_after_sizing_boundary"); + assert.equal(earlyBoundarySizing.orders.length, 0); + + // Pre-close NAV (20:30 observed, 20:31 fresh) becomes stale after 21:00Z XNYS close when sizing runs at 21:30Z. + const preCloseNav = evaluateSizingUnitNav( + { + account_id: "ibkr:live:a1", + platform: "ibkr", + broker_environment: "live", + management_status: "managed", + evidence_state: "known", + currency: "USD", + nav_usd: "5000.00", + settled_cash_usd: "5000.00", + unsettled_cash_usd: "0", + tbill_nav_usd: "0", + etf_market_value_usd: "0", + accrued_fees_usd: "0", + margin_debt_usd: "0", + margin_enabled: false, + positions: [], + observed_at: "2025-01-08T20:30:00.000Z", + fetched_at: "2025-01-08T20:30:05.000Z", + evaluated_at: "2025-01-08T20:31:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r4:nav-pre-close", + }, + { calendarProvider: providerR4, require_live_cohort: true }, + ); + assert.equal(preCloseNav.status, "available"); + assert.equal(preCloseNav.freshness.data_status, "fresh"); + + const staleAfterClose = evaluateDeployableCapitalSizing( + { + sizing_unit_nav: preCloseNav, + r_cash_usd: "0", + proceeds_eligible_usd: "0", + k_pend_usd: "0", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "AAPL", q_pre: "0", price_ref: "50.00", price_lim: "50.00", w_target: "1" }], + evaluated_at: "2025-01-08T21:30:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r4:stale-after-close", + }, + { calendarProvider: providerR4 }, + ); + assert.ok(validateSchema(staleAfterClose), ajv.errorsText(validateSchema.errors)); + assert.equal(staleAfterClose.status, "unavailable"); + assert.equal(staleAfterClose.reason, "snapshot_stale"); + assert.equal(staleAfterClose.orders.length, 0); + + // Later sizing timestamp without calendarProvider also fails closed rather than trusting cached freshness. + const laterWithoutCal = evaluateDeployableCapitalSizing({ + sizing_unit_nav: preCloseNav, + r_cash_usd: "0", + proceeds_eligible_usd: "0", + k_pend_usd: "0", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [{ symbol: "AAPL", q_pre: "0", price_ref: "50.00", price_lim: "50.00", w_target: "1" }], + evaluated_at: "2025-01-08T21:30:00.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r4:no-cal", + }); + assert.ok(validateSchema(laterWithoutCal)); + assert.equal(laterWithoutCal.status, "unavailable"); + assert.equal(laterWithoutCal.reason, "calendar_provider_unavailable"); + + // NAV observed before sizing (20:30) but evaluated_at after sizing (20:31 vs 20:30:10) also fails closed. + const navEvaluatedAfterSizing = evaluateDeployableCapitalSizing({ + sizing_unit_nav: preCloseNav, + r_cash_usd: "0", + proceeds_eligible_usd: "0", + k_pend_usd: "0", + fee_schedule: { provenance: "synthetic_fixture", c_min_usd: "1.00", c_per_share_usd: "0.01", c_reg: "0.25", b_exec_usd: "0" }, + targets: [], + evaluated_at: "2025-01-08T20:30:10.000Z", + origin: "synthetic", + source_class: "synthetic", + evidence_ref: "sa2:codex-r4:nav-eval-after", + }); + assert.ok(validateSchema(navEvaluatedAfterSizing)); + assert.equal(navEvaluatedAfterSizing.status, "unavailable"); + assert.equal(navEvaluatedAfterSizing.reason, "nav_evaluated_after_sizing_boundary"); +} + +console.log("sa2_deployable_capital_validation: PASS (SA-A13)"); diff --git a/tests/sa2_orders_fills_validation.mjs b/tests/sa2_orders_fills_validation.mjs new file mode 100644 index 00000000..78899f58 --- /dev/null +++ b/tests/sa2_orders_fills_validation.mjs @@ -0,0 +1,2501 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; + +const require = createRequire(new URL("../web/strategy-switch-console/package.json", import.meta.url)); +const Ajv2020 = require("ajv/dist/2020").default; +const addFormats = require("ajv-formats"); + +const loadJson = (relPath) => JSON.parse(readFileSync(new URL(relPath, import.meta.url), "utf8")); + +const ordersFillsSchema = loadJson("../schemas/qsl-authoritative-orders-fills.v1.schema.json"); +const matrix = loadJson("./fixtures/sa2/sa2_orders_fills_matrix.json"); + +const ajv = new Ajv2020({ allErrors: true, strict: true, strictTypes: false }); +addFormats(ajv); +const validateSchema = ajv.compile(ordersFillsSchema); + +const PRIVATE_LOCATOR_RE = new RegExp( + "(?:source_ref|kv_key|do_key|kv://|do://|/" + "Users/|/" + "home/|broker_account_hash|broker_account_id)", +); + +const { + ALLOWED_ORDER_BROKERS, + ALLOWED_ORDER_ENVIRONMENTS, + ORDER_DOMAIN_CAPS, + ORDER_LIFECYCLE_STATES, +} = await import("../web/strategy-switch-console/application/orders_fills/constants.js"); +const { evaluateDomainCoverage } = await import( + "../web/strategy-switch-console/application/orders_fills/coverage.js" +); +const { adaptLegacyBrokerExecutionPayload, normalizeBrokerIdentity } = await import( + "../web/strategy-switch-console/application/orders_fills/normalize.js" +); +const { deduplicateExecutions, reconcileOrdersAndFills } = await import( + "../web/strategy-switch-console/application/orders_fills/dedup_state.js" +); +const { + applyOrderUnknownObservation, + checkSymbolOrderAllowed, + createOrderUnknownLockStore, + deserializeOrderUnknownLockStore, + listActiveOrderUnknownLocks, + lockedSymbolsForAccount, + serializeOrderUnknownLockStore, +} = await import("../web/strategy-switch-console/application/orders_fills/order_unknown_lock.js"); +const { evaluateAuthoritativeOrdersAndFills } = await import( + "../web/strategy-switch-console/application/orders_fills/helpers.js" +); + +// 0. Leaf boundary checks (constants.js zero imports; zero Worker/runtime_support/storage/network imports). +const stripJsComments = (src) => src.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ""); +for (const modName of [ + "constants.js", + "coverage.js", + "normalize.js", + "dedup_state.js", + "order_unknown_lock.js", + "helpers.js", +]) { + const code = stripJsComments( + readFileSync(new URL(`../web/strategy-switch-console/application/orders_fills/${modName}`, import.meta.url), "utf8"), + ); + if (modName === "constants.js") { + assert.equal(/\bimport\b|\brequire\s*\(/.test(code), false, "orders_fills/constants.js must have zero imports"); + } + assert.equal(/runtime_support|worker\.js|\bfetch\s*\(/.test(code), false, `${modName} violates leaf boundary`); +} + +assert.deepEqual(ALLOWED_ORDER_BROKERS, ["schwab", "firstrade", "ibkr", "longbridge", "binance"]); +assert.deepEqual(ALLOWED_ORDER_ENVIRONMENTS, ["live", "paper"]); +assert.deepEqual(ORDER_DOMAIN_CAPS, [256, 512, 2048]); +assert.ok(ORDER_LIFECYCLE_STATES.includes("PARTIAL_CANCEL")); +assert.ok(ORDER_LIFECYCLE_STATES.includes("ORDER_UNKNOWN")); + +// 1. Multi-broker & environment separation across all 5 canonical brokers + invalid identity rejections +{ + const seenKeys = new Set(); + for (const acct of matrix.cases.multi_broker_separation.accounts) { + const id = normalizeBrokerIdentity(acct); + assert.equal(id.broker, acct.broker); + assert.equal(id.environment, acct.environment); + assert.equal(id.account, acct.account); + assert.equal(seenKeys.has(id.binding_key), false); + seenKeys.add(id.binding_key); + + const res = evaluateAuthoritativeOrdersAndFills({ + broker: acct.broker, + environment: acct.environment, + account: acct.account, + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: acct.source_class, + evidence_ref: `sa2:a12:${acct.broker}:${acct.environment}`, + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: `${acct.broker}_${acct.environment}_orders`, + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-shared-cross-venue", + broker_order_id: `brk-${acct.broker}-${acct.environment}`, + symbol: acct.symbol, + side: "BUY", + state: "FILLED", + qty_submitted: "1", + limit_price: acct.price, + currency: "USD", + fee_native: null, + fee_currency: null, + submitted_at: "2026-11-24T14:50:00.000Z", + evidence_ref: `sa2:a12:sub:${acct.broker}`, + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: `${acct.broker}_${acct.environment}_fills`, + scope: "account_executions", + cap: 2048, + completeness: "complete", + truncated: false, + records: [ + { + execution_ref: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + report_ref: "1111111111111111111111111111111111111111111111111111111111111111", + client_order_id: "ord-shared-cross-venue", + broker_order_id: `brk-${acct.broker}-${acct.environment}`, + symbol: acct.symbol, + side: "BUY", + qty: "1", + price: acct.price, + currency: "USD", + fee_native: null, + fee_currency: null, + executed_at: "2026-11-24T14:51:00.000Z", + evidence_ref: `sa2:a12:exec:${acct.broker}`, + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: `${acct.broker}_${acct.environment}_open`, + scope: "cutoff_open_orders", + cap: 256, + completeness: "complete", + truncated: false, + records: [], + }, + }, + }); + assert.ok(validateSchema(res), `${acct.broker}/${acct.environment}: ${ajv.errorsText(validateSchema.errors)}`); + assert.equal(PRIVATE_LOCATOR_RE.test(JSON.stringify(res)), false); + } + assert.equal(seenKeys.size, matrix.cases.multi_broker_separation.accounts.length); + + for (const bad of matrix.cases.multi_broker_separation.invalid_inputs) { + assert.throws(() => normalizeBrokerIdentity(bad), `${bad.name} must throw`); + } + + // Dynamic raw account ID & private locator negative controls (kept out of static JSON fixtures). + const dynamicBadAccounts = [ + { name: "raw_u_account_rejected", broker: "ibkr", environment: "live", account: "U" + "1234567" }, + { name: "raw_du_account_rejected", broker: "ibkr", environment: "paper", account: "DU" + "987654" }, + { name: "raw_6digit_account_rejected", broker: "schwab", environment: "live", account: "1234" + "5678" }, + { name: "raw_split_digits_rejected", broker: "schwab", environment: "live", account: ["12", "34", "56"].join("-") }, + { name: "private_kv_locator_rejected", broker: "ibkr", environment: "live", account: "kv:" + "//ibkr/live/a1" }, + ]; + for (const bad of dynamicBadAccounts) { + assert.throws(() => normalizeBrokerIdentity(bad), `${bad.name} must throw`); + } +} + +// 2. Identical + supplemental dedup vs conflicting duplicates +{ + const spec = matrix.cases.dedup_and_lifecycle.identical_and_supplemental_dedup; + const res = evaluateAuthoritativeOrdersAndFills({ + broker: spec.broker, + environment: spec.environment, + account: spec.account, + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:a12:dedup-lifecycle", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "longbridge_paper_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: spec.submissions, + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "longbridge_paper_fills", + scope: "account_executions", + cap: 512, + completeness: "complete", + truncated: false, + records: spec.executions, + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "longbridge_paper_open", + scope: "cutoff_open_orders", + cap: 512, + completeness: "complete", + truncated: false, + records: spec.cutoff_open_orders, + }, + }, + }); + assert.ok(validateSchema(res), ajv.errorsText(validateSchema.errors)); + assert.equal(res.executions.length, spec.expected.executions_count); + assert.equal(res.executions[0].fee_usd, spec.expected.fee_usd); + assert.equal(res.orders[0].qty_submitted, spec.expected.qty_submitted); + assert.equal(res.orders[0].qty_filled, spec.expected.qty_filled); + assert.equal(res.orders[0].qty_remaining, spec.expected.qty_remaining); + assert.equal(res.summary.k_pend_usd, spec.expected.k_pend_usd); + + for (const conflict of matrix.cases.dedup_and_lifecycle.conflicting_execution_cases) { + const base = { + broker: spec.broker, + environment: spec.environment, + account: spec.account, + ...spec.executions[1], + }; + const bad = { ...base, ...conflict.patch }; + assert.throws(() => deduplicateExecutions([bad], [base]), /conflicting_duplicate_execution/, conflict.name); + } +} + +// 3. Pre-ack vs post-ack ORDER-UNKNOWN locks & restart persistence +{ + const spec = matrix.cases.order_unknown_recovery; + let store = createOrderUnknownLockStore(); + store = applyOrderUnknownObservation(store, spec.pre_ack_timeout); + store = applyOrderUnknownObservation(store, spec.post_ack_timeout); + const reloaded = deserializeOrderUnknownLockStore(JSON.parse(JSON.stringify(serializeOrderUnknownLockStore(store)))); + + const preCheck = checkSymbolOrderAllowed(reloaded, { + broker: spec.pre_ack_timeout.broker, + environment: spec.pre_ack_timeout.environment, + account: spec.pre_ack_timeout.account, + symbol: "TQQQ", + }); + assert.equal(preCheck.allowed, false); + assert.equal(preCheck.query_target.by, spec.expected.pre_ack_query_by); + assert.equal(preCheck.lock.k_pend_usd, spec.expected.pre_ack_k_pend_usd); + + const postCheck = checkSymbolOrderAllowed(reloaded, { + broker: spec.post_ack_timeout.broker, + environment: spec.post_ack_timeout.environment, + account: spec.post_ack_timeout.account, + symbol: "SOXL", + }); + assert.equal(postCheck.allowed, false); + assert.equal(postCheck.query_target.by, spec.expected.post_ack_query_by); + assert.equal(postCheck.query_target.broker_order_id, spec.post_ack_timeout.broker_order_id); + assert.equal(postCheck.lock.k_pend_usd, spec.expected.post_ack_k_pend_usd); + + // Cross-environment isolation: lock on (longbridge, paper) does NOT lock (longbridge, live) + const liveCrossCheck = checkSymbolOrderAllowed(reloaded, { + broker: "longbridge", + environment: "live", + account: "longbridge:live:sg", + symbol: "TQQQ", + }); + assert.equal(liveCrossCheck.allowed, true); + assert.deepEqual( + lockedSymbolsForAccount(reloaded, { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + }), + ["TQQQ"], + ); +} + +// 4. Caps (256 / 512 / 2048), incomplete coverage, unsupported domains, K_pend non-release +{ + for (const row of matrix.cases.caps_and_completeness_matrix) { + const cov = evaluateDomainCoverage({ + domain: "cutoff_open_orders", + domain_capability: row.domain_capability, + as_of: row.domain_capability === "supported" ? "2026-11-24T15:00:00.000Z" : null, + source: row.name, + scope: "cutoff_open_orders", + cap: row.cap, + count: row.count, + truncated: row.truncated, + completeness: row.completeness, + }); + assert.equal(cov.empty_domain_proven, row.expected.empty_domain_proven, `${row.name}.empty_domain_proven`); + assert.equal(cov.k_pend_release_allowed, row.expected.k_pend_release_allowed, `${row.name}.k_pend_release_allowed`); + if (row.expected.count !== undefined) { + assert.equal(cov.count, row.expected.count, `${row.name}.count`); + } + + const full = evaluateAuthoritativeOrdersAndFills( + { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: `sa2:a12:${row.name}`, + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { + domain_capability: row.domain_capability, + as_of: row.domain_capability === "supported" ? "2026-11-24T15:00:00.000Z" : null, + source: row.name, + scope: "cutoff_open_orders", + cap: row.cap, + count: row.count, + truncated: row.truncated, + completeness: row.completeness, + }, + }, + }, + { priorKPendUsd: row.prior_k_pend_usd }, + ); + assert.ok(validateSchema(full), `${row.name} schema: ${ajv.errorsText(validateSchema.errors)}`); + assert.equal(full.summary.k_pend_usd, row.expected.k_pend_usd, `${row.name}.summary.k_pend_usd`); + assert.equal(full.summary.k_pend_release_allowed, row.expected.k_pend_release_allowed, `${row.name}.summary.k_pend_release_allowed`); + } + + assert.throws(() => + evaluateDomainCoverage({ + domain: "cutoff_open_orders", + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "bad_cap", + scope: "cutoff_open_orders", + cap: 1000, + count: 0, + truncated: false, + completeness: "complete", + }), + ); +} + +// 5. Null fees, non-USD unavailability, and legacy broker_executions.v1 pure adapter +{ + const spec = matrix.cases.null_fee_and_non_usd_cases; + const nullFeeRes = evaluateAuthoritativeOrdersAndFills({ + broker: spec.null_fee_usd_execution.broker, + environment: spec.null_fee_usd_execution.environment, + account: spec.null_fee_usd_execution.account, + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:a12:null-fee-check", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "longbridge_paper_fills", + scope: "account_executions", + cap: 512, + completeness: "complete", + truncated: false, + records: [spec.null_fee_usd_execution], + }, + cutoff_open_orders: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + }, + }); + assert.ok(validateSchema(nullFeeRes)); + assert.equal(nullFeeRes.executions[0].fee_native, null); + assert.equal(nullFeeRes.executions[0].fee_usd, null); + assert.equal(nullFeeRes.executions[0].notional_usd, "250.00"); + + const hkdRes = evaluateAuthoritativeOrdersAndFills({ + broker: spec.non_usd_hkd_execution.broker, + environment: spec.non_usd_hkd_execution.environment, + account: spec.non_usd_hkd_execution.account, + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "authorized_live_broker", + evidence_ref: "sa2:a12:hkd-check", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "longbridge_live_fills", + scope: "account_executions", + cap: 512, + completeness: "complete", + truncated: false, + records: [spec.non_usd_hkd_execution], + }, + cutoff_open_orders: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + }, + }); + assert.ok(validateSchema(hkdRes)); + assert.equal(hkdRes.executions[0].currency, "HKD"); + assert.equal(hkdRes.executions[0].notional_usd, null); + assert.equal(hkdRes.executions[0].fee_usd, null); + assert.equal(hkdRes.summary.fx_inferred, false); + + const legacyWithSelector = { + ...spec.legacy_ibkr_flex_payload, + account_selector: "U" + "100001", + }; + const adapted = adaptLegacyBrokerExecutionPayload(legacyWithSelector, { + broker: "ibkr", + environment: "live", + account: "ibkr:live:a1", + evidence_ref: "sa2:a12:legacy-ibkr-adapter", + }); + const adaptedEval = evaluateAuthoritativeOrdersAndFills(adapted); + assert.ok(validateSchema(adaptedEval), ajv.errorsText(validateSchema.errors)); + assert.equal(adaptedEval.domains.executions.completeness, "incomplete"); + assert.equal(adaptedEval.domains.executions.k_pend_release_allowed, false); + assert.equal(adaptedEval.executions[0].fee_native, "-0.123456789000000001"); + assert.equal(adaptedEval.executions[0].fee_currency, "EUR"); + assert.equal(adaptedEval.executions[0].fee_usd, null); + assert.equal(adaptedEval.summary.k_pend_usd, null); + assert.equal(PRIVATE_LOCATOR_RE.test(JSON.stringify(adaptedEval)), false); + assert.equal(JSON.stringify(adaptedEval).includes("U" + "100001"), false); +} + +// 6. P1 regression guards for C-SA-25 (#1-#7, #9b, #14) +{ + // #1a: First read of unsupported / incomplete / truncated open orders must NEVER release K_pend = "0". + for (const badDomain of [ + { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + { domain_capability: "supported", as_of: "2026-11-24T15:00:00.000Z", source: "lb_open", scope: "cutoff_open_orders", cap: 256, count: 0, truncated: false, completeness: "incomplete", records: [] }, + { domain_capability: "supported", as_of: "2026-11-24T15:00:00.000Z", source: "lb_open", scope: "cutoff_open_orders", cap: 256, count: 256, truncated: true, completeness: "incomplete" }, + ]) { + const res = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:p1:first-read-incomplete", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: badDomain, + }, + }); + assert.ok(validateSchema(res), ajv.errorsText(validateSchema.errors)); + assert.equal(res.summary.k_pend_release_allowed, false); + assert.equal(res.summary.k_pend_usd, null); + } + + // #1b: Non-overlapping new submission alongside unreleased priorKPendUsd is additive, never dropped by max(). + const withPriorAndNewSub = evaluateAuthoritativeOrdersAndFills( + { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:p1:prior-plus-new", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-new-1", + broker_order_id: null, + symbol: "TQQQ", + side: "BUY", + state: "SUBMITTED", + qty_submitted: "8", + limit_price: "50.00", + currency: "USD", + estimated_fee_usd: "1.25", + submitted_at: "2026-11-24T14:58:00.000Z", + evidence_ref: "sa2:p1:new-sub", + }, + ], + }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + }, + }, + { priorKPendUsd: "1000.00" }, + ); + assert.ok(validateSchema(withPriorAndNewSub), ajv.errorsText(validateSchema.errors)); + assert.equal(withPriorAndNewSub.summary.k_pend_usd, "1401.25"); + assert.equal(withPriorAndNewSub.summary.k_pend_release_allowed, false); + + // Overlapping prior order ID deduplicated against priorKPendUsd while adding non-overlapping new order. + const overlapDeduped = evaluateAuthoritativeOrdersAndFills( + { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:p1:prior-overlap", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-old-1", + broker_order_id: "brk-old-1", + symbol: "SOXL", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + limit_price: "40.00", + currency: "USD", + estimated_fee_usd: "0", + submitted_at: "2026-11-24T14:30:00.000Z", + evidence_ref: "sa2:p1:old-sub", + }, + { + client_order_id: "ord-new-2", + broker_order_id: "brk-new-2", + symbol: "TQQQ", + side: "BUY", + state: "SUBMITTED", + qty_submitted: "6", + limit_price: "50.00", + currency: "USD", + estimated_fee_usd: "0", + submitted_at: "2026-11-24T14:59:00.000Z", + evidence_ref: "sa2:p1:new-sub-2", + }, + ], + }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 512, + count: 1, + truncated: false, + completeness: "incomplete", + records: [ + { + client_order_id: "ord-old-1", + broker_order_id: "brk-old-1", + symbol: "SOXL", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "40.00", + currency: "USD", + reserved_fee_usd: "0", + as_of: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:p1:old-open", + }, + ], + }, + }, + }, + { priorKPendUsd: "1000.00", priorKPendOrderIds: ["ord-old-1"] }, + ); + assert.ok(validateSchema(overlapDeduped)); + assert.equal(overlapDeduped.summary.k_pend_usd, "1300.00"); + + // #2: Coverage count=1, records=[], completeness="complete" fails closed as incomplete; + // records.length > cap (257>256, 513>512, 2049>2048) rejects regardless of truncated flag. + const mismatchCov = evaluateDomainCoverage({ + domain: "cutoff_open_orders", + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 512, + count: 1, + truncated: false, + completeness: "complete", + records: [], + }); + assert.equal(mismatchCov.completeness, "incomplete"); + assert.equal(mismatchCov.empty_domain_proven, false); + assert.equal(mismatchCov.k_pend_release_allowed, false); + + for (const capVal of [256, 512, 2048]) { + for (const truncFlag of [false, true]) { + assert.throws( + () => evaluateDomainCoverage({ + domain: "cutoff_open_orders", + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "cap_overflow", + scope: "cutoff_open_orders", + cap: capVal, + count: capVal + 1, + truncated: truncFlag, + completeness: "incomplete", + records: Array.from({ length: capVal + 1 }, (_, idx) => ({ id: idx })), + }), + /domain_records_exceed_cap/, + ); + } + } + + // #3a: Same-batch ORDER_UNKNOWN -> ACCEPTED cannot erase ORDER_UNKNOWN lock. + const sameBatchDowngradeAttempt = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:p1:inbatch-order-unknown", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-race-1", + broker_order_id: null, + symbol: "TQQQ", + side: "BUY", + state: "ORDER_UNKNOWN", + qty_submitted: "5", + limit_price: "50.00", + currency: "USD", + estimated_fee_usd: "1.00", + submitted_at: "2026-11-24T14:55:00.000Z", + evidence_ref: "sa2:p1:race-1", + }, + { + client_order_id: "ord-race-1", + broker_order_id: "brk-race-1", + symbol: "TQQQ", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "5", + limit_price: "50.00", + currency: "USD", + estimated_fee_usd: "1.00", + submitted_at: "2026-11-24T14:56:00.000Z", + evidence_ref: "sa2:p1:race-2", + }, + ], + }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + }, + }); + assert.ok(validateSchema(sameBatchDowngradeAttempt)); + assert.equal(sameBatchDowngradeAttempt.orders[0].state, "ORDER_UNKNOWN"); + assert.deepEqual(sameBatchDowngradeAttempt.order_unknown_symbols, ["TQQQ"]); + assert.equal(sameBatchDowngradeAttempt.summary.k_pend_release_allowed, false); + + // #3b + #4: Reloaded lock key normalized across canonical/short account forms AND cannot unlock via wrong symbol. + let symLockStore = createOrderUnknownLockStore(); + symLockStore = applyOrderUnknownObservation(symLockStore, { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + client_order_id: "ord-lock-sym", + broker_order_id: null, + symbol: "TQQQ", + side: "BUY", + state: "ORDER_UNKNOWN", + qty_submitted: "10", + limit_price: "50.00", + currency: "USD", + estimated_fee_usd: "1.25", + submitted_at: "2026-11-24T14:55:00.000Z", + }); + const symLockReloaded = deserializeOrderUnknownLockStore(JSON.parse(JSON.stringify(serializeOrderUnknownLockStore(symLockStore)))); + assert.equal( + checkSymbolOrderAllowed(symLockReloaded, { + broker: "longbridge", + environment: "paper", + account: "pilot", + symbol: "TQQQ", + }).allowed, + false, + ); + assert.throws( + () => evaluateAuthoritativeOrdersAndFills( + { + broker: "longbridge", + environment: "paper", + account: "pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:p1:wrong-symbol-clear", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-lock-sym", + broker_order_id: null, + symbol: "SOXL", + side: "BUY", + state: "CANCELED", + qty_submitted: "10", + limit_price: "50.00", + currency: "USD", + resolved_at: "2026-11-24T14:59:00.000Z", + evidence_ref: "sa2:p1:wrong-symbol-cancel", + }, + ], + }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + }, + }, + { lockStore: symLockReloaded }, + ), + /order_unknown_symbol_mismatch/, + ); + + // #3c: Future-dated CANCELED / fill (> evaluated_at) must NEVER release K_pend early or clear lock. + const futureCancelRes = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:p1:future-cancel", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-future-cancel", + broker_order_id: null, + symbol: "TQQQ", + side: "BUY", + state: "CANCELED", + qty_submitted: "10", + limit_price: "50.00", + currency: "USD", + estimated_fee_usd: "1.25", + submitted_at: "2026-11-24T14:50:00.000Z", + resolved_at: "2026-11-24T15:05:00.000Z", + evidence_ref: "sa2:p1:future-cancel-sub", + }, + ], + }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 512, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }); + assert.ok(validateSchema(futureCancelRes)); + assert.equal(futureCancelRes.summary.k_pend_usd, "501.25"); + assert.equal(futureCancelRes.summary.k_pend_release_allowed, false); + + const lockAfterFutureCancel = applyOrderUnknownObservation( + symLockReloaded, + { + broker: "longbridge", + environment: "paper", + account: "pilot", + client_order_id: "ord-lock-sym", + symbol: "TQQQ", + state: "CANCELED", + resolved_at: "2026-11-24T15:05:00.000Z", + }, + { evaluatedAt: "2026-11-24T15:00:00.000Z" }, + ); + assert.deepEqual( + lockedSymbolsForAccount(lockAfterFutureCancel, { broker: "longbridge", environment: "paper", account: "pilot" }), + ["TQQQ"], + ); + + // #5: Duplicate broker_order_id collision across distinct client_order_id values fails closed. + assert.throws( + () => evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:p1:broker-id-hijack", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-a", + broker_order_id: "brk-shared", + symbol: "TQQQ", + side: "BUY", + state: "SUBMITTED", + qty_submitted: "5", + limit_price: "50.00", + currency: "USD", + estimated_fee_usd: "1.00", + submitted_at: "2026-11-24T14:50:00.000Z", + evidence_ref: "sa2:p1:hijack-a", + }, + { + client_order_id: "ord-b", + broker_order_id: "brk-shared", + symbol: "SOXL", + side: "BUY", + state: "SUBMITTED", + qty_submitted: "5", + limit_price: "25.00", + currency: "USD", + estimated_fee_usd: "1.00", + submitted_at: "2026-11-24T14:51:00.000Z", + evidence_ref: "sa2:p1:hijack-b", + }, + ], + }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + }, + }), + /conflicting_duplicate_broker_order_id/, + ); + + // #6a + #9b: IBKR Flex multi-report dedup across distinct observed_at timestamps + reject relabeling to longbridge/paper. + const legacyFlexWithSelector = { + ...matrix.cases.null_fee_and_non_usd_cases.legacy_ibkr_flex_payload, + account_selector: "U" + "100001", + }; + const flexReport1 = adaptLegacyBrokerExecutionPayload( + { ...legacyFlexWithSelector, observed_at: "2026-10-23T16:00:00.000Z" }, + { broker: "ibkr", environment: "live", account: "ibkr:live:a1" }, + ); + const flexReport2 = adaptLegacyBrokerExecutionPayload( + { ...legacyFlexWithSelector, observed_at: "2026-10-24T01:00:00.000Z" }, + { broker: "ibkr", environment: "live", account: "ibkr:live:a1" }, + ); + const mergedFlex = deduplicateExecutions( + flexReport2.domains.executions.records, + flexReport1.domains.executions.records, + ); + assert.equal(mergedFlex.length, 1); + const evalFlex1 = evaluateAuthoritativeOrdersAndFills(flexReport1); + const evalFlex2 = evaluateAuthoritativeOrdersAndFills(flexReport2); + assert.equal(deduplicateExecutions(evalFlex2.executions, evalFlex1.executions).length, 1); + + assert.throws( + () => adaptLegacyBrokerExecutionPayload(legacyFlexWithSelector, { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + }), + /legacy_source_broker_mismatch/, + ); + assert.throws( + () => adaptLegacyBrokerExecutionPayload(legacyFlexWithSelector, { + broker: "ibkr", + environment: "paper", + account: "ibkr:paper:a1", + }), + /legacy_source_environment_mismatch/, + ); + + // #6b: Conflicting non-USD notional_usd or usd_basis_qualified must fail closed. + const hkdQ1 = { + broker: "longbridge", + environment: "live", + account: "longbridge:live:hk", + execution_ref: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + report_ref: "1111111111111111111111111111111111111111111111111111111111111111", + client_order_id: null, + broker_order_id: null, + symbol: "2800.HK", + side: "BUY", + qty: "100", + price: "20.00", + currency: "HKD", + notional_usd: "256.00", + fee_native: null, + fee_currency: null, + fee_usd: null, + usd_basis_qualified: true, + executed_at: "2026-11-24T06:30:00.000Z", + evidence_ref: "sa2:p1:hkd-1", + }; + assert.throws( + () => deduplicateExecutions([{ ...hkdQ1, notional_usd: "260.00" }], [hkdQ1]), + /conflicting_duplicate_execution/, + ); + assert.throws( + () => deduplicateExecutions([{ ...hkdQ1, usd_basis_qualified: false, notional_usd: null }], [hkdQ1]), + /conflicting_duplicate_execution/, + ); + + // #7: Non-USD ORDER_UNKNOWN never multiplies native price as USD, and missing estimated_fee_usd is never coerced to 0. + let hkdLockStore = createOrderUnknownLockStore(); + hkdLockStore = applyOrderUnknownObservation(hkdLockStore, { + broker: "longbridge", + environment: "live", + account: "longbridge:live:hk", + client_order_id: "ord-hkd-lock", + broker_order_id: null, + symbol: "2800.HK", + side: "BUY", + state: "ORDER_UNKNOWN", + qty_submitted: "500", + limit_price: "20.10", + currency: "HKD", + usd_basis_qualified: true, + submitted_at: "2026-11-24T06:30:00.000Z", + }); + assert.equal( + listActiveOrderUnknownLocks(hkdLockStore, { broker: "longbridge", environment: "live", account: "hk" })[0].k_pend_usd, + null, + ); + + const missingEstFee = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:p1:missing-fee-kpend", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-nofee-open", + broker_order_id: "brk-nofee-open", + symbol: "TQQQ", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "50.00", + currency: "USD", + as_of: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:p1:nofee-open", + }, + ], + }, + }, + }); + assert.ok(validateSchema(missingEstFee)); + assert.equal(missingEstFee.orders[0].k_pend_usd, null); + assert.equal(missingEstFee.summary.k_pend_usd, null); + + // #14: Schema rejects raw account IDs encoded as currency; coverage rejects raw currency in native_currency / records. + const badCurPayload = structuredClone(missingEstFee); + badCurPayload.orders[0].currency = "U" + "1234567"; + assert.equal(validateSchema(badCurPayload), false); + assert.throws( + () => evaluateDomainCoverage({ + domain: "executions", + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_fills", + scope: "account_executions", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + native_currency: "DU" + "987654", + records: [], + }), + ); +} + +// 7. Codex review regressions (#1 future empty cutoff domain, #2 post-cutoff executions, #4 count>0 omitted records) +{ + // Codex #1 (PRRT_kwDOSZeN-M67n_nW): empty complete cutoff snapshot with as_of > evaluated_at cannot release K_pend. + const futureEmptyCutoffInput = { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex:future-empty-cutoff", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T16:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }; + const futureWithPrior = evaluateAuthoritativeOrdersAndFills(futureEmptyCutoffInput, { priorKPendUsd: "1000.00" }); + assert.ok(validateSchema(futureWithPrior), ajv.errorsText(validateSchema.errors)); + assert.equal(futureWithPrior.summary.k_pend_release_allowed, false); + assert.equal(futureWithPrior.summary.k_pend_usd, "1000.00"); + assert.equal(futureWithPrior.domains.cutoff_open_orders.empty_domain_proven, false); + assert.equal(futureWithPrior.domains.cutoff_open_orders.k_pend_release_allowed, false); + + const futureNoPrior = evaluateAuthoritativeOrdersAndFills(futureEmptyCutoffInput); + assert.ok(validateSchema(futureNoPrior)); + assert.equal(futureNoPrior.summary.k_pend_release_allowed, false); + assert.equal(futureNoPrior.summary.k_pend_usd, null); + + const directFutureCutoff = reconcileOrdersAndFills({ + identity: { broker: "longbridge", environment: "paper", account: "longbridge:paper:pilot", binding_key: "longbridge|paper|longbridge:paper:pilot" }, + cutoffCoverage: { as_of: "2026-11-24T16:00:00.000Z", k_pend_release_allowed: true }, + priorKPendUsd: "1000.00", + evaluatedAt: "2026-11-24T15:02:00.000Z", + }); + assert.equal(directFutureCutoff.k_pend_release_allowed, false); + assert.equal(directFutureCutoff.k_pend_usd, "1000.00"); + + // Codex #2 (PRRT_kwDOSZeN-M67n_ne): executions after cutoff.as_of and <= evaluated_at advance remaining qty cleanly. + const asyncCutoffWithFill = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex:async-cutoff-exec", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_orders", + scope: "account_submissions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-async-1", + broker_order_id: "brk-async-1", + symbol: "TQQQ", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + limit_price: "50.00", + currency: "USD", + estimated_fee_usd: "1.25", + submitted_at: "2026-11-24T14:59:00.000Z", + evidence_ref: "sa2:codex:async-sub", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_fills", + scope: "account_executions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + execution_ref: "abababababababababababababababababababababababababababababababab", + report_ref: "1111111111111111111111111111111111111111111111111111111111111111", + client_order_id: "ord-async-1", + broker_order_id: "brk-async-1", + symbol: "TQQQ", + side: "BUY", + qty: "2", + price: "49.50", + currency: "USD", + fee_native: "0.25", + fee_currency: "USD", + executed_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex:async-exec-1", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-async-1", + broker_order_id: "brk-async-1", + symbol: "TQQQ", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "50.00", + currency: "USD", + reserved_fee_usd: "1.25", + as_of: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:codex:async-open", + }, + ], + }, + }, + }); + assert.ok(validateSchema(asyncCutoffWithFill), ajv.errorsText(validateSchema.errors)); + assert.equal(asyncCutoffWithFill.orders[0].qty_filled, "2"); + assert.equal(asyncCutoffWithFill.orders[0].qty_remaining, "8"); + assert.equal(asyncCutoffWithFill.orders[0].state, "PARTIAL_FILL"); + assert.equal(asyncCutoffWithFill.orders[0].k_pend_usd, "401.25"); + assert.equal(asyncCutoffWithFill.summary.k_pend_usd, "401.25"); + + // Full fill after cutoff completes cleanly with zero remaining K_pend. + const asyncFullFill = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex:async-full-fill", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_fills", + scope: "account_executions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + execution_ref: "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", + report_ref: "2222222222222222222222222222222222222222222222222222222222222222", + client_order_id: "ord-async-2", + broker_order_id: "brk-async-2", + symbol: "TQQQ", + side: "BUY", + qty: "10", + price: "50.00", + currency: "USD", + fee_native: "1.25", + fee_currency: "USD", + executed_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex:async-full-exec", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-async-2", + broker_order_id: "brk-async-2", + symbol: "TQQQ", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "50.00", + currency: "USD", + reserved_fee_usd: "1.25", + as_of: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:codex:async-open-2", + }, + ], + }, + }, + }); + assert.ok(validateSchema(asyncFullFill)); + assert.equal(asyncFullFill.orders[0].state, "FILLED"); + assert.equal(asyncFullFill.orders[0].qty_remaining, "0"); + assert.equal(asyncFullFill.summary.k_pend_usd, "0"); + + // Genuine pre-cutoff execution mismatch AT cutoff.as_of still rejects 409; post-cutoff overfill still rejects 400. + assert.throws( + () => evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex:precutoff-mismatch", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_fills", + scope: "account_executions", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + execution_ref: "efefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefef", + report_ref: "3333333333333333333333333333333333333333333333333333333333333333", + client_order_id: "ord-pre-mismatch", + broker_order_id: "brk-pre-mismatch", + symbol: "TQQQ", + side: "BUY", + qty: "2", + price: "50.00", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: "2026-11-24T14:59:00.000Z", + evidence_ref: "sa2:codex:pre-exec", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 512, + completeness: "complete", + truncated: false, + records: [ + { + client_order_id: "ord-pre-mismatch", + broker_order_id: "brk-pre-mismatch", + symbol: "TQQQ", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "50.00", + currency: "USD", + reserved_fee_usd: "1.25", + as_of: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:codex:pre-open", + }, + ], + }, + }, + }), + /order_remaining_cutoff_mismatch/, + ); + + // Codex #4 (PRRT_kwDOSZeN-M67n_nv): positive count without records array cannot stay complete or release K_pend. + const positiveCountNoRecordsCov = evaluateDomainCoverage({ + domain: "cutoff_open_orders", + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + }); + assert.equal(positiveCountNoRecordsCov.completeness, "incomplete"); + assert.equal(positiveCountNoRecordsCov.empty_domain_proven, false); + assert.equal(positiveCountNoRecordsCov.k_pend_release_allowed, false); + + const positiveCountOmittedInput = { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex:count1-no-records", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + }, + }, + }; + const omittedWithPrior = evaluateAuthoritativeOrdersAndFills(positiveCountOmittedInput, { priorKPendUsd: "1000.00" }); + assert.ok(validateSchema(omittedWithPrior), ajv.errorsText(validateSchema.errors)); + assert.equal(omittedWithPrior.domains.cutoff_open_orders.completeness, "incomplete"); + assert.equal(omittedWithPrior.summary.k_pend_release_allowed, false); + assert.equal(omittedWithPrior.summary.k_pend_usd, "1000.00"); + + const omittedNoPrior = evaluateAuthoritativeOrdersAndFills(positiveCountOmittedInput); + assert.ok(validateSchema(omittedNoPrior)); + assert.equal(omittedNoPrior.summary.k_pend_release_allowed, false); + assert.equal(omittedNoPrior.summary.k_pend_usd, null); +} + +// 8. Codex round-2 P2 regression guards (two-pass exec link, updated_at cancel, legacy TZ, mixed fee_usd) +{ + // P2 #1: Two-pass execution linking when submission & cutoff lack broker_order_id and earlier exec omits client_order_id. + const twoPassInput = { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r2:p2-1-twopass", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-twopass-1", + broker_order_id: null, + symbol: "AAPL", + side: "BUY", + state: "SUBMITTED", + qty_submitted: "10", + limit_price: "50", + estimated_fee_usd: "0", + currency: "USD", + fee_native: null, + fee_currency: null, + fee_usd: null, + submitted_at: "2026-11-24T14:55:00.000Z", + evidence_ref: "sa2:codex-r2:sub1", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_execs", + scope: "account_executions", + cap: 512, + count: 2, + truncated: false, + completeness: "complete", + records: [ + { + execution_ref: "exec-twopass-early", + client_order_id: null, + broker_order_id: "brk-twopass-1", + symbol: "AAPL", + side: "BUY", + qty: "2", + price: "50", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: "2026-11-24T14:58:00.000Z", + evidence_ref: "sa2:codex-r2:ex-early", + }, + { + execution_ref: "exec-twopass-late", + client_order_id: "ord-twopass-1", + broker_order_id: "brk-twopass-1", + symbol: "AAPL", + side: "BUY", + qty: "2", + price: "50", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:codex-r2:ex-late", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T14:56:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-twopass-1", + broker_order_id: null, + symbol: "AAPL", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "50", + reserved_fee_usd: "0", + currency: "USD", + as_of: "2026-11-24T14:56:00.000Z", + evidence_ref: "sa2:codex-r2:open1", + }, + ], + }, + }, + }; + const twoPassRes = evaluateAuthoritativeOrdersAndFills(twoPassInput); + assert.ok(validateSchema(twoPassRes), ajv.errorsText(validateSchema.errors)); + assert.equal(twoPassRes.orders.length, 1); + assert.equal(twoPassRes.orders[0].broker_order_id, "brk-twopass-1"); + assert.equal(twoPassRes.orders[0].qty_filled, "4"); + assert.equal(twoPassRes.orders[0].qty_remaining, "6"); + assert.equal(twoPassRes.orders[0].state, "PARTIAL_FILL"); + assert.equal(twoPassRes.orders[0].k_pend_usd, "300.00"); + assert.equal(twoPassRes.summary.k_pend_usd, "300.00"); + assert.equal(twoPassRes.summary.k_pend_release_allowed, true); + + // P2 #2: Post-cutoff terminal/cancel update identified via updated_at advances cutoff snapshot & releases K_pend. + const updatedAtCancelRes = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r2:p2-2-updated-at", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-upd-cancel", + broker_order_id: "brk-upd-cancel", + symbol: "AAPL", + side: "BUY", + state: "CANCELED", + qty_submitted: "10", + limit_price: "50", + estimated_fee_usd: "0", + currency: "USD", + fee_native: null, + fee_currency: null, + fee_usd: null, + submitted_at: "2026-11-24T14:55:00.000Z", + updated_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r2:sub-upd-cancel", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_execs", + scope: "account_executions", + cap: 512, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-upd-cancel", + broker_order_id: "brk-upd-cancel", + symbol: "AAPL", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "50", + reserved_fee_usd: "0", + currency: "USD", + as_of: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:codex-r2:open-upd-cancel", + }, + ], + }, + }, + }, { priorKPendUsd: "500.00" }); + assert.ok(validateSchema(updatedAtCancelRes), ajv.errorsText(validateSchema.errors)); + assert.equal(updatedAtCancelRes.orders[0].state, "CANCELED"); + assert.equal(updatedAtCancelRes.orders[0].qty_canceled, "10"); + assert.equal(updatedAtCancelRes.orders[0].qty_remaining, "0"); + assert.equal(updatedAtCancelRes.orders[0].k_pend_usd, "0"); + assert.equal(updatedAtCancelRes.orders[0].updated_at, "2026-11-24T15:01:00.000Z"); + assert.equal(updatedAtCancelRes.summary.k_pend_usd, "0"); + assert.equal(updatedAtCancelRes.summary.k_pend_release_allowed, true); + + // Also cover PARTIAL_CANCEL reported via updated_at after cutoff with post-cutoff fill. + const updatedAtPartialCancelRes = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r2:p2-2-partial-cancel", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-upd-pc", + broker_order_id: "brk-upd-pc", + symbol: "AAPL", + side: "BUY", + state: "PARTIAL_CANCEL", + qty_submitted: "10", + limit_price: "50", + estimated_fee_usd: "0", + currency: "USD", + fee_native: null, + fee_currency: null, + fee_usd: null, + submitted_at: "2026-11-24T14:55:00.000Z", + updated_at: "2026-11-24T15:01:30.000Z", + evidence_ref: "sa2:codex-r2:sub-upd-pc", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_execs", + scope: "account_executions", + cap: 512, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + execution_ref: "exec-upd-pc-1", + client_order_id: "ord-upd-pc", + broker_order_id: "brk-upd-pc", + symbol: "AAPL", + side: "BUY", + qty: "4", + price: "50", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r2:ex-upd-pc", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-upd-pc", + broker_order_id: "brk-upd-pc", + symbol: "AAPL", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "50", + reserved_fee_usd: "0", + currency: "USD", + as_of: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:codex-r2:open-upd-pc", + }, + ], + }, + }, + }); + assert.ok(validateSchema(updatedAtPartialCancelRes), ajv.errorsText(validateSchema.errors)); + assert.equal(updatedAtPartialCancelRes.orders[0].state, "PARTIAL_CANCEL"); + assert.equal(updatedAtPartialCancelRes.orders[0].qty_filled, "4"); + assert.equal(updatedAtPartialCancelRes.orders[0].qty_canceled, "6"); + assert.equal(updatedAtPartialCancelRes.orders[0].qty_remaining, "0"); + assert.equal(updatedAtPartialCancelRes.orders[0].k_pend_usd, "0"); + assert.equal(updatedAtPartialCancelRes.summary.k_pend_usd, "0"); + + // P2 #3: Legacy execution adapter converts local_time + time_zone deterministically & never fabricates T00:00:00Z. + const baseLegacy = { + ...matrix.cases.null_fee_and_non_usd_cases.legacy_ibkr_flex_payload, + account_selector: "U" + "100001", + observed_at: "2026-11-24T15:00:00.000Z", + }; + const legacyUtcFuture = adaptLegacyBrokerExecutionPayload({ + ...baseLegacy, + records: [ + { + ...baseLegacy.records[0], + trade_date: "2026-11-24", + local_time: "2026-11-24T20:00:00", + time_zone: "UTC", + }, + ], + }, { broker: "ibkr", environment: "live", account: "ibkr:live:a1" }); + assert.equal(legacyUtcFuture.domains.executions.records[0].executed_at, "2026-11-24T20:00:00.000Z"); + const evalUtcFuture = evaluateAuthoritativeOrdersAndFills(legacyUtcFuture); + assert.ok(validateSchema(evalUtcFuture), ajv.errorsText(validateSchema.errors)); + assert.equal(evalUtcFuture.executions[0].executed_at, "2026-11-24T20:00:00.000Z"); + assert.equal(evalUtcFuture.summary.k_pend_release_allowed, false); + + // Verify the converted 20:00Z execution sits on the future side of a 15:00Z evaluation boundary + // even when paired with a complete empty cutoff snapshot, whereas 21:00Z allows release. + const completeEmptyBoundaryInput = (evaluatedAt) => ({ + broker: "ibkr", + environment: "live", + account: "ibkr:live:a1", + as_of: evaluatedAt, + evaluated_at: evaluatedAt, + origin: "synthetic", + source_class: "authorized_live_broker", + evidence_ref: "sa2:codex-r2:legacy-boundary", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { + ...legacyUtcFuture.domains.executions, + as_of: evaluatedAt, + completeness: "complete", + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: evaluatedAt, + source: "ibkr_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }); + const boundaryAt1500 = evaluateAuthoritativeOrdersAndFills( + completeEmptyBoundaryInput("2026-11-24T15:00:00.000Z"), + { priorKPendUsd: "100.00" }, + ); + assert.ok(validateSchema(boundaryAt1500)); + assert.equal(boundaryAt1500.summary.k_pend_release_allowed, false); + assert.equal(boundaryAt1500.summary.k_pend_usd, "100.00"); + + const boundaryAt2100 = evaluateAuthoritativeOrdersAndFills( + completeEmptyBoundaryInput("2026-11-24T21:00:00.000Z"), + { priorKPendUsd: "100.00" }, + ); + assert.ok(validateSchema(boundaryAt2100)); + assert.equal(boundaryAt2100.summary.k_pend_release_allowed, true); + assert.equal(boundaryAt2100.summary.k_pend_usd, "0"); + + const legacyNyDst = adaptLegacyBrokerExecutionPayload({ + ...baseLegacy, + observed_at: "2026-11-24T21:00:00.000Z", + records: [ + { + ...baseLegacy.records[0], + execution_ref: "a".repeat(64), + trade_date: "2026-11-24", + local_time: "2026-11-24T09:30:00", + time_zone: "America/New_York", + }, + { + ...baseLegacy.records[0], + execution_ref: "b".repeat(64), + trade_date: "2026-07-15", + local_time: "2026-07-15T09:30:00", + time_zone: "America/New_York", + }, + ], + }, { broker: "ibkr", environment: "live", account: "ibkr:live:a1" }); + assert.equal(legacyNyDst.domains.executions.records[0].executed_at, "2026-11-24T14:30:00.000Z"); + assert.equal(legacyNyDst.domains.executions.records[1].executed_at, "2026-07-15T13:30:00.000Z"); + + // Unknown time_zone leaves executed_at: null (never midnight UTC), supports enrichment, and blocks K_pend release. + const legacyUnknownZone = adaptLegacyBrokerExecutionPayload({ + ...baseLegacy, + observed_at: "2026-10-23T16:00:00.000Z", + records: [ + { + ...baseLegacy.records[0], + trade_date: "2026-10-23", + local_time: "2026-10-23T09:31:00", + time_zone: null, + }, + ], + }, { broker: "ibkr", environment: "live", account: "ibkr:live:a1" }); + assert.equal(legacyUnknownZone.domains.executions.records[0].executed_at, null); + const evalUnknownZone = evaluateAuthoritativeOrdersAndFills(legacyUnknownZone); + assert.ok(validateSchema(evalUnknownZone), ajv.errorsText(validateSchema.errors)); + assert.equal(evalUnknownZone.executions[0].executed_at, null); + + const enrichedUnknownToKnown = deduplicateExecutions( + [{ ...legacyUnknownZone.domains.executions.records[0], executed_at: "2026-10-23T13:31:00.000Z" }], + legacyUnknownZone.domains.executions.records, + ); + assert.equal(enrichedUnknownToKnown.length, 1); + assert.equal(enrichedUnknownToKnown[0].executed_at, "2026-10-23T13:31:00.000Z"); + + const nullExecWithCompleteCutoff = evaluateAuthoritativeOrdersAndFills({ + broker: "ibkr", + environment: "live", + account: "ibkr:live:a1", + as_of: "2026-11-24T15:00:00.000Z", + evaluated_at: "2026-11-24T15:00:05.000Z", + origin: "synthetic", + source_class: "authorized_live_broker", + evidence_ref: "sa2:codex-r2:null-exec-ts", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "ibkr_flex", + scope: "account_executions", + cap: 512, + count: 1, + truncated: false, + completeness: "complete", + records: [legacyUnknownZone.domains.executions.records[0]], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "ibkr_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }, { priorKPendUsd: "100.00" }); + assert.ok(validateSchema(nullExecWithCompleteCutoff)); + assert.equal(nullExecWithCompleteCutoff.summary.k_pend_release_allowed, false); + assert.equal(nullExecWithCompleteCutoff.summary.k_pend_usd, "100.00"); + + // Reject spring-forward DST gap, mismatched trade_date prefix, or invalid timezone. + for (const [badRow, expectedErr] of [ + [{ trade_date: "2026-03-08", local_time: "2026-03-08T02:30:00", time_zone: "America/New_York" }, /invalid_legacy_execution_local_time/], + [{ trade_date: "2026-11-24", local_time: "2026-11-25T09:30:00", time_zone: "UTC" }, /invalid_legacy_execution_local_time/], + [{ trade_date: "2026-11-24", local_time: "2026-11-24T09:30:00", time_zone: "Mars/Olympus_Mons" }, /invalid_legacy_execution_time_zone/], + ]) { + assert.throws( + () => adaptLegacyBrokerExecutionPayload({ + ...baseLegacy, + records: [{ ...baseLegacy.records[0], ...badRow }], + }, { broker: "ibkr", environment: "live", account: "ibkr:live:a1" }), + expectedErr, + ); + } + + // P2 #4: Mixed fee currencies still sum fee_usd when every fill carries fee_usd, keeping fee_native/fee_currency null. + const mixedFeeUsdRes = evaluateAuthoritativeOrdersAndFills({ + broker: "ibkr", + environment: "paper", + account: "ibkr:paper:a1", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r2:p2-4-mixed-fee-usd", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "ibkr_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-mixed-fee", + broker_order_id: "brk-mixed-fee", + symbol: "AAPL", + side: "BUY", + state: "FILLED", + qty_submitted: "10", + limit_price: "50", + currency: "USD", + fee_native: null, + fee_currency: null, + fee_usd: null, + submitted_at: "2026-11-24T15:00:00.000Z", + resolved_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r2:sub-mixed-fee", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "ibkr_execs", + scope: "account_executions", + cap: 512, + count: 2, + truncated: false, + completeness: "complete", + records: [ + { + execution_ref: "exec-mixed-fee-usd", + client_order_id: "ord-mixed-fee", + broker_order_id: "brk-mixed-fee", + symbol: "AAPL", + side: "BUY", + qty: "5", + price: "50", + currency: "USD", + fee_native: "1.00", + fee_currency: "USD", + executed_at: "2026-11-24T15:00:30.000Z", + evidence_ref: "sa2:codex-r2:ex-fee-1", + }, + { + execution_ref: "exec-mixed-fee-hkd", + client_order_id: "ord-mixed-fee", + broker_order_id: "brk-mixed-fee", + symbol: "AAPL", + side: "BUY", + qty: "5", + price: "50", + currency: "USD", + fee_native: "7.80", + fee_currency: "HKD", + fee_usd: "1.00", + usd_basis_qualified: true, + executed_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r2:ex-fee-2", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "ibkr_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }); + assert.ok(validateSchema(mixedFeeUsdRes), ajv.errorsText(validateSchema.errors)); + assert.equal(mixedFeeUsdRes.orders[0].fee_native, null); + assert.equal(mixedFeeUsdRes.orders[0].fee_currency, null); + assert.equal(mixedFeeUsdRes.orders[0].fee_usd, "2.00"); + + // Unqualified non-USD fee on one fill still leaves aggregated fee_usd null. + const mixedFeeUnqualified = evaluateAuthoritativeOrdersAndFills({ + broker: "ibkr", + environment: "paper", + account: "ibkr:paper:a1", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r2:p2-4-unqualified", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "ibkr_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-mixed-unq", + broker_order_id: "brk-mixed-unq", + symbol: "AAPL", + side: "BUY", + state: "FILLED", + qty_submitted: "10", + limit_price: "50", + currency: "USD", + fee_native: null, + fee_currency: null, + fee_usd: null, + submitted_at: "2026-11-24T15:00:00.000Z", + resolved_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r2:sub-mixed-unq", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "ibkr_execs", + scope: "account_executions", + cap: 512, + count: 2, + truncated: false, + completeness: "complete", + records: [ + { + execution_ref: "exec-mixed-unq-1", + client_order_id: "ord-mixed-unq", + broker_order_id: "brk-mixed-unq", + symbol: "AAPL", + side: "BUY", + qty: "5", + price: "50", + currency: "USD", + fee_native: "1.00", + fee_currency: "USD", + executed_at: "2026-11-24T15:00:30.000Z", + evidence_ref: "sa2:codex-r2:ex-unq-1", + }, + { + execution_ref: "exec-mixed-unq-2", + client_order_id: "ord-mixed-unq", + broker_order_id: "brk-mixed-unq", + symbol: "AAPL", + side: "BUY", + qty: "5", + price: "50", + currency: "USD", + fee_native: "7.80", + fee_currency: "HKD", + fee_usd: null, + usd_basis_qualified: false, + executed_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r2:ex-unq-2", + }, + ], + }, + cutoff_open_orders: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "cutoff_open_orders" }, + }, + }); + assert.ok(validateSchema(mixedFeeUnqualified), ajv.errorsText(validateSchema.errors)); + assert.equal(mixedFeeUnqualified.orders[0].fee_native, null); + assert.equal(mixedFeeUnqualified.orders[0].fee_currency, null); + assert.equal(mixedFeeUnqualified.orders[0].fee_usd, null); +} + +// 9. Codex round-3 regression guards (untimed execution reservation & lagging FILLED reconciliation) +{ + // R3 #1 (PRRT_kwDOSZeN-M67o1UQ): Untimed execution (executed_at: null) without cutoff must NEVER mark FILLED or zero K_pend. + const untimedBuyInput = ({ includeFeeReserve }) => ({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: `sa2:codex-r3:untimed-buy:${includeFeeReserve ? "reserved" : "null"}`, + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-untimed-1", + broker_order_id: "brk-untimed-1", + symbol: "AAPL", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + limit_price: "50", + ...(includeFeeReserve ? { estimated_fee_usd: "0" } : {}), + currency: "USD", + fee_native: null, + fee_currency: null, + fee_usd: null, + submitted_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r3:sub-untimed", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_execs", + scope: "account_executions", + cap: 512, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + execution_ref: "exec-untimed-1", + client_order_id: "ord-untimed-1", + broker_order_id: "brk-untimed-1", + symbol: "AAPL", + side: "BUY", + qty: "10", + price: "50", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: null, + evidence_ref: "sa2:codex-r3:ex-untimed", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }); + + const untimedReserved = evaluateAuthoritativeOrdersAndFills(untimedBuyInput({ includeFeeReserve: true })); + assert.ok(validateSchema(untimedReserved), ajv.errorsText(validateSchema.errors)); + assert.equal(untimedReserved.orders[0].state, "ACCEPTED"); + assert.equal(untimedReserved.orders[0].qty_filled, "0"); + assert.equal(untimedReserved.orders[0].qty_remaining, "10"); + assert.equal(untimedReserved.orders[0].k_pend_usd, "500.00"); + assert.equal(untimedReserved.summary.k_pend_usd, "500.00"); + assert.equal(untimedReserved.summary.k_pend_release_allowed, false); + + const untimedNoFee = evaluateAuthoritativeOrdersAndFills(untimedBuyInput({ includeFeeReserve: false })); + assert.ok(validateSchema(untimedNoFee), ajv.errorsText(validateSchema.errors)); + assert.equal(untimedNoFee.orders[0].state, "ACCEPTED"); + assert.equal(untimedNoFee.orders[0].qty_filled, "0"); + assert.equal(untimedNoFee.orders[0].qty_remaining, "10"); + assert.equal(untimedNoFee.orders[0].k_pend_usd, null); + assert.equal(untimedNoFee.summary.k_pend_usd, null); + assert.equal(untimedNoFee.summary.k_pend_release_allowed, false); + + // Unlinked untimed execution + empty complete cutoff without prior K_pend must still fail closed (never "0"). + const untimedUnlinked = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r3:untimed-unlinked", + domains: { + submissions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_submissions" }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_execs", + scope: "account_executions", + cap: 512, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + execution_ref: "exec-untimed-unlinked", + client_order_id: null, + broker_order_id: null, + symbol: "AAPL", + side: "BUY", + qty: "10", + price: "50", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: null, + evidence_ref: "sa2:codex-r3:ex-unlinked", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }); + assert.ok(validateSchema(untimedUnlinked), ajv.errorsText(validateSchema.errors)); + assert.equal(untimedUnlinked.summary.k_pend_release_allowed, false); + assert.equal(untimedUnlinked.summary.k_pend_usd, null); + + // R3 #3 (PRRT_kwDOSZeN-M67o1Ua): Definitive FILLED submission with unsupported/lagging executions reconciles qty_filled & leaves avg_fill_price null. + const filledUnsupportedExecs = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r3:filled-unsupported-execs", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-filled-no-exec", + broker_order_id: "brk-filled-no-exec", + symbol: "AAPL", + side: "BUY", + state: "FILLED", + qty_submitted: "10", + limit_price: "50", + currency: "USD", + fee_native: null, + fee_currency: null, + fee_usd: null, + submitted_at: "2026-11-24T14:55:00.000Z", + resolved_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r3:sub-filled-no-exec", + }, + ], + }, + executions: { domain_capability: "unsupported", as_of: null, source: "omitted", scope: "account_executions" }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }); + assert.ok(validateSchema(filledUnsupportedExecs), ajv.errorsText(validateSchema.errors)); + assert.equal(filledUnsupportedExecs.orders[0].state, "FILLED"); + assert.equal(filledUnsupportedExecs.orders[0].qty_submitted, "10"); + assert.equal(filledUnsupportedExecs.orders[0].qty_filled, "10"); + assert.equal(filledUnsupportedExecs.orders[0].qty_canceled, "0"); + assert.equal(filledUnsupportedExecs.orders[0].qty_remaining, "0"); + assert.equal(filledUnsupportedExecs.orders[0].avg_fill_price, null); + assert.equal(filledUnsupportedExecs.orders[0].notional_usd, null); + assert.equal(filledUnsupportedExecs.orders[0].k_pend_usd, "0"); + assert.equal(filledUnsupportedExecs.summary.k_pend_usd, "0"); + assert.equal(filledUnsupportedExecs.summary.k_pend_release_allowed, true); + + // Post-cutoff FILLED via updated_at with only partial (4 of 10) lagging executions: qty_filled="10", avg_fill_price=null. + const filledPartialLagExecs = evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r3:filled-partial-lag", + domains: { + submissions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_subs", + scope: "account_submissions", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-filled-lag", + broker_order_id: "brk-filled-lag", + symbol: "AAPL", + side: "BUY", + state: "FILLED", + qty_submitted: "10", + limit_price: "50", + currency: "USD", + fee_native: null, + fee_currency: null, + fee_usd: null, + submitted_at: "2026-11-24T14:55:00.000Z", + updated_at: "2026-11-24T15:01:30.000Z", + evidence_ref: "sa2:codex-r3:sub-filled-lag", + }, + ], + }, + executions: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_execs", + scope: "account_executions", + cap: 512, + count: 1, + truncated: false, + completeness: "incomplete", + records: [ + { + execution_ref: "exec-lag-partial", + client_order_id: "ord-filled-lag", + broker_order_id: "brk-filled-lag", + symbol: "AAPL", + side: "BUY", + qty: "4", + price: "49.50", + currency: "USD", + fee_native: "0", + fee_currency: "USD", + executed_at: "2026-11-24T15:01:00.000Z", + evidence_ref: "sa2:codex-r3:ex-lag", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:00:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 1, + truncated: false, + completeness: "complete", + records: [ + { + client_order_id: "ord-filled-lag", + broker_order_id: "brk-filled-lag", + symbol: "AAPL", + side: "BUY", + state: "ACCEPTED", + qty_submitted: "10", + qty_filled: "0", + qty_canceled: "0", + qty_remaining: "10", + limit_price: "50", + reserved_fee_usd: "0", + currency: "USD", + as_of: "2026-11-24T15:00:00.000Z", + evidence_ref: "sa2:codex-r3:open-lag", + }, + ], + }, + }, + }); + assert.ok(validateSchema(filledPartialLagExecs), ajv.errorsText(validateSchema.errors)); + assert.equal(filledPartialLagExecs.orders[0].state, "FILLED"); + assert.equal(filledPartialLagExecs.orders[0].qty_filled, "10"); + assert.equal(filledPartialLagExecs.orders[0].qty_remaining, "0"); + assert.equal(filledPartialLagExecs.orders[0].avg_fill_price, null); + assert.equal(filledPartialLagExecs.orders[0].k_pend_usd, "0"); + assert.equal(filledPartialLagExecs.summary.k_pend_usd, "0"); + assert.equal(filledPartialLagExecs.summary.k_pend_release_allowed, true); + + // Over-fill execution (> qty_submitted) on FILLED submission still fails closed. + assert.throws( + () => evaluateAuthoritativeOrdersAndFills({ + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + as_of: "2026-11-24T15:02:00.000Z", + evaluated_at: "2026-11-24T15:02:00.000Z", + origin: "synthetic", + source_class: "paper_broker", + evidence_ref: "sa2:codex-r3:overfill-fail", + domains: { + submissions: filledPartialLagExecs.domains.submissions, + executions: { + ...filledPartialLagExecs.domains.executions, + completeness: "complete", + records: [ + { + ...filledPartialLagExecs.domains.executions.records[0], + execution_ref: "exec-overfill-1", + client_order_id: "ord-filled-lag", + qty: "11", + }, + ], + }, + cutoff_open_orders: { + domain_capability: "supported", + as_of: "2026-11-24T15:02:00.000Z", + source: "lb_open", + scope: "cutoff_open_orders", + cap: 256, + count: 0, + truncated: false, + completeness: "complete", + records: [], + }, + }, + }), + /order_quantities_exceed_submitted/, + ); +} + +// 10. Codex round-4 regression guard (PRRT_kwDOSZeN-M67pKB0: untimed terminal observation must NOT clear ORDER_UNKNOWN lock) +{ + let untimedLockStore = createOrderUnknownLockStore(); + untimedLockStore = applyOrderUnknownObservation(untimedLockStore, { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + client_order_id: "ord-lock-untimed", + broker_order_id: null, + symbol: "AAPL", + side: "BUY", + state: "ORDER_UNKNOWN", + qty_submitted: "10", + limit_price: "50.00", + estimated_fee_usd: "0", + currency: "USD", + submitted_at: "2026-11-24T14:55:00.000Z", + evidence_ref: "sa2:codex-r4:lock-create", + }); + + const untimedTerminalEvent = { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + client_order_id: "ord-lock-untimed", + symbol: "AAPL", + state: "CANCELED", + }; + const retainedWithEval = applyOrderUnknownObservation( + untimedLockStore, + untimedTerminalEvent, + { evaluatedAt: "2026-11-24T15:00:00.000Z" }, + ); + assert.deepEqual( + lockedSymbolsForAccount(retainedWithEval, { broker: "longbridge", environment: "paper", account: "longbridge:paper:pilot" }), + ["AAPL"], + ); + const retainedCheck = checkSymbolOrderAllowed(retainedWithEval, { + broker: "longbridge", + environment: "paper", + account: "longbridge:paper:pilot", + symbol: "AAPL", + }); + assert.equal(retainedCheck.allowed, false); + assert.equal(retainedCheck.lock.k_pend_usd, "500.00"); + + const retainedWithoutEval = applyOrderUnknownObservation(untimedLockStore, untimedTerminalEvent); + assert.deepEqual( + lockedSymbolsForAccount(retainedWithoutEval, { broker: "longbridge", environment: "paper", account: "longbridge:paper:pilot" }), + ["AAPL"], + ); + + // Positive control: timestamped terminal evidence <= evaluatedAt clears the lock cleanly. + const clearedTimestamped = applyOrderUnknownObservation( + retainedWithEval, + { ...untimedTerminalEvent, resolved_at: "2026-11-24T14:59:00.000Z" }, + { evaluatedAt: "2026-11-24T15:00:00.000Z" }, + ); + assert.deepEqual( + lockedSymbolsForAccount(clearedTimestamped, { broker: "longbridge", environment: "paper", account: "longbridge:paper:pilot" }), + [], + ); +} + +console.log("sa2_orders_fills_validation: PASS (SA-A12)"); diff --git a/web/strategy-switch-console/application/console_api/executions.js b/web/strategy-switch-console/application/console_api/executions.js index 8c581616..1e47375c 100644 --- a/web/strategy-switch-console/application/console_api/executions.js +++ b/web/strategy-switch-console/application/console_api/executions.js @@ -1,5 +1,9 @@ import { rangeStart } from "../../performance_math.js"; import { mergeExecutionRecord } from "../account_facts/executions.js"; +import { + adaptLegacyBrokerExecutionPayload, + evaluateAuthoritativeOrdersAndFills, +} from "../orders_fills/helpers.js"; const REQUIRED_FIELDS = ["execution_ref", "trade_date", "symbol", "asset_category", "side", "quantity", "price", "currency"]; const OPTIONAL_FIELDS = ["local_time", "time_zone", "commission", "commission_currency", "taxes"]; @@ -222,3 +226,18 @@ export async function executionStatsResponse(options, { scope, range, today, gro }), win_rate_percent: null, realized_pnl: null, }, status === "unavailable" ? 503 : 200); } + +/** + * Pure read-only C-SA-25 authoritative orders/fills projection helper. + * Never touches KV or SQLite writes (ADR 0002 compliant). + */ +export function buildConsoleOrdersFillsReadModel(input = {}, _deps = {}) { + const payload = input?.legacyPayload + ? adaptLegacyBrokerExecutionPayload(input.legacyPayload, input.context || {}) + : input; + return evaluateAuthoritativeOrdersAndFills(payload, { + lockStore: input?.lockStore ?? null, + priorKPendUsd: input?.priorKPendUsd ?? input?.prior_k_pend_usd ?? null, + evaluated_at: input?.evaluated_at, + }); +} diff --git a/web/strategy-switch-console/application/orders_fills/constants.js b/web/strategy-switch-console/application/orders_fills/constants.js new file mode 100644 index 00000000..9a9322ce --- /dev/null +++ b/web/strategy-switch-console/application/orders_fills/constants.js @@ -0,0 +1,111 @@ +/** + * C-SA-25: Authoritative orders, fills, cutoff open orders, and ORDER-UNKNOWN constants. + * + * Pure zero-import constant table under application/orders_fills/: + * - Never imports helpers, Worker/DO modules, storage, or network. + * - Separates broker from paper/live environment and enforces 256/512/2048 caps. + */ + +export const AUTHORITATIVE_ORDERS_FILLS_SCHEMA = "qsl.authoritative_orders_fills.v1"; +export const ORDER_UNKNOWN_LOCK_STORE_SCHEMA = "qsl.order_unknown_lock_store.v1"; + +export const ALLOWED_ORDER_BROKERS = Object.freeze([ + "schwab", + "firstrade", + "ibkr", + "longbridge", + "binance", +]); + +export const ALLOWED_ORDER_ENVIRONMENTS = Object.freeze([ + "live", + "paper", +]); + +export const ORDER_LIFECYCLE_STATES = Object.freeze([ + "SUBMITTED", + "ACCEPTED", + "PARTIAL_FILL", + "FILLED", + "PARTIAL_CANCEL", + "CANCELED", + "REJECTED", + "ORDER_UNKNOWN", +]); + +export const TERMINAL_ORDER_STATES = Object.freeze([ + "FILLED", + "CANCELED", + "REJECTED", +]); + +export const WORKING_ORDER_STATES = Object.freeze([ + "SUBMITTED", + "ACCEPTED", + "PARTIAL_FILL", + "PARTIAL_CANCEL", + "ORDER_UNKNOWN", +]); + +export const ORDER_SIDES = Object.freeze(["BUY", "SELL"]); + +export const ORDER_DOMAIN_NAMES = Object.freeze([ + "submissions", + "executions", + "cutoff_open_orders", +]); + +export const ORDER_DOMAIN_CAPS = Object.freeze([256, 512, 2048]); + +export const DOMAIN_CAPABILITIES = Object.freeze(["supported", "unsupported"]); + +export const COMPLETENESS_STATUSES = Object.freeze([ + "complete", + "incomplete", + "unknown", + "unsupported", +]); + +export const SOURCE_CLASSES = Object.freeze([ + "synthetic", + "historical_reconstruction", + "decision_time_market", + "operator_declared", + "authorized_operational", + "paper_broker", + "authorized_live_broker", +]); + +export const ORIGINS = Object.freeze(["synthetic", "production"]); + +export const BROKER_SET = new Set(ALLOWED_ORDER_BROKERS); +export const ENVIRONMENT_SET = new Set(ALLOWED_ORDER_ENVIRONMENTS); +export const ORDER_STATE_SET = new Set(ORDER_LIFECYCLE_STATES); +export const TERMINAL_STATE_SET = new Set(TERMINAL_ORDER_STATES); +export const ORDER_SIDE_SET = new Set(ORDER_SIDES); +export const DOMAIN_NAME_SET = new Set(ORDER_DOMAIN_NAMES); +export const DOMAIN_CAP_SET = new Set(ORDER_DOMAIN_CAPS); +export const DOMAIN_CAPABILITY_SET = new Set(DOMAIN_CAPABILITIES); +export const COMPLETENESS_SET = new Set(COMPLETENESS_STATUSES); +export const SOURCE_CLASS_SET = new Set(SOURCE_CLASSES); +export const ORIGIN_SET = new Set(ORIGINS); + +export const DECIMAL_RE = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/; +export const NON_NEGATIVE_DECIMAL_RE = /^(?:0|[1-9]\d*)(?:\.\d+)?$/; +export const POSITIVE_DECIMAL_RE = /^(?:0\.\d*[1-9]\d*|[1-9]\d*(?:\.\d+)?)$/; +export const CURRENCY_RE = /^[A-Z]{3,10}$/; +export const SYMBOL_RE = /^[A-Z0-9][A-Z0-9./_-]{0,63}$/; +export const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; +export const OPAQUE_ACCOUNT_SLOT_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/; +export const CANONICAL_ORDER_ACCOUNT_RE = /^(schwab|firstrade|ibkr|longbridge|binance):(live|paper):([a-z0-9][a-z0-9_-]{0,31})$/; +export const HEX64_RE = /^[a-f0-9]{64}$/; +export const SHA256_EVIDENCE_RE = /^sha256:[a-f0-9]{64}$/; + +export class OrdersFillsError extends Error { + constructor(code = "invalid_orders_fills", status = 400) { + super(code); + this.name = "OrdersFillsError"; + this.code = code; + this.status = status; + } +} diff --git a/web/strategy-switch-console/application/orders_fills/coverage.js b/web/strategy-switch-console/application/orders_fills/coverage.js new file mode 100644 index 00000000..48fd9b7e --- /dev/null +++ b/web/strategy-switch-console/application/orders_fills/coverage.js @@ -0,0 +1,221 @@ +/** + * C-SA-25: Explicit cap (256 / 512 / 2048), completeness proof, empty-domain gate, + * unsupported-domain marker, and K_pend non-release enforcement. + * + * Pure leaf module under application/orders_fills/: imports only inward from + * ./constants.js, ../naming_canonical/helpers.js, and ../sizing_unit/nav.js. + */ + +import { isRawAccountIdentifier, isUnsafePrivateLocator } from "../naming_canonical/helpers.js"; +import { parseInstantNs, toUtcIsoFromNs } from "../sizing_unit/nav.js"; +import { + COMPLETENESS_SET, + CURRENCY_RE, + DOMAIN_CAP_SET, + DOMAIN_CAPABILITY_SET, + DOMAIN_NAME_SET, + OrdersFillsError, +} from "./constants.js"; + +function validateSafeCurrencyToken(value, fieldName) { + if (typeof value !== "string" || value.length === 0) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + if (isUnsafePrivateLocator(value)) { + throw new OrdersFillsError(`unsafe_private_locator_${fieldName}`, 400); + } + if (isRawAccountIdentifier(value)) { + throw new OrdersFillsError(`raw_account_id_prohibited_${fieldName}`, 400); + } + if (!CURRENCY_RE.test(value)) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return value; +} + +function validateSafeMetaText(value, fieldName) { + if (typeof value !== "string" || value.trim().length === 0 || value.length > 128) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + if (isUnsafePrivateLocator(value)) { + throw new OrdersFillsError(`unsafe_private_locator_${fieldName}`, 400); + } + if (isRawAccountIdentifier(value)) { + throw new OrdersFillsError(`raw_account_id_prohibited_${fieldName}`, 400); + } + return value; +} + +function parseStrictUtcInstant(value, fieldName, { nullable = false } = {}) { + if (value === null || value === undefined) { + if (nullable) return null; + throw new OrdersFillsError(`missing_${fieldName}`, 400); + } + if (typeof value !== "string") { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + const ns = parseInstantNs(value); + if (ns === null) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return toUtcIsoFromNs(ns); +} + +/** + * Evaluates C-SA-25 domain coverage, cap (256/512/2048), completeness, empty-domain proof, + * and K_pend release gating. + */ +export function evaluateDomainCoverage(rawDomain, options = {}) { + if (!rawDomain || typeof rawDomain !== "object" || Array.isArray(rawDomain)) { + throw new OrdersFillsError("invalid_domain_envelope", 400); + } + const domain = options.domain ?? rawDomain.domain; + if (!DOMAIN_NAME_SET.has(domain)) { + throw new OrdersFillsError("invalid_domain_name", 400); + } + const capability = rawDomain.domain_capability; + if (!DOMAIN_CAPABILITY_SET.has(capability)) { + throw new OrdersFillsError("invalid_domain_capability", 400); + } + + const source = validateSafeMetaText(rawDomain.source, "domain_source"); + const scope = validateSafeMetaText(rawDomain.scope, "domain_scope"); + + if (capability === "unsupported") { + if (Array.isArray(rawDomain.records) && rawDomain.records.length > 0) { + throw new OrdersFillsError("unsupported_domain_has_records", 400); + } + if (rawDomain.completeness === "complete") { + throw new OrdersFillsError("unsupported_domain_cannot_be_complete", 400); + } + if (rawDomain.count !== undefined && rawDomain.count !== null) { + throw new OrdersFillsError("unsupported_domain_cannot_emit_count", 400); + } + const asOf = parseStrictUtcInstant(rawDomain.as_of ?? null, "domain_as_of", { nullable: true }); + return { + domain, + domain_capability: "unsupported", + as_of: asOf, + source, + scope, + native_currency: null, + currencies_present: [], + cap: null, + count: null, + truncated: null, + completeness: "unsupported", + empty_domain_proven: false, + k_pend_release_allowed: false, + records: [], + }; + } + + const asOf = parseStrictUtcInstant(rawDomain.as_of, "domain_as_of", { nullable: false }); + if (!Number.isInteger(rawDomain.cap) || !DOMAIN_CAP_SET.has(rawDomain.cap)) { + throw new OrdersFillsError("invalid_domain_cap", 400); + } + const cap = rawDomain.cap; + + let completeness = rawDomain.completeness; + if (!COMPLETENESS_SET.has(completeness) || completeness === "unsupported") { + throw new OrdersFillsError("invalid_domain_completeness", 400); + } + if (typeof rawDomain.truncated !== "boolean") { + throw new OrdersFillsError("invalid_domain_truncated_flag", 400); + } + const truncated = rawDomain.truncated; + + const normalizedRecords = Array.isArray(options.records) + ? options.records + : Array.isArray(rawDomain.records) + ? rawDomain.records + : null; + + if (normalizedRecords !== null && normalizedRecords.length > cap) { + throw new OrdersFillsError("domain_records_exceed_cap", 400); + } + + let count; + if (rawDomain.count !== undefined && rawDomain.count !== null) { + if (!Number.isInteger(rawDomain.count) || rawDomain.count < 0) { + throw new OrdersFillsError("invalid_domain_count", 400); + } + if (normalizedRecords !== null && rawDomain.count < normalizedRecords.length) { + throw new OrdersFillsError("domain_count_below_records_length", 400); + } + count = rawDomain.count; + } else if (normalizedRecords !== null) { + count = normalizedRecords.length; + } else { + throw new OrdersFillsError("missing_domain_count_or_records", 400); + } + + if (count > cap && !truncated) { + throw new OrdersFillsError("domain_count_exceeds_cap", 400); + } + + if ( + !truncated + && ((normalizedRecords === null && count > 0) || (normalizedRecords !== null && count !== normalizedRecords.length)) + ) { + completeness = "incomplete"; + } + + const evalAtRaw = options.evaluatedAt ?? options.evaluated_at ?? null; + let domainAsOfInFuture = false; + if (evalAtRaw !== null && evalAtRaw !== undefined) { + const evalNs = typeof evalAtRaw === "string" ? parseInstantNs(evalAtRaw) : null; + if (evalNs === null) { + throw new OrdersFillsError("invalid_evaluated_at", 400); + } + const asOfNs = parseInstantNs(asOf); + if (asOfNs !== null && asOfNs > evalNs) { + domainAsOfInFuture = true; + } + } + + const currencies = new Set(); + if (rawDomain.native_currency !== undefined && rawDomain.native_currency !== null) { + currencies.add(validateSafeCurrencyToken(rawDomain.native_currency, "native_currency")); + } + if (normalizedRecords) { + for (const rec of normalizedRecords) { + if (rec && rec.currency !== undefined && rec.currency !== null) { + currencies.add(validateSafeCurrencyToken(rec.currency, "record_currency")); + } + if (rec && rec.fee_currency !== undefined && rec.fee_currency !== null) { + validateSafeCurrencyToken(rec.fee_currency, "record_fee_currency"); + } + } + } + const currenciesPresent = [...currencies].sort(); + const nativeCurrency = currenciesPresent.length === 1 ? currenciesPresent[0] : null; + + const emptyDomainProven = !domainAsOfInFuture + && truncated === false + && completeness === "complete" + && count === 0; + const hasOrderUnknownLocks = Boolean(options.hasOrderUnknownLocks); + const kPendReleaseAllowed = !domainAsOfInFuture + && truncated === false + && completeness === "complete" + && count < cap + && !hasOrderUnknownLocks; + + return { + domain, + domain_capability: "supported", + as_of: asOf, + source, + scope, + native_currency: nativeCurrency, + currencies_present: currenciesPresent, + cap, + count, + truncated, + completeness, + empty_domain_proven: emptyDomainProven, + k_pend_release_allowed: kPendReleaseAllowed, + records: normalizedRecords ?? [], + }; +} diff --git a/web/strategy-switch-console/application/orders_fills/dedup_state.js b/web/strategy-switch-console/application/orders_fills/dedup_state.js new file mode 100644 index 00000000..dd325e04 --- /dev/null +++ b/web/strategy-switch-console/application/orders_fills/dedup_state.js @@ -0,0 +1,852 @@ +/** + * C-SA-25: Execution deduplication, conflicting-duplicate rejection, client_order_id -> + * broker_order_id linking, lifecycle math (partial fill, partial cancel, cancel, reject), + * and K_pend commitment calculation. + * + * Pure leaf module under application/orders_fills/: imports only inward from + * ./constants.js, ./normalize.js, ./order_unknown_lock.js, and ../sizing_unit/nav.js. + */ + +import { + addDecimal, + eqDecimal, + mulDecimal, + parseDecimal, + parseInstantNs, + ratAdd, + ratDiv, + ratMul, + ratSub, + ratToDecimalText, + subDecimal, + toUtcIsoFromNs, +} from "../sizing_unit/nav.js"; +import { + ORDER_STATE_SET, + OrdersFillsError, + TERMINAL_STATE_SET, +} from "./constants.js"; +import { formatQtyExact, formatUsdExact, getSubmissionMeta } from "./normalize.js"; +import { buildOrderUnknownQueryTarget, listActiveOrderUnknownLocks } from "./order_unknown_lock.js"; + +const ZERO_DEC = { num: 0n, scale: 0 }; + +function decEqNullable(aText, bText) { + const aNorm = aText ?? null; + const bNorm = bText ?? null; + if (aNorm === null && bNorm === null) return true; + if (aNorm === null || bNorm === null) return false; + const a = parseDecimal(aNorm); + const b = parseDecimal(bNorm); + return Boolean(a && b && eqDecimal(a, b)); +} + +function mergeTwoExecutions(prev, next) { + if ( + prev.broker !== next.broker + || prev.environment !== next.environment + || prev.account !== next.account + || prev.execution_ref !== next.execution_ref + ) { + throw new OrdersFillsError("execution_dedup_key_mismatch", 409); + } + const prevExecNs = prev.executed_at !== null && prev.executed_at !== undefined + ? parseInstantNs(prev.executed_at) + : null; + const nextExecNs = next.executed_at !== null && next.executed_at !== undefined + ? parseInstantNs(next.executed_at) + : null; + if ( + prev.symbol !== next.symbol + || prev.side !== next.side + || !decEqNullable(prev.qty, next.qty) + || !decEqNullable(prev.price, next.price) + || prev.currency !== next.currency + || (prevExecNs !== null && nextExecNs !== null && prevExecNs !== nextExecNs) + ) { + throw new OrdersFillsError("conflicting_duplicate_execution", 409); + } + + if ((prev.usd_basis_qualified ?? null) !== (next.usd_basis_qualified ?? null)) { + throw new OrdersFillsError("conflicting_duplicate_execution", 409); + } + if (!decEqNullable(prev.notional_usd, next.notional_usd)) { + throw new OrdersFillsError("conflicting_duplicate_execution", 409); + } + + for (const idField of ["client_order_id", "broker_order_id"]) { + const a = prev[idField] ?? null; + const b = next[idField] ?? null; + if (a !== null && b !== null && a !== b) { + throw new OrdersFillsError("conflicting_duplicate_execution", 409); + } + } + + let feeNative = prev.fee_native ?? null; + let feeCurrency = prev.fee_currency ?? null; + let feeUsd = prev.fee_usd ?? null; + let usdBasisQualified = prev.usd_basis_qualified; + + if (prev.fee_native === null && next.fee_native !== null) { + feeNative = next.fee_native; + feeCurrency = next.fee_currency; + feeUsd = next.fee_usd; + usdBasisQualified = prev.usd_basis_qualified || next.usd_basis_qualified; + } else if (prev.fee_native !== null && next.fee_native !== null) { + if (!decEqNullable(prev.fee_native, next.fee_native) || prev.fee_currency !== next.fee_currency) { + throw new OrdersFillsError("conflicting_duplicate_execution", 409); + } + if (prev.fee_usd !== null && next.fee_usd !== null && !decEqNullable(prev.fee_usd, next.fee_usd)) { + throw new OrdersFillsError("conflicting_duplicate_execution", 409); + } + if (feeUsd === null && next.fee_usd !== null) { + feeUsd = next.fee_usd; + } + } else if (prev.fee_currency !== null && next.fee_currency !== null && prev.fee_currency !== next.fee_currency) { + throw new OrdersFillsError("conflicting_duplicate_execution", 409); + } else if (prev.fee_currency === null && next.fee_currency !== null) { + feeCurrency = next.fee_currency; + } + + const executedAt = prev.executed_at ?? next.executed_at ?? null; + const enriched = ( + feeNative !== prev.fee_native + || feeCurrency !== prev.fee_currency + || feeUsd !== prev.fee_usd + || (prev.client_order_id === null && next.client_order_id !== null) + || (prev.broker_order_id === null && next.broker_order_id !== null) + || ((prev.executed_at ?? null) === null && (next.executed_at ?? null) !== null) + ); + + return { + ...prev, + client_order_id: prev.client_order_id ?? next.client_order_id ?? null, + broker_order_id: prev.broker_order_id ?? next.broker_order_id ?? null, + fee_native: feeNative, + fee_currency: feeCurrency, + fee_usd: feeUsd, + usd_basis_qualified: usdBasisQualified, + executed_at: executedAt, + report_ref: enriched && next.report_ref !== null ? next.report_ref : (prev.report_ref ?? next.report_ref ?? null), + evidence_ref: enriched ? next.evidence_ref : prev.evidence_ref, + }; +} + +function compareNullableIso(aIso, bIso) { + if (aIso === bIso) return 0; + if (aIso === null || aIso === undefined) return 1; + if (bIso === null || bIso === undefined) return -1; + return aIso.localeCompare(bIso); +} + +/** + * Deduplicates execution records keyed strictly by (broker, environment, account, execution_ref). + * Throws OrdersFillsError("conflicting_duplicate_execution", 409) on substantive mismatch. + */ +export function deduplicateExecutions(incomingExecutions = [], existingExecutions = []) { + const byKey = new Map(); + for (const row of [...existingExecutions, ...incomingExecutions]) { + if (!row || typeof row !== "object") { + throw new OrdersFillsError("invalid_execution_record", 400); + } + const key = JSON.stringify([row.broker, row.environment, row.account, row.execution_ref]); + if (byKey.has(key)) { + byKey.set(key, mergeTwoExecutions(byKey.get(key), row)); + } else { + byKey.set(key, { ...row }); + } + } + return [...byKey.values()].sort((a, b) => ( + a.broker.localeCompare(b.broker) + || a.environment.localeCompare(b.environment) + || a.account.localeCompare(b.account) + || compareNullableIso(a.executed_at ?? null, b.executed_at ?? null) + || a.execution_ref.localeCompare(b.execution_ref) + )); +} + +function cmpDec(a, b) { + const lhs = a.num * (10n ** BigInt(b.scale)); + const rhs = b.num * (10n ** BigInt(a.scale)); + return lhs < rhs ? -1 : lhs > rhs ? 1 : 0; +} + +function maxDec(a, b) { + return cmpDec(a, b) >= 0 ? a : b; +} + +function maxTimestampIso(aIso, bIso) { + if (!aIso) return bIso; + if (!bIso) return aIso; + const aNs = parseInstantNs(aIso); + const bNs = parseInstantNs(bIso); + if (aNs === null) return bIso; + if (bNs === null) return aIso; + return aNs >= bNs ? toUtcIsoFromNs(aNs) : toUtcIsoFromNs(bNs); +} + +function mergeOrderSkeleton(prev, next) { + if (prev.symbol !== next.symbol || prev.side !== next.side || prev.currency !== next.currency) { + throw new OrdersFillsError("conflicting_duplicate_order", 409); + } + if (!decEqNullable(prev.qty_submitted, next.qty_submitted)) { + throw new OrdersFillsError("conflicting_duplicate_order", 409); + } + if (prev.broker_order_id !== null && next.broker_order_id !== null && prev.broker_order_id !== next.broker_order_id) { + throw new OrdersFillsError("conflicting_duplicate_order", 409); + } + if (prev.limit_price !== null && next.limit_price !== null && !decEqNullable(prev.limit_price, next.limit_price)) { + throw new OrdersFillsError("conflicting_duplicate_order", 409); + } + return { + ...prev, + broker_order_id: prev.broker_order_id ?? next.broker_order_id ?? null, + limit_price: prev.limit_price ?? next.limit_price ?? null, + usd_basis_qualified: prev.usd_basis_qualified || next.usd_basis_qualified, + }; +} + +/** + * Reconciles submissions, deduplicated executions, cutoff open orders, and ORDER-UNKNOWN locks + * for one (broker, environment, account) identity. + */ +export function reconcileOrdersAndFills({ + identity, + submissions = [], + executions = [], + cutoffOpenOrders = [], + cutoffCoverage = null, + lockStore = null, + priorKPendUsd = null, + priorKPendOrderIds = null, + evaluatedAt, +}) { + const evalNs = typeof evaluatedAt === "string" ? parseInstantNs(evaluatedAt) : null; + if (evaluatedAt !== undefined && evaluatedAt !== null && evalNs === null) { + throw new OrdersFillsError("invalid_evaluated_at", 400); + } + const dedupedExecs = deduplicateExecutions(executions, []); + const orderMap = new Map(); + let hasFutureEvents = false; + + const ensureEntry = (clientOrderId, base) => { + const key = `${identity.binding_key}|${clientOrderId}`; + if (!orderMap.has(key)) { + orderMap.set(key, { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + client_order_id: clientOrderId, + broker_order_id: base.broker_order_id ?? null, + symbol: base.symbol, + side: base.side, + currency: base.currency, + qty_submitted: base.qty_submitted, + limit_price: base.limit_price ?? null, + usd_basis_qualified: Boolean(base.usd_basis_qualified), + submission: null, + terminalSub: null, + sawOrderUnknown: false, + sawFutureTransition: false, + cutoff: null, + executions: [], + }); + } else { + const merged = mergeOrderSkeleton(orderMap.get(key), base); + orderMap.set(key, merged); + } + return orderMap.get(key); + }; + + for (const sub of submissions) { + const meta = getSubmissionMeta(sub); + const subSubmittedNs = meta?.submitted_at_ns ?? parseInstantNs(sub.submitted_at); + const subEffectiveNs = meta?.effective_at_ns ?? subSubmittedNs; + const isFutureSub = evalNs !== null && subEffectiveNs !== null && subEffectiveNs > evalNs; + const isSubmittedAfterEval = evalNs !== null && subSubmittedNs !== null && subSubmittedNs > evalNs; + + if (isFutureSub) { + hasFutureEvents = true; + if (isSubmittedAfterEval) { + continue; + } + const entry = ensureEntry(sub.client_order_id, sub); + entry.sawFutureTransition = true; + // Keep original WeakMap-tracked sub object when no prior submission exists, + // while sawFutureTransition prevents future cancel/terminal/filled state taking effect. + if (!entry.submission) { + entry.submission = sub; + } + if (sub.state === "ORDER_UNKNOWN") { + entry.sawOrderUnknown = true; + } + continue; + } + + const entry = ensureEntry(sub.client_order_id, sub); + if (sub.state === "ORDER_UNKNOWN") { + entry.sawOrderUnknown = true; + } + if (entry.submission) { + if ( + entry.submission.state !== sub.state + && TERMINAL_STATE_SET.has(entry.submission.state) + && !TERMINAL_STATE_SET.has(sub.state) + && !entry.sawFutureTransition + ) { + throw new OrdersFillsError("conflicting_duplicate_order", 409); + } + if ( + entry.terminalSub + && TERMINAL_STATE_SET.has(sub.state) + && entry.terminalSub.state !== sub.state + ) { + throw new OrdersFillsError("conflicting_duplicate_order", 409); + } + } + if (TERMINAL_STATE_SET.has(sub.state)) { + entry.terminalSub = sub; + } + entry.submission = sub; + } + + for (const open of cutoffOpenOrders) { + const entry = ensureEntry(open.client_order_id, open); + if (entry.cutoff) { + throw new OrdersFillsError("conflicting_duplicate_order", 409); + } + const cutoffNs = parseInstantNs(open.as_of); + if (evalNs !== null && cutoffNs !== null && cutoffNs > evalNs) { + hasFutureEvents = true; + entry.sawFutureTransition = true; + } + entry.cutoff = open; + } + + // Link executions to orders by client_order_id or broker_order_id within the same account. + // Reject conflicting duplicate broker_order_id across distinct client_order_id values. + const byBrokerOrderId = new Map(); + for (const entry of orderMap.values()) { + if (entry.broker_order_id !== null) { + const existingOwner = byBrokerOrderId.get(entry.broker_order_id); + if (existingOwner && existingOwner.client_order_id !== entry.client_order_id) { + throw new OrdersFillsError("conflicting_duplicate_broker_order_id", 409); + } + byBrokerOrderId.set(entry.broker_order_id, entry); + } + } + let hasUnknownExecTimestamps = false; + const linkExecutionToTarget = (exec, target) => { + if (target.symbol !== exec.symbol || target.side !== exec.side || target.currency !== exec.currency) { + throw new OrdersFillsError("execution_order_mismatch", 409); + } + if (target.broker_order_id !== null && exec.broker_order_id !== null && target.broker_order_id !== exec.broker_order_id) { + throw new OrdersFillsError("execution_broker_order_id_mismatch", 409); + } + if (target.broker_order_id === null && exec.broker_order_id !== null) { + const existingOwner = byBrokerOrderId.get(exec.broker_order_id); + if (existingOwner && existingOwner.client_order_id !== target.client_order_id) { + throw new OrdersFillsError("conflicting_duplicate_broker_order_id", 409); + } + target.broker_order_id = exec.broker_order_id; + byBrokerOrderId.set(exec.broker_order_id, target); + } + target.executions.push(exec); + }; + + // Pass 1: link client_order_id-bearing executions first so they populate missing + // broker_order_id mappings before retrying broker_order_id-only executions. + const unmatchedBrokerExecs = []; + for (const exec of dedupedExecs) { + const execNs = exec.executed_at !== null && exec.executed_at !== undefined + ? parseInstantNs(exec.executed_at) + : null; + if (execNs === null) { + hasUnknownExecTimestamps = true; + } else if (evalNs !== null && execNs > evalNs) { + hasFutureEvents = true; + } + if (exec.client_order_id !== null) { + const target = orderMap.get(`${identity.binding_key}|${exec.client_order_id}`) ?? null; + if (target) { + linkExecutionToTarget(exec, target); + } + } else if (exec.broker_order_id !== null) { + unmatchedBrokerExecs.push(exec); + } + } + for (const exec of unmatchedBrokerExecs) { + const target = byBrokerOrderId.get(exec.broker_order_id) ?? null; + if (target) { + linkExecutionToTarget(exec, target); + } + } + for (const entry of orderMap.values()) { + if (entry.executions.length > 1) { + entry.executions.sort((a, b) => ( + compareNullableIso(a.executed_at ?? null, b.executed_at ?? null) + || a.execution_ref.localeCompare(b.execution_ref) + )); + } + } + + const activeLocks = lockStore ? listActiveOrderUnknownLocks(lockStore, identity) : []; + const lockByClientId = new Map(activeLocks.map((l) => [l.client_order_id, l])); + const lockByBrokerId = new Map(activeLocks.filter((l) => l.broker_order_id !== null).map((l) => [l.broker_order_id, l])); + + const reconciledOrders = []; + const computedOrderLocks = new Map(); + + for (const entry of orderMap.values()) { + const sub = entry.submission; + const cutoff = entry.cutoff; + const matchingExecs = entry.executions; + const effectiveExecs = matchingExecs.filter((ex) => { + if (ex.executed_at === null || ex.executed_at === undefined) return false; + if (evalNs === null) return true; + const exNs = parseInstantNs(ex.executed_at); + return exNs !== null && exNs <= evalNs; + }); + const orderHasUnknownExecTs = matchingExecs.some( + (ex) => ex.executed_at === null || ex.executed_at === undefined, + ); + const lockFromClient = lockByClientId.get(entry.client_order_id) ?? null; + const lockFromBroker = entry.broker_order_id !== null ? (lockByBrokerId.get(entry.broker_order_id) ?? null) : null; + if (lockFromClient && lockFromBroker && lockFromClient.client_order_id !== lockFromBroker.client_order_id) { + throw new OrdersFillsError("conflicting_broker_order_id_on_lock", 409); + } + const activeLock = lockFromClient ?? lockFromBroker ?? null; + if (activeLock && activeLock.symbol !== entry.symbol) { + throw new OrdersFillsError("order_unknown_symbol_mismatch", 409); + } + + const subDec = parseDecimal(entry.qty_submitted); + let filledFromExecs = ZERO_DEC; + for (const ex of effectiveExecs) { + filledFromExecs = addDecimal(filledFromExecs, parseDecimal(ex.qty)); + } + const cutoffNs = cutoff ? parseInstantNs(cutoff.as_of) : null; + if (cutoff && cutoffNs === null) { + throw new OrdersFillsError("invalid_cutoff_as_of", 400); + } + const cutoffIsFuture = Boolean(cutoff && evalNs !== null && cutoffNs !== null && cutoffNs > evalNs); + const subMeta = getSubmissionMeta(sub); + + let filledDec = ZERO_DEC; + let filledAfterCutoff = ZERO_DEC; + let canceledDec = ZERO_DEC; + let postCutoffSubTerminal = false; + + if (cutoff && !cutoffIsFuture) { + let filledUpToCutoffFromExecs = ZERO_DEC; + for (const ex of effectiveExecs) { + const exNs = ex.executed_at !== null && ex.executed_at !== undefined + ? parseInstantNs(ex.executed_at) + : null; + if (exNs === null) { + continue; + } + if (exNs <= cutoffNs) { + filledUpToCutoffFromExecs = addDecimal(filledUpToCutoffFromExecs, parseDecimal(ex.qty)); + } else { + filledAfterCutoff = addDecimal(filledAfterCutoff, parseDecimal(ex.qty)); + } + } + const cutoffFilled = parseDecimal(cutoff.qty_filled); + const filledAtCutoffDec = maxDec(filledUpToCutoffFromExecs, cutoffFilled); + const canceledAtCutoffDec = parseDecimal(cutoff.qty_canceled); + const remainingAtCutoffDec = subDecimal(subDecimal(subDec, filledAtCutoffDec), canceledAtCutoffDec); + if (remainingAtCutoffDec.num < 0n) { + throw new OrdersFillsError("order_quantities_exceed_submitted", 400); + } + if (!eqDecimal(remainingAtCutoffDec, parseDecimal(cutoff.qty_remaining))) { + throw new OrdersFillsError("order_remaining_cutoff_mismatch", 409); + } + + filledDec = addDecimal(filledAtCutoffDec, filledAfterCutoff); + canceledDec = canceledAtCutoffDec; + const subTransitionNs = sub + ? (subMeta?.effective_at_ns ?? parseInstantNs(sub.submitted_at)) + : null; + if ( + !entry.sawFutureTransition + && sub + && subTransitionNs !== null + && subTransitionNs > cutoffNs + ) { + if (subMeta?.qty_canceled !== undefined) { + canceledDec = maxDec(canceledAtCutoffDec, parseDecimal(subMeta.qty_canceled)); + } else if (sub.state === "CANCELED" || sub.state === "REJECTED") { + canceledDec = maxDec(canceledAtCutoffDec, subDecimal(subDec, filledDec)); + } else if (sub.state === "PARTIAL_CANCEL" && filledDec.num > 0n) { + canceledDec = maxDec(canceledAtCutoffDec, subDecimal(subDec, filledDec)); + } + if (TERMINAL_STATE_SET.has(sub.state) || sub.state === "PARTIAL_CANCEL") { + postCutoffSubTerminal = true; + } + } + } else { + filledDec = filledFromExecs; + if (!entry.sawFutureTransition && !cutoffIsFuture) { + if (subMeta?.qty_canceled !== undefined) { + canceledDec = parseDecimal(subMeta.qty_canceled); + } else if (sub && (sub.state === "CANCELED" || sub.state === "REJECTED")) { + canceledDec = subDecimal(subDec, filledDec); + } + } + } + + if (cmpDec(filledDec, subDec) > 0 || cmpDec(addDecimal(filledDec, canceledDec), subDec) > 0) { + throw new OrdersFillsError("order_quantities_exceed_submitted", 400); + } + + const isDefinitiveFilled = !entry.sawFutureTransition && ( + (cutoff && !cutoffIsFuture && cutoff.state === "FILLED") + || (sub?.state === "FILLED" && (!cutoff || postCutoffSubTerminal)) + ); + if (isDefinitiveFilled) { + if (canceledDec.num > 0n) { + throw new OrdersFillsError("conflicting_duplicate_order", 409); + } + filledDec = subDec; + canceledDec = ZERO_DEC; + } + + const remainingDec = subDecimal(subDecimal(subDec, filledDec), canceledDec); + if (remainingDec.num < 0n) { + throw new OrdersFillsError("order_quantities_exceed_submitted", 400); + } + + let state = (postCutoffSubTerminal ? sub.state : null) + ?? (cutoff && !cutoffIsFuture ? cutoff.state : null) + ?? (entry.sawFutureTransition ? (entry.sawOrderUnknown ? "ORDER_UNKNOWN" : "SUBMITTED") : sub?.state) + ?? "SUBMITTED"; + if (!ORDER_STATE_SET.has(state)) { + throw new OrdersFillsError("invalid_order_state", 400); + } + const subTerminal = !entry.sawFutureTransition && (Boolean(entry.terminalSub) || (sub && TERMINAL_STATE_SET.has(sub.state))); + const cutoffTerminal = Boolean(cutoff && !cutoffIsFuture && TERMINAL_STATE_SET.has(cutoff.state)); + const terminalObserved = !entry.sawFutureTransition && (subTerminal || cutoffTerminal); + + if ((activeLock || entry.sawOrderUnknown) && !terminalObserved) { + state = "ORDER_UNKNOWN"; + } else if (entry.sawFutureTransition && TERMINAL_STATE_SET.has(state)) { + state = activeLock || entry.sawOrderUnknown ? "ORDER_UNKNOWN" : "SUBMITTED"; + } else if (!terminalObserved && state !== "ORDER_UNKNOWN" && state !== "PARTIAL_CANCEL") { + if (remainingDec.num === 0n && eqDecimal(filledDec, subDec) && !cutoffIsFuture) { + state = "FILLED"; + } else if (remainingDec.num === 0n && filledDec.num > 0n && canceledDec.num > 0n && !cutoffIsFuture) { + state = "PARTIAL_CANCEL"; + } else if (filledDec.num > 0n && remainingDec.num > 0n) { + state = "PARTIAL_FILL"; + } + } + + // Avg fill price across effective executions only when execution qty backs reconciled fills + let avgFillPrice = null; + if (effectiveExecs.length > 0 && filledFromExecs.num > 0n && eqDecimal(filledFromExecs, filledDec)) { + let totalVal = { n: 0n, d: 1n }; + let totalQty = { n: 0n, d: 1n }; + for (const ex of effectiveExecs) { + const q = parseDecimal(ex.qty); + const p = parseDecimal(ex.price); + const qRat = { n: q.num, d: 10n ** BigInt(q.scale) }; + const pRat = { n: p.num, d: 10n ** BigInt(p.scale) }; + totalVal = ratAdd(totalVal, ratMul(qRat, pRat)); + totalQty = ratAdd(totalQty, qRat); + } + if (totalQty.n > 0n) { + avgFillPrice = ratToDecimalText(ratDiv(totalVal, totalQty), { minScale: 2, maxScale: 8 }); + } + } + + // Fees: preserve null whenever any fee is missing or execution details lag filled qty. + let feeNative = null; + let feeCurrency = null; + let feeUsd = null; + if (effectiveExecs.length > 0 && eqDecimal(filledFromExecs, filledDec)) { + const anyNullFee = effectiveExecs.some((ex) => ex.fee_native === null); + const feeCurrencies = [...new Set(effectiveExecs.map((ex) => ex.fee_currency).filter(Boolean))]; + if (!anyNullFee && feeCurrencies.length === 1) { + let sumNative = ZERO_DEC; + for (const ex of effectiveExecs) { + sumNative = addDecimal(sumNative, parseDecimal(ex.fee_native)); + } + feeCurrency = feeCurrencies[0]; + feeNative = feeCurrency === "USD" ? formatUsdExact(sumNative) : formatQtyExact(sumNative); + } + const allUsd = effectiveExecs.every((ex) => ex.fee_usd !== null); + if (allUsd) { + let sumUsd = ZERO_DEC; + for (const ex of effectiveExecs) { + sumUsd = addDecimal(sumUsd, parseDecimal(ex.fee_usd)); + } + feeUsd = formatUsdExact(sumUsd); + } + } else if (effectiveExecs.length === 0 && filledFromExecs.num === 0n && sub && sub.fee_native !== null) { + feeNative = sub.fee_native; + feeCurrency = sub.fee_currency; + feeUsd = sub.fee_usd; + } + + let notionalUsd = null; + let usdBasisQualified = entry.currency === "USD" || entry.usd_basis_qualified; + if (entry.currency === "USD") { + if (filledFromExecs.num > 0n && eqDecimal(filledFromExecs, filledDec)) { + let sumNotional = ZERO_DEC; + for (const ex of effectiveExecs) { + sumNotional = addDecimal(sumNotional, parseDecimal(ex.notional_usd)); + } + notionalUsd = formatUsdExact(sumNotional); + } else if (filledDec.num === 0n && entry.limit_price !== null) { + notionalUsd = formatUsdExact(mulDecimal(subDec, parseDecimal(entry.limit_price))); + } + } else if ( + effectiveExecs.length > 0 + && eqDecimal(filledFromExecs, filledDec) + && effectiveExecs.every((ex) => ex.notional_usd !== null) + ) { + let sumNotional = ZERO_DEC; + for (const ex of effectiveExecs) { + sumNotional = addDecimal(sumNotional, parseDecimal(ex.notional_usd)); + } + notionalUsd = formatUsdExact(sumNotional); + usdBasisQualified = true; + } + + let kPendUsd = null; + const isTerminalZeroRemaining = ( + (TERMINAL_STATE_SET.has(state) || (state === "PARTIAL_CANCEL" && remainingDec.num === 0n)) + && !entry.sawFutureTransition + ); + if (entry.side === "SELL") { + kPendUsd = usdBasisQualified ? "0" : null; + } else if (isTerminalZeroRemaining) { + kPendUsd = usdBasisQualified ? "0" : null; + } else if (orderHasUnknownExecTs && cutoff && !cutoffIsFuture) { + kPendUsd = null; + } else if (activeLock && activeLock.k_pend_usd !== null) { + kPendUsd = activeLock.k_pend_usd; + } else if (cutoff && !cutoffIsFuture && cutoff.k_pend_usd !== null && filledAfterCutoff.num === 0n) { + kPendUsd = cutoff.k_pend_usd; + } else if (entry.currency === "USD") { + if (remainingDec.num === 0n) { + kPendUsd = "0"; + } else if (entry.limit_price !== null) { + const feeReserveRaw = cutoff?.reserved_fee_usd ?? subMeta?.estimated_fee_usd ?? null; + if (feeReserveRaw === null) { + kPendUsd = null; + } else { + const baseNotional = mulDecimal(remainingDec, parseDecimal(entry.limit_price)); + kPendUsd = formatUsdExact(addDecimal(baseNotional, parseDecimal(feeReserveRaw))); + } + } else { + kPendUsd = null; + } + } + + const subEventIso = !entry.sawFutureTransition + ? (subMeta?.effective_at_ns !== null && subMeta?.effective_at_ns !== undefined + ? toUtcIsoFromNs(subMeta.effective_at_ns) + : (sub?.submitted_at ?? null)) + : (sub?.submitted_at ?? null); + let latestExecAt = null; + for (const ex of effectiveExecs) { + latestExecAt = maxTimestampIso(latestExecAt, ex.executed_at); + } + const updatedAt = maxTimestampIso( + maxTimestampIso(subEventIso, cutoff && !cutoffIsFuture ? cutoff.as_of : null), + latestExecAt, + ) ?? evaluatedAt; + + const queryTarget = state === "ORDER_UNKNOWN" + ? buildOrderUnknownQueryTarget({ + ...identity, + client_order_id: entry.client_order_id, + broker_order_id: entry.broker_order_id, + }) + : null; + + const evidenceRef = cutoff?.evidence_ref + ?? (effectiveExecs.length > 0 ? effectiveExecs[effectiveExecs.length - 1].evidence_ref : null) + ?? sub?.evidence_ref + ?? (matchingExecs.length > 0 ? matchingExecs[matchingExecs.length - 1].evidence_ref : "sa2:reconciled"); + + if (state === "ORDER_UNKNOWN") { + computedOrderLocks.set(entry.client_order_id, { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + symbol: entry.symbol, + client_order_id: entry.client_order_id, + broker_order_id: entry.broker_order_id, + query_target: queryTarget, + k_pend_usd: kPendUsd, + locked_at: activeLock?.locked_at ?? updatedAt, + status: "locked", + allow_new_orders: false, + query_before_retry_required: true, + clear_condition: "definitive_terminal_broker_evidence", + }); + } + + reconciledOrders.push({ + broker: identity.broker, + environment: identity.environment, + account: identity.account, + client_order_id: entry.client_order_id, + broker_order_id: entry.broker_order_id, + symbol: entry.symbol, + side: entry.side, + state, + currency: entry.currency, + qty_submitted: entry.qty_submitted, + qty_filled: formatQtyExact(filledDec), + qty_canceled: formatQtyExact(canceledDec), + qty_remaining: formatQtyExact(remainingDec), + limit_price: entry.limit_price, + avg_fill_price: avgFillPrice, + fee_native: feeNative, + fee_currency: feeCurrency, + fee_usd: feeUsd, + notional_usd: notionalUsd, + k_pend_usd: kPendUsd, + usd_basis_qualified: usdBasisQualified, + query_target: queryTarget, + updated_at: updatedAt, + evidence_ref: evidenceRef, + }); + } + + // Merge active locks from external persistent lockStore that were NOT terminated on exact symbol & identity. + for (const lock of activeLocks) { + if (!computedOrderLocks.has(lock.client_order_id)) { + const terminatedOnMatchingOrder = reconciledOrders.some((o) => { + const ordMeta = orderMap.get(`${identity.binding_key}|${o.client_order_id}`); + if (ordMeta?.sawFutureTransition) return false; + const idMatches = o.client_order_id === lock.client_order_id + || (lock.broker_order_id !== null && o.broker_order_id === lock.broker_order_id); + return ( + idMatches + && o.broker === lock.broker + && o.environment === lock.environment + && o.account === lock.account + && o.symbol === lock.symbol + && TERMINAL_STATE_SET.has(o.state) + ); + }); + if (!terminatedOnMatchingOrder) { + computedOrderLocks.set(lock.client_order_id, lock); + } + } + } + + const orderUnknownLocks = [...computedOrderLocks.values()].sort((a, b) => ( + a.symbol.localeCompare(b.symbol) || a.client_order_id.localeCompare(b.client_order_id) + )); + const orderUnknownSymbols = [...new Set(orderUnknownLocks.map((l) => l.symbol))].sort(); + + const priorOrderIdSet = new Set(); + if (Array.isArray(priorKPendOrderIds)) { + for (const id of priorKPendOrderIds) { + if (typeof id === "string" && id.length > 0) priorOrderIdSet.add(id); + } + } + + // Compute aggregate K_pend in USD across working orders + any unrepresented external locks, + // partitioning any overlapping prior-accounted IDs from non-overlapping new orders/submissions. + let overlapVisibleDec = ZERO_DEC; + let newNonOverlappingDec = ZERO_DEC; + let kPendUnavailable = false; + const accountedLockClientIds = new Set(); + + for (const ord of reconciledOrders) { + if (ord.state === "ORDER_UNKNOWN") accountedLockClientIds.add(ord.client_order_id); + const isWorkingBuy = ord.side === "BUY" + && !TERMINAL_STATE_SET.has(ord.state) + && !(ord.state === "PARTIAL_CANCEL" && ord.qty_remaining === "0"); + if (ord.k_pend_usd === null) { + if (isWorkingBuy) { + kPendUnavailable = true; + } + } else { + const kDec = parseDecimal(ord.k_pend_usd); + const isPriorOverlap = priorOrderIdSet.has(ord.client_order_id) + || (ord.broker_order_id !== null && priorOrderIdSet.has(ord.broker_order_id)); + if (isPriorOverlap) { + overlapVisibleDec = addDecimal(overlapVisibleDec, kDec); + } else { + newNonOverlappingDec = addDecimal(newNonOverlappingDec, kDec); + } + } + } + + for (const lock of orderUnknownLocks) { + if (accountedLockClientIds.has(lock.client_order_id)) continue; + if (lock.k_pend_usd === null) { + kPendUnavailable = true; + } else { + const kDec = parseDecimal(lock.k_pend_usd); + const isPriorOverlap = priorOrderIdSet.has(lock.client_order_id) + || (lock.broker_order_id !== null && priorOrderIdSet.has(lock.broker_order_id)); + if (isPriorOverlap) { + overlapVisibleDec = addDecimal(overlapVisibleDec, kDec); + } else { + newNonOverlappingDec = addDecimal(newNonOverlappingDec, kDec); + } + } + } + + const cutoffCoverageAsOfNs = cutoffCoverage?.as_of ? parseInstantNs(cutoffCoverage.as_of) : null; + const cutoffCoverageIsFuture = Boolean( + evalNs !== null && cutoffCoverageAsOfNs !== null && cutoffCoverageAsOfNs > evalNs, + ); + if (cutoffCoverageIsFuture) { + hasFutureEvents = true; + } + const cutoffDomainProvenComplete = Boolean(cutoffCoverage?.k_pend_release_allowed) && !cutoffCoverageIsFuture; + const coverageAllowsRelease = ( + cutoffDomainProvenComplete + && orderUnknownLocks.length === 0 + && !hasFutureEvents + && !hasUnknownExecTimestamps + ); + + if ( + (!cutoffDomainProvenComplete || (hasUnknownExecTimestamps && overlapVisibleDec.num === 0n && newNonOverlappingDec.num === 0n)) + && (priorKPendUsd === null || priorKPendUsd === undefined) + ) { + kPendUnavailable = true; + } + + let kPendUsdOut = null; + if (!kPendUnavailable) { + if (!coverageAllowsRelease && priorKPendUsd !== null && priorKPendUsd !== undefined) { + const priorDec = typeof priorKPendUsd === "string" ? parseDecimal(priorKPendUsd) : null; + if (!priorDec || priorDec.num < 0n) { + throw new OrdersFillsError("invalid_prior_k_pend_usd", 400); + } + kPendUsdOut = formatUsdExact(addDecimal(newNonOverlappingDec, maxDec(overlapVisibleDec, priorDec))); + } else { + kPendUsdOut = formatUsdExact(addDecimal(overlapVisibleDec, newNonOverlappingDec)); + } + } else if (!coverageAllowsRelease && priorKPendUsd !== null && priorKPendUsd !== undefined) { + // Still validate explicit priorKPendUsd type/sign even when unknown working order keeps total K_pend null + const priorDec = typeof priorKPendUsd === "string" ? parseDecimal(priorKPendUsd) : null; + if (!priorDec || priorDec.num < 0n) { + throw new OrdersFillsError("invalid_prior_k_pend_usd", 400); + } + } + + reconciledOrders.sort((a, b) => a.client_order_id.localeCompare(b.client_order_id)); + + return { + orders: reconciledOrders, + executions: dedupedExecs, + order_unknown_locks: orderUnknownLocks, + order_unknown_symbols: orderUnknownSymbols, + k_pend_usd: kPendUsdOut, + k_pend_release_allowed: coverageAllowsRelease, + has_future_events: hasFutureEvents, + }; +} diff --git a/web/strategy-switch-console/application/orders_fills/helpers.js b/web/strategy-switch-console/application/orders_fills/helpers.js new file mode 100644 index 00000000..8a6ecd48 --- /dev/null +++ b/web/strategy-switch-console/application/orders_fills/helpers.js @@ -0,0 +1,180 @@ +/** + * C-SA-25: Authoritative orders, fills, cutoff open orders, and ORDER-UNKNOWN composition entrypoint. + * + * Pure leaf barrel/composition module under application/orders_fills/: + * - Imports only inward from sibling leaf modules and ../naming_canonical / ../sizing_unit/nav.js. + * - Never imports runtime_support.js, worker.js, storage, or network. + */ + +import { isRawAccountIdentifier, isUnsafePrivateLocator } from "../naming_canonical/helpers.js"; +import { parseInstantNs, stripPrivateLocators, toUtcIsoFromNs } from "../sizing_unit/nav.js"; +import { + AUTHORITATIVE_ORDERS_FILLS_SCHEMA, + ORIGIN_SET, + OrdersFillsError, + SAFE_ID_RE, + SHA256_EVIDENCE_RE, + SOURCE_CLASS_SET, +} from "./constants.js"; +import { evaluateDomainCoverage } from "./coverage.js"; +import { deduplicateExecutions, reconcileOrdersAndFills } from "./dedup_state.js"; +import { adaptLegacyBrokerExecutionPayload, normalizeBrokerIdentity, normalizeOrderDomain } from "./normalize.js"; +import { + applyOrderUnknownObservation, + checkSymbolOrderAllowed, + createOrderUnknownLockStore, + deserializeOrderUnknownLockStore, + listActiveOrderUnknownLocks, + lockedSymbolsForAccount, + serializeOrderUnknownLockStore, +} from "./order_unknown_lock.js"; + +export { + AUTHORITATIVE_ORDERS_FILLS_SCHEMA, + OrdersFillsError, + adaptLegacyBrokerExecutionPayload, + applyOrderUnknownObservation, + checkSymbolOrderAllowed, + createOrderUnknownLockStore, + deduplicateExecutions, + deserializeOrderUnknownLockStore, + evaluateDomainCoverage, + listActiveOrderUnknownLocks, + lockedSymbolsForAccount, + normalizeBrokerIdentity, + normalizeOrderDomain, + reconcileOrdersAndFills, + serializeOrderUnknownLockStore, +}; + +function validateEnvelopeRef(value, fieldName) { + if (typeof value !== "string" || value.length === 0 || value.length > 128) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + if (isUnsafePrivateLocator(value)) { + throw new OrdersFillsError(`unsafe_private_locator_${fieldName}`, 400); + } + if (SHA256_EVIDENCE_RE.test(value)) return value; + if (isRawAccountIdentifier(value) || !SAFE_ID_RE.test(value)) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return value; +} + +function parseEnvelopeUtc(value, fieldName, { nullable = false } = {}) { + if (value === null || value === undefined) { + if (nullable) return null; + throw new OrdersFillsError(`missing_${fieldName}`, 400); + } + if (typeof value !== "string") { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + const ns = parseInstantNs(value); + if (ns === null) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return toUtcIsoFromNs(ns); +} + +/** + * Evaluates and reconciles submissions, executions, cutoff open orders, cap/completeness proof, + * and ORDER-UNKNOWN locks into a closed qsl.authoritative_orders_fills.v1 envelope. + */ +export function evaluateAuthoritativeOrdersAndFills(input, options = {}) { + if (!input || typeof input !== "object" || Array.isArray(input)) { + throw new OrdersFillsError("invalid_orders_fills_input", 400); + } + const identity = normalizeBrokerIdentity(input); + const asOf = parseEnvelopeUtc(input.as_of ?? null, "as_of", { nullable: true }); + const evaluatedAt = parseEnvelopeUtc(input.evaluated_at ?? options.evaluated_at, "evaluated_at", { nullable: false }); + + const origin = ORIGIN_SET.has(input.origin) ? input.origin : null; + if (!origin) throw new OrdersFillsError("invalid_origin", 400); + const sourceClass = SOURCE_CLASS_SET.has(input.source_class) ? input.source_class : null; + if (!sourceClass) throw new OrdersFillsError("invalid_source_class", 400); + const evidenceRef = validateEnvelopeRef(input.evidence_ref, "evidence_ref"); + + if (!input.domains || typeof input.domains !== "object" || Array.isArray(input.domains)) { + throw new OrdersFillsError("missing_domains", 400); + } + + const lockStore = options.lockStore ?? null; + const submissions = normalizeOrderDomain("submissions", input.domains.submissions, identity, { evaluatedAt }); + const executions = normalizeOrderDomain("executions", input.domains.executions, identity, { evaluatedAt }); + const prelimCutoff = normalizeOrderDomain("cutoff_open_orders", input.domains.cutoff_open_orders, identity, { evaluatedAt }); + + const priorOrdersFills = options.priorOrdersFills ?? input.prior_orders_fills ?? null; + const priorKPendOrderIds = options.priorKPendOrderIds + ?? input.prior_k_pend_order_ids + ?? (Array.isArray(priorOrdersFills?.orders) ? priorOrdersFills.orders.map((o) => o.client_order_id) : null); + + const reconciled = reconcileOrdersAndFills({ + identity, + submissions: submissions.records, + executions: executions.records, + cutoffOpenOrders: prelimCutoff.records, + cutoffCoverage: prelimCutoff, + lockStore, + priorKPendUsd: options.priorKPendUsd ?? input.prior_k_pend_usd ?? priorOrdersFills?.summary?.k_pend_usd ?? null, + priorKPendOrderIds, + evaluatedAt, + }); + + const hasOrderUnknownLocks = reconciled.order_unknown_locks.length > 0; + const cutoffFinal = { + ...prelimCutoff, + k_pend_release_allowed: Boolean(reconciled.k_pend_release_allowed), + }; + + const currenciesSet = new Set([ + ...submissions.currencies_present, + ...executions.currencies_present, + ...cutoffFinal.currencies_present, + ...reconciled.orders.map((o) => o.currency), + ]); + const currenciesPresent = [...currenciesSet].sort(); + + const status = hasOrderUnknownLocks + ? "blocked" + : cutoffFinal.domain_capability === "unsupported" && submissions.domain_capability === "unsupported" && executions.domain_capability === "unsupported" + ? "unavailable" + : "ok"; + const reason = hasOrderUnknownLocks + ? "order_unknown_symbol_lock_active" + : status === "unavailable" + ? "all_order_domains_unsupported" + : null; + + return stripPrivateLocators({ + schema_version: AUTHORITATIVE_ORDERS_FILLS_SCHEMA, + status, + reason, + broker: identity.broker, + environment: identity.environment, + account: identity.account, + account_binding: identity, + as_of: asOf, + evaluated_at: evaluatedAt, + domains: { + submissions, + executions, + cutoff_open_orders: cutoffFinal, + }, + orders: reconciled.orders, + executions: reconciled.executions, + order_unknown_locks: reconciled.order_unknown_locks, + order_unknown_symbols: reconciled.order_unknown_symbols, + summary: { + k_pend_usd: reconciled.k_pend_usd, + k_pend_release_allowed: reconciled.k_pend_release_allowed, + empty_open_orders_proven: cutoffFinal.empty_domain_proven, + order_unknown_active: hasOrderUnknownLocks, + currencies_present: currenciesPresent, + currency_coercion: "prohibited", + fx_inferred: false, + }, + origin, + source_class: sourceClass, + evidence_ref: evidenceRef, + }); +} diff --git a/web/strategy-switch-console/application/orders_fills/normalize.js b/web/strategy-switch-console/application/orders_fills/normalize.js new file mode 100644 index 00000000..d0ea2fab --- /dev/null +++ b/web/strategy-switch-console/application/orders_fills/normalize.js @@ -0,0 +1,764 @@ +/** + * C-SA-25: Broker-agnostic submission, execution, and cutoff open-order normalizer. + * + * Pure leaf module under application/orders_fills/: + * - Separates broker from paper/live environment and binds keys to (broker, environment, account). + * - Rejects IEEE floats, raw brokerage account IDs, and private storage locators. + * - Preserves null fees (never coerced to "0") and non-USD unavailability without FX guessing. + * - Provides pure additive adaptLegacyBrokerExecutionPayload(...) preserving broker_executions.v1. + */ + +import { isRawAccountIdentifier, isUnsafePrivateLocator } from "../naming_canonical/helpers.js"; +import { + absDecimal, + addDecimal, + formatDecimal, + mulDecimal, + parseDecimal, + parseInstantNs, + subDecimal, + toUtcIsoFromNs, +} from "../sizing_unit/nav.js"; +import { + BROKER_SET, + CANONICAL_ORDER_ACCOUNT_RE, + CURRENCY_RE, + DECIMAL_RE, + ENVIRONMENT_SET, + HEX64_RE, + NON_NEGATIVE_DECIMAL_RE, + OPAQUE_ACCOUNT_SLOT_RE, + ORDER_SIDE_SET, + ORDER_STATE_SET, + OrdersFillsError, + POSITIVE_DECIMAL_RE, + SAFE_ID_RE, + SHA256_EVIDENCE_RE, + SYMBOL_RE, +} from "./constants.js"; +import { evaluateDomainCoverage } from "./coverage.js"; + +function assertSafeIdentifier(value, fieldName, { allowNull = false, allowHex64 = false, allowSha256 = false } = {}) { + if (value === null || value === undefined) { + if (allowNull) return null; + throw new OrdersFillsError(`missing_${fieldName}`, 400); + } + if (typeof value !== "string" || value.length === 0 || value.length > 128) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + if (isUnsafePrivateLocator(value)) { + throw new OrdersFillsError(`unsafe_private_locator_${fieldName}`, 400); + } + if (allowHex64 && HEX64_RE.test(value)) return value; + if (allowSha256 && SHA256_EVIDENCE_RE.test(value)) return value; + if (isRawAccountIdentifier(value)) { + throw new OrdersFillsError(`raw_account_id_prohibited_${fieldName}`, 400); + } + if (!SAFE_ID_RE.test(value)) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return value; +} + +function parseStrictUtcString(value, fieldName) { + if (typeof value !== "string") { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + const ns = parseInstantNs(value); + if (ns === null) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return toUtcIsoFromNs(ns); +} + +function validateSymbol(value) { + if (typeof value !== "string" || !SYMBOL_RE.test(value) || isRawAccountIdentifier(value) || isUnsafePrivateLocator(value)) { + throw new OrdersFillsError("invalid_symbol", 400); + } + return value; +} + +function validateCurrency(value, fieldName = "currency", { allowNull = false } = {}) { + if (value === null || value === undefined) { + if (allowNull) return null; + throw new OrdersFillsError(`missing_${fieldName}`, 400); + } + if (typeof value !== "string") { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + if (isUnsafePrivateLocator(value)) { + throw new OrdersFillsError(`unsafe_private_locator_${fieldName}`, 400); + } + if (isRawAccountIdentifier(value)) { + throw new OrdersFillsError(`raw_account_id_prohibited_${fieldName}`, 400); + } + if (!CURRENCY_RE.test(value)) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return value; +} + +function validateDecimalString(value, fieldName, { allowNull = false, positive = false, nonNegative = false } = {}) { + if (value === null || value === undefined) { + if (allowNull) return null; + throw new OrdersFillsError(`missing_${fieldName}`, 400); + } + if (typeof value !== "string") { + throw new OrdersFillsError(`invalid_float_or_nonstring_${fieldName}`, 400); + } + if (positive && !POSITIVE_DECIMAL_RE.test(value)) { + throw new OrdersFillsError(`non_positive_${fieldName}`, 400); + } + if (nonNegative && !NON_NEGATIVE_DECIMAL_RE.test(value)) { + throw new OrdersFillsError(`negative_or_invalid_${fieldName}`, 400); + } + if (!DECIMAL_RE.test(value)) { + throw new OrdersFillsError(`invalid_decimal_${fieldName}`, 400); + } + const dec = parseDecimal(value); + if (!dec) { + throw new OrdersFillsError(`invalid_decimal_${fieldName}`, 400); + } + if (dec.num === 0n && value.startsWith("-")) return "0"; + return value; +} + +export function formatUsdExact(dec) { + if (!dec || typeof dec.num !== "bigint") return null; + if (dec.num === 0n) return "0"; + return formatDecimal(dec, { minScale: Math.max(2, dec.scale) }); +} + +export function formatQtyExact(dec) { + if (!dec || typeof dec.num !== "bigint") return null; + return formatDecimal(dec); +} + +/** + * Normalizes and validates (broker, environment, account) identity separation. + */ +export function normalizeBrokerIdentity(raw = {}) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new OrdersFillsError("invalid_identity", 400); + } + const broker = raw.broker; + if (typeof broker !== "string" || !BROKER_SET.has(broker)) { + throw new OrdersFillsError("invalid_broker", 400); + } + const environment = raw.environment; + if (typeof environment !== "string" || !ENVIRONMENT_SET.has(environment)) { + throw new OrdersFillsError("invalid_order_environment", 400); + } + const account = raw.account; + if (typeof account !== "string" || account.length === 0 || account.length > 64) { + throw new OrdersFillsError("invalid_account", 400); + } + if (isUnsafePrivateLocator(account)) { + throw new OrdersFillsError("unsafe_private_locator_account", 400); + } + if (isRawAccountIdentifier(account)) { + throw new OrdersFillsError("raw_account_id_prohibited", 400); + } + let slot; + if (account.includes(":")) { + const match = CANONICAL_ORDER_ACCOUNT_RE.exec(account); + if (!match) { + throw new OrdersFillsError("invalid_canonical_account_tuple", 400); + } + const [, acctBroker, acctEnv, parsedSlot] = match; + if (acctBroker !== broker || acctEnv !== environment) { + throw new OrdersFillsError("account_broker_environment_mismatch", 409); + } + if (isRawAccountIdentifier(parsedSlot)) { + throw new OrdersFillsError("raw_account_id_prohibited", 400); + } + slot = parsedSlot; + } else { + if (!OPAQUE_ACCOUNT_SLOT_RE.test(account)) { + throw new OrdersFillsError("invalid_account_slot", 400); + } + slot = account; + } + + const canonicalAccount = `${broker}:${environment}:${slot}`; + + return { + broker, + environment, + account: canonicalAccount, + binding_key: `${broker}|${environment}|${canonicalAccount}`, + }; +} + +function assertRecordIdentityMatches(raw, identity) { + if (raw.broker !== undefined && raw.broker !== identity.broker) { + throw new OrdersFillsError("record_broker_mismatch", 409); + } + if (raw.environment !== undefined && raw.environment !== identity.environment) { + throw new OrdersFillsError("record_environment_mismatch", 409); + } + if (raw.account !== undefined) { + const recIdentity = normalizeBrokerIdentity({ + broker: raw.broker ?? identity.broker, + environment: raw.environment ?? identity.environment, + account: raw.account, + }); + if (recIdentity.account !== identity.account) { + throw new OrdersFillsError("record_account_mismatch", 409); + } + } +} + +function resolveFeeFields(raw) { + const feeNative = validateDecimalString(raw.fee_native ?? null, "fee_native", { allowNull: true }); + const feeCurrency = validateCurrency(raw.fee_currency ?? null, "fee_currency", { allowNull: true }); + if (feeNative === null) { + if (raw.fee_usd !== undefined && raw.fee_usd !== null) { + throw new OrdersFillsError("fee_usd_without_native_fee", 400); + } + return { + fee_native: null, + fee_currency: feeCurrency, + fee_usd: null, + fee_usd_qualified: false, + }; + } + if (feeCurrency === null) { + throw new OrdersFillsError("missing_fee_currency", 400); + } + if (feeCurrency === "USD") { + const dec = parseDecimal(feeNative); + return { + fee_native: feeNative, + fee_currency: "USD", + fee_usd: formatUsdExact(dec), + fee_usd_qualified: true, + }; + } + if (raw.usd_basis_qualified === true && raw.fee_usd !== undefined && raw.fee_usd !== null) { + const explicit = validateDecimalString(raw.fee_usd, "fee_usd"); + return { + fee_native: feeNative, + fee_currency: feeCurrency, + fee_usd: formatUsdExact(parseDecimal(explicit)), + fee_usd_qualified: true, + }; + } + return { + fee_native: feeNative, + fee_currency: feeCurrency, + fee_usd: null, + fee_usd_qualified: false, + }; +} + +function resolveNotionalUsd(qtyText, priceText, currency, raw) { + if (priceText === null) { + if (currency === "USD") return { notional_usd: null, usd_basis_qualified: true }; + return { notional_usd: null, usd_basis_qualified: false }; + } + if (currency === "USD") { + const prod = mulDecimal(parseDecimal(qtyText), parseDecimal(priceText)); + return { notional_usd: formatUsdExact(prod), usd_basis_qualified: true }; + } + if (raw.usd_basis_qualified === true && raw.notional_usd !== undefined && raw.notional_usd !== null) { + const explicit = validateDecimalString(raw.notional_usd, "notional_usd", { nonNegative: true }); + return { notional_usd: formatUsdExact(parseDecimal(explicit)), usd_basis_qualified: true }; + } + return { notional_usd: null, usd_basis_qualified: false }; +} + +const SUBMISSION_META = new WeakMap(); + +export function getSubmissionMeta(record) { + return (record && typeof record === "object" ? SUBMISSION_META.get(record) : null) ?? null; +} + +export function normalizeSubmissionRecord(raw, identity) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new OrdersFillsError("invalid_submission_record", 400); + } + assertRecordIdentityMatches(raw, identity); + const clientOrderId = assertSafeIdentifier(raw.client_order_id, "client_order_id"); + const brokerOrderId = assertSafeIdentifier(raw.broker_order_id ?? null, "broker_order_id", { allowNull: true }); + const symbol = validateSymbol(raw.symbol); + if (!ORDER_SIDE_SET.has(raw.side)) { + throw new OrdersFillsError("invalid_order_side", 400); + } + if (!ORDER_STATE_SET.has(raw.state)) { + throw new OrdersFillsError("invalid_order_state", 400); + } + const qtySubmitted = validateDecimalString(raw.qty_submitted, "qty_submitted", { positive: true }); + const limitPrice = validateDecimalString(raw.limit_price ?? null, "limit_price", { allowNull: true, positive: true }); + const currency = validateCurrency(raw.currency); + const submittedAt = parseStrictUtcString( + raw.submitted_at ?? raw.resolved_at ?? raw.canceled_at ?? raw.updated_at, + "submitted_at", + ); + const submittedAtNs = parseInstantNs(submittedAt); + let effectiveEventAtNs = submittedAtNs; + let resolvedAtNs = null; + for (const [tsField, tsVal] of [ + ["resolved_at", raw.resolved_at], + ["canceled_at", raw.canceled_at], + ["updated_at", raw.updated_at], + ]) { + if (tsVal !== undefined && tsVal !== null) { + const iso = parseStrictUtcString(tsVal, tsField); + const ns = parseInstantNs(iso); + if (ns > effectiveEventAtNs) effectiveEventAtNs = ns; + if (tsField === "resolved_at" || tsField === "canceled_at") { + resolvedAtNs = resolvedAtNs === null || ns > resolvedAtNs ? ns : resolvedAtNs; + } + } + } + const evidenceRef = assertSafeIdentifier(raw.evidence_ref, "evidence_ref", { allowSha256: true }); + + const fee = resolveFeeFields(raw); + const notional = resolveNotionalUsd(qtySubmitted, limitPrice, currency, raw); + + // Optional submission cancel / estimated fee / timestamp metadata carried via WeakMap. + const qtyCanceled = raw.qty_canceled !== undefined && raw.qty_canceled !== null + ? validateDecimalString(raw.qty_canceled, "qty_canceled", { nonNegative: true }) + : null; + const estimatedFeeUsd = raw.estimated_fee_usd !== undefined && raw.estimated_fee_usd !== null + ? validateDecimalString(raw.estimated_fee_usd, "estimated_fee_usd", { nonNegative: true }) + : null; + + const record = { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + client_order_id: clientOrderId, + broker_order_id: brokerOrderId, + symbol, + side: raw.side, + state: raw.state, + qty_submitted: qtySubmitted, + limit_price: limitPrice, + currency, + notional_usd: notional.notional_usd, + fee_native: fee.fee_native, + fee_currency: fee.fee_currency, + fee_usd: fee.fee_usd, + usd_basis_qualified: notional.usd_basis_qualified, + submitted_at: submittedAt, + evidence_ref: evidenceRef, + }; + SUBMISSION_META.set(record, { + ...(qtyCanceled !== null ? { qty_canceled: qtyCanceled } : {}), + ...(estimatedFeeUsd !== null ? { estimated_fee_usd: estimatedFeeUsd } : {}), + submitted_at_ns: submittedAtNs, + effective_at_ns: effectiveEventAtNs, + resolved_at_ns: resolvedAtNs, + }); + return record; +} + +export function normalizeExecutionRecord(raw, identity) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new OrdersFillsError("invalid_execution_record", 400); + } + assertRecordIdentityMatches(raw, identity); + const executionRef = assertSafeIdentifier(raw.execution_ref, "execution_ref", { allowHex64: true }); + const reportRef = assertSafeIdentifier(raw.report_ref ?? null, "report_ref", { allowNull: true, allowHex64: true }); + const clientOrderId = assertSafeIdentifier(raw.client_order_id ?? null, "client_order_id", { allowNull: true }); + const brokerOrderId = assertSafeIdentifier(raw.broker_order_id ?? null, "broker_order_id", { allowNull: true }); + const symbol = validateSymbol(raw.symbol); + if (!ORDER_SIDE_SET.has(raw.side)) { + throw new OrdersFillsError("invalid_order_side", 400); + } + const qty = validateDecimalString(raw.qty, "qty", { positive: true }); + const price = validateDecimalString(raw.price, "price", { nonNegative: true }); + const currency = validateCurrency(raw.currency); + if (raw.executed_at === undefined) { + throw new OrdersFillsError("missing_executed_at", 400); + } + const executedAt = raw.executed_at === null + ? null + : parseStrictUtcString(raw.executed_at, "executed_at"); + const evidenceRef = assertSafeIdentifier(raw.evidence_ref, "evidence_ref", { allowSha256: true }); + + const fee = resolveFeeFields(raw); + const notional = resolveNotionalUsd(qty, price, currency, raw); + + return { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + execution_ref: executionRef, + report_ref: reportRef, + client_order_id: clientOrderId, + broker_order_id: brokerOrderId, + symbol, + side: raw.side, + qty, + price, + currency, + notional_usd: notional.notional_usd, + fee_native: fee.fee_native, + fee_currency: fee.fee_currency, + fee_usd: fee.fee_usd, + usd_basis_qualified: notional.usd_basis_qualified, + executed_at: executedAt, + evidence_ref: evidenceRef, + }; +} + +export function normalizeCutoffOpenOrderRecord(raw, identity) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new OrdersFillsError("invalid_cutoff_open_order_record", 400); + } + assertRecordIdentityMatches(raw, identity); + const clientOrderId = assertSafeIdentifier(raw.client_order_id, "client_order_id"); + const brokerOrderId = assertSafeIdentifier(raw.broker_order_id ?? null, "broker_order_id", { allowNull: true }); + const symbol = validateSymbol(raw.symbol); + if (!ORDER_SIDE_SET.has(raw.side)) { + throw new OrdersFillsError("invalid_order_side", 400); + } + if (!ORDER_STATE_SET.has(raw.state)) { + throw new OrdersFillsError("invalid_order_state", 400); + } + const qtySubmitted = validateDecimalString(raw.qty_submitted, "qty_submitted", { positive: true }); + const qtyFilled = validateDecimalString(raw.qty_filled ?? "0", "qty_filled", { nonNegative: true }); + const qtyCanceled = validateDecimalString(raw.qty_canceled ?? "0", "qty_canceled", { nonNegative: true }); + const expectedRemainingDec = subDecimal( + subDecimal(parseDecimal(qtySubmitted), parseDecimal(qtyFilled)), + parseDecimal(qtyCanceled), + ); + if (expectedRemainingDec.num < 0n) { + throw new OrdersFillsError("open_order_qty_exceeds_submitted", 400); + } + const qtyRemaining = raw.qty_remaining !== undefined && raw.qty_remaining !== null + ? validateDecimalString(raw.qty_remaining, "qty_remaining", { nonNegative: true }) + : formatQtyExact(expectedRemainingDec); + if (parseDecimal(qtyRemaining).num * (10n ** BigInt(expectedRemainingDec.scale)) + !== expectedRemainingDec.num * (10n ** BigInt(parseDecimal(qtyRemaining).scale))) { + throw new OrdersFillsError("open_order_qty_remaining_mismatch", 400); + } + + const limitPrice = validateDecimalString(raw.limit_price ?? null, "limit_price", { allowNull: true, positive: true }); + const currency = validateCurrency(raw.currency); + const asOf = parseStrictUtcString(raw.as_of, "open_order_as_of"); + const evidenceRef = assertSafeIdentifier(raw.evidence_ref, "evidence_ref", { allowSha256: true }); + + const reservedFeeUsd = raw.reserved_fee_usd !== undefined && raw.reserved_fee_usd !== null + ? formatUsdExact(parseDecimal(validateDecimalString(raw.reserved_fee_usd, "reserved_fee_usd", { nonNegative: true }))) + : null; + + let kPendUsd = null; + let usdBasisQualified = currency === "USD" || raw.usd_basis_qualified === true; + if (raw.k_pend_usd !== undefined && raw.k_pend_usd !== null) { + if (!usdBasisQualified) { + kPendUsd = null; + } else { + kPendUsd = formatUsdExact(parseDecimal(validateDecimalString(raw.k_pend_usd, "k_pend_usd", { nonNegative: true }))); + } + } else if (raw.side === "SELL") { + kPendUsd = usdBasisQualified ? "0" : null; + } else if (currency === "USD") { + if (expectedRemainingDec.num === 0n) { + kPendUsd = "0"; + } else if (limitPrice !== null && reservedFeeUsd !== null) { + const baseNotional = mulDecimal(expectedRemainingDec, parseDecimal(limitPrice)); + const feeDec = parseDecimal(reservedFeeUsd); + kPendUsd = formatUsdExact(addDecimal(baseNotional, feeDec)); + } else { + kPendUsd = null; + } + } else { + usdBasisQualified = false; + kPendUsd = null; + } + + return { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + client_order_id: clientOrderId, + broker_order_id: brokerOrderId, + symbol, + side: raw.side, + state: raw.state, + qty_submitted: qtySubmitted, + qty_filled: qtyFilled, + qty_canceled: qtyCanceled, + qty_remaining: qtyRemaining, + limit_price: limitPrice, + currency, + k_pend_usd: kPendUsd, + reserved_fee_usd: reservedFeeUsd, + usd_basis_qualified: usdBasisQualified, + as_of: asOf, + evidence_ref: evidenceRef, + }; +} + +/** + * Normalizes one domain (submissions | executions | cutoff_open_orders) with cap/completeness proof. + */ +export function normalizeOrderDomain(domainName, rawDomain, identity, options = {}) { + if (!rawDomain || typeof rawDomain !== "object" || Array.isArray(rawDomain)) { + throw new OrdersFillsError(`missing_domain_${domainName}`, 400); + } + const capability = rawDomain.domain_capability; + if (capability === "unsupported") { + return evaluateDomainCoverage(rawDomain, { ...options, domain: domainName }); + } + const hasRecordsArray = Array.isArray(rawDomain.records); + if (!hasRecordsArray && rawDomain.records !== undefined) { + throw new OrdersFillsError(`invalid_domain_records_${domainName}`, 400); + } + const rawRecords = hasRecordsArray ? rawDomain.records : []; + let normalizedRecords; + if (domainName === "submissions") { + normalizedRecords = rawRecords.map((rec) => normalizeSubmissionRecord(rec, identity)); + } else if (domainName === "executions") { + normalizedRecords = rawRecords.map((rec) => normalizeExecutionRecord(rec, identity)); + } else if (domainName === "cutoff_open_orders") { + normalizedRecords = rawRecords.map((rec) => normalizeCutoffOpenOrderRecord(rec, identity)); + } else { + throw new OrdersFillsError("invalid_domain_name", 400); + } + + return evaluateDomainCoverage(rawDomain, { + ...options, + domain: domainName, + records: hasRecordsArray ? normalizedRecords : undefined, + }); +} + +/** + * Pure additive adapter converting legacy broker_executions.v1 (ibkr_flex) payloads + * into C-SA-25 multi-domain input without mutating legacy contracts or exposing + * private storage locators (source_ref / source_binding_id) or raw account selectors. + */ +const LEGACY_LOCAL_TIME_RE = /^(?:(\d{4}-\d{2}-\d{2})T)?(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/; + +function validateLegacyTradeDate(tradeDate) { + if (typeof tradeDate !== "string") { + throw new OrdersFillsError("invalid_legacy_execution_trade_date", 400); + } + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(tradeDate); + if (!match) { + throw new OrdersFillsError("invalid_legacy_execution_trade_date", 400); + } + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const probe = new Date(Date.UTC(year, month - 1, day)); + if ( + probe.getUTCFullYear() !== year + || probe.getUTCMonth() !== month - 1 + || probe.getUTCDate() !== day + ) { + throw new OrdersFillsError("invalid_legacy_execution_trade_date", 400); + } + return { year, month, day }; +} + +function parseLegacyLocalTime(localTime, tradeDate) { + if (typeof localTime !== "string") { + throw new OrdersFillsError("invalid_legacy_execution_local_time", 400); + } + const match = LEGACY_LOCAL_TIME_RE.exec(localTime); + if (!match) { + throw new OrdersFillsError("invalid_legacy_execution_local_time", 400); + } + if (match[1] !== undefined && match[1] !== tradeDate) { + throw new OrdersFillsError("invalid_legacy_execution_local_time", 400); + } + const hour = Number(match[2]); + const minute = Number(match[3]); + const second = Number(match[4]); + const ms = match[5] ? Number(match[5].padEnd(3, "0")) : 0; + if (hour > 23 || minute > 59 || second > 59 || ms > 999) { + throw new OrdersFillsError("invalid_legacy_execution_local_time", 400); + } + return { hour, minute, second, ms }; +} + +function buildLegacyZoneFormatter(timeZone) { + if (typeof timeZone !== "string" || timeZone.length === 0 || timeZone.length > 64) { + throw new OrdersFillsError("invalid_legacy_execution_time_zone", 400); + } + try { + return new Intl.DateTimeFormat("en-CA", { + timeZone, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hourCycle: "h23", + }); + } catch { + throw new OrdersFillsError("invalid_legacy_execution_time_zone", 400); + } +} + +function extractZonedWallUtcMs(instantMs, dtf) { + const parts = {}; + for (const part of dtf.formatToParts(new Date(instantMs))) { + if (part.type !== "literal") { + parts[part.type] = Number(part.value); + } + } + const hour = parts.hour === 24 ? 0 : parts.hour; + return Date.UTC(parts.year, parts.month - 1, parts.day, hour, parts.minute, parts.second, 0); +} + +function convertLocalTimeWithZoneToUtc(dateParts, timeParts, dtf) { + const targetWholeSecMs = Date.UTC( + dateParts.year, + dateParts.month - 1, + dateParts.day, + timeParts.hour, + timeParts.minute, + timeParts.second, + 0, + ); + const offset1 = extractZonedWallUtcMs(targetWholeSecMs, dtf) - targetWholeSecMs; + const guess2 = targetWholeSecMs - offset1; + const offset2 = extractZonedWallUtcMs(guess2, dtf) - guess2; + const guess3 = targetWholeSecMs - offset2; + if (extractZonedWallUtcMs(guess3, dtf) !== targetWholeSecMs) { + throw new OrdersFillsError("invalid_legacy_execution_local_time", 400); + } + return toUtcIsoFromNs(BigInt(guess3 + timeParts.ms) * 1_000_000n); +} + +export function adaptLegacyBrokerExecutionPayload(legacyPayload, context = {}) { + if (!legacyPayload || typeof legacyPayload !== "object" || Array.isArray(legacyPayload)) { + throw new OrdersFillsError("invalid_legacy_broker_executions", 400); + } + if (legacyPayload.schema_version !== "broker_executions.v1" || legacyPayload.source !== "ibkr_flex") { + throw new OrdersFillsError("unsupported_legacy_broker_executions_schema", 400); + } + if (!Array.isArray(legacyPayload.records)) { + throw new OrdersFillsError("invalid_legacy_broker_executions_records", 400); + } + if (context.broker !== undefined && context.broker !== "ibkr") { + throw new OrdersFillsError("legacy_source_broker_mismatch", 409); + } + const targetEnv = context.environment ?? "live"; + const acctScope = typeof legacyPayload.account_scope === "string" ? legacyPayload.account_scope : ""; + const acctSelector = typeof legacyPayload.account_selector === "string" ? legacyPayload.account_selector : ""; + if (/^U\d+$/i.test(acctSelector) && targetEnv !== "live") { + throw new OrdersFillsError("legacy_source_environment_mismatch", 409); + } + if (/^DU\d+$/i.test(acctSelector) && targetEnv !== "paper") { + throw new OrdersFillsError("legacy_source_environment_mismatch", 409); + } + if (/\blive\b/i.test(acctScope) && !/\bpaper\b/i.test(acctScope) && targetEnv !== "live") { + throw new OrdersFillsError("legacy_source_environment_mismatch", 409); + } + if (/\bpaper\b/i.test(acctScope) && !/\blive\b/i.test(acctScope) && targetEnv !== "paper") { + throw new OrdersFillsError("legacy_source_environment_mismatch", 409); + } + if (!/\bpaper\b/i.test(acctScope) && !/^DU\d+$/i.test(acctSelector) && targetEnv !== "live") { + throw new OrdersFillsError("legacy_source_environment_mismatch", 409); + } + const identity = normalizeBrokerIdentity({ + broker: "ibkr", + environment: targetEnv, + account: context.account, + }); + const asOf = parseStrictUtcString(legacyPayload.observed_at, "legacy_observed_at"); + const evaluatedAt = context.evaluated_at + ? parseStrictUtcString(context.evaluated_at, "evaluated_at") + : asOf; + const cap = context.cap ?? 256; + const evidenceRef = assertSafeIdentifier( + context.evidence_ref ?? "legacy:broker_executions:v1", + "evidence_ref", + { allowSha256: true }, + ); + const legacyCoverage = typeof legacyPayload.coverage === "string" + && !isRawAccountIdentifier(legacyPayload.coverage) + && !isUnsafePrivateLocator(legacyPayload.coverage) + ? legacyPayload.coverage + : null; + if (!legacyCoverage) { + throw new OrdersFillsError("invalid_legacy_broker_executions_coverage", 400); + } + + const mappedRecords = legacyPayload.records.map((row, idx) => { + const qtyDec = parseDecimal(row?.quantity); + if (!qtyDec || qtyDec.num === 0n) { + throw new OrdersFillsError("invalid_legacy_execution_quantity", 400); + } + const positiveQty = formatQtyExact(absDecimal(qtyDec)); + const dateParts = validateLegacyTradeDate(row.trade_date); + const localTimeParts = row.local_time !== undefined && row.local_time !== null + ? parseLegacyLocalTime(row.local_time, row.trade_date) + : null; + const zoneFormatter = row.time_zone !== undefined && row.time_zone !== null + ? buildLegacyZoneFormatter(row.time_zone) + : null; + + let executedAt = null; + if (row.executed_at !== undefined) { + executedAt = row.executed_at === null + ? null + : parseStrictUtcString(row.executed_at, "legacy_executed_at"); + } else if (localTimeParts !== null && zoneFormatter !== null) { + executedAt = convertLocalTimeWithZoneToUtc(dateParts, localTimeParts, zoneFormatter); + } + return { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + execution_ref: row.execution_ref, + report_ref: row.report_ref ?? null, + client_order_id: null, + broker_order_id: null, + symbol: row.symbol, + side: row.side, + qty: positiveQty, + price: row.price, + currency: row.currency, + fee_native: row.commission ?? null, + fee_currency: row.commission_currency ?? null, + executed_at: executedAt, + evidence_ref: `${evidenceRef}:${idx}`, + }; + }); + + return { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + as_of: asOf, + evaluated_at: evaluatedAt, + origin: context.origin === "production" ? "production" : "synthetic", + source_class: context.source_class ?? "authorized_live_broker", + evidence_ref: evidenceRef, + domains: { + submissions: { + domain_capability: "unsupported", + as_of: null, + source: "ibkr_flex_executions_only", + scope: "account_submissions", + }, + executions: { + domain_capability: "supported", + as_of: asOf, + source: legacyPayload.source, + scope: legacyCoverage, + cap, + count: mappedRecords.length, + truncated: mappedRecords.length >= cap, + completeness: "incomplete", + records: mappedRecords, + }, + cutoff_open_orders: { + domain_capability: "unsupported", + as_of: null, + source: "ibkr_flex_executions_only", + scope: "cutoff_open_orders", + }, + }, + }; +} diff --git a/web/strategy-switch-console/application/orders_fills/order_unknown_lock.js b/web/strategy-switch-console/application/orders_fills/order_unknown_lock.js new file mode 100644 index 00000000..9b90b38e --- /dev/null +++ b/web/strategy-switch-console/application/orders_fills/order_unknown_lock.js @@ -0,0 +1,453 @@ +/** + * C-SA-25 + O4/Q5-2: Restart-persistent ORDER-UNKNOWN symbol lock & query-before-retry invariant. + * + * Pure serializable JSON store under application/orders_fills/: + * - Imports only inward from ./constants.js, ./normalize.js, ../naming_canonical/helpers.js, + * and ../sizing_unit/nav.js (zero Worker/DO, SQLite, KV, or network imports). + * - Binds locks to (broker, environment, account, client_order_id) and symbol. + * - Survives JSON serialization/deserialization reload, prohibits new orders on locked + * symbols, retains K_pend commitment, emits deterministic query_target, and clears + * ONLY upon definitive terminal broker evidence (FILLED / CANCELED / REJECTED). + */ + +import { isRawAccountIdentifier, isUnsafePrivateLocator } from "../naming_canonical/helpers.js"; +import { + addDecimal, + mulDecimal, + parseDecimal, + parseInstantNs, + subDecimal, + toUtcIsoFromNs, +} from "../sizing_unit/nav.js"; +import { + CURRENCY_RE, + ORDER_SIDE_SET, + ORDER_STATE_SET, + ORDER_UNKNOWN_LOCK_STORE_SCHEMA, + OrdersFillsError, + SAFE_ID_RE, + SYMBOL_RE, + TERMINAL_STATE_SET, +} from "./constants.js"; +import { formatUsdExact, normalizeBrokerIdentity } from "./normalize.js"; + +function lockEntryKey(broker, environment, account, clientOrderId) { + return `${broker}|${environment}|${account}|${clientOrderId}`; +} + +function validateSafeLockId(value, fieldName, { allowNull = false } = {}) { + if (value === null || value === undefined) { + if (allowNull) return null; + throw new OrdersFillsError(`missing_${fieldName}`, 400); + } + if (typeof value !== "string" || value.length === 0 || value.length > 128) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + if (isUnsafePrivateLocator(value)) { + throw new OrdersFillsError(`unsafe_private_locator_${fieldName}`, 400); + } + if (isRawAccountIdentifier(value) || !SAFE_ID_RE.test(value)) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return value; +} + +function validateLockSymbol(value) { + if (typeof value !== "string" || !SYMBOL_RE.test(value) || isRawAccountIdentifier(value) || isUnsafePrivateLocator(value)) { + throw new OrdersFillsError("invalid_lock_symbol", 400); + } + return value; +} + +function validateLockTimestamp(value, fieldName) { + if (typeof value !== "string") { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + const ns = parseInstantNs(value); + if (ns === null) { + throw new OrdersFillsError(`invalid_${fieldName}`, 400); + } + return toUtcIsoFromNs(ns); +} + +export function buildOrderUnknownQueryTarget({ broker, environment, account, client_order_id, broker_order_id }) { + if (broker_order_id !== null && broker_order_id !== undefined) { + return { + by: "broker_order_id", + broker, + environment, + account, + client_order_id, + broker_order_id, + }; + } + return { + by: "client_order_tuple", + broker, + environment, + account, + client_order_id, + broker_order_id: null, + }; +} + +function computeOrderUnknownKPendUsd(event) { + const currency = event.currency ?? "USD"; + if ( + typeof currency !== "string" + || isRawAccountIdentifier(currency) + || isUnsafePrivateLocator(currency) + || !CURRENCY_RE.test(currency) + ) { + throw new OrdersFillsError("invalid_order_currency", 400); + } + const usdQualified = currency === "USD" || event.usd_basis_qualified === true; + if (event.k_pend_usd !== undefined && event.k_pend_usd !== null) { + if (!usdQualified) return null; + if (typeof event.k_pend_usd !== "string") { + throw new OrdersFillsError("invalid_k_pend_usd", 400); + } + const dec = parseDecimal(event.k_pend_usd); + if (!dec || dec.num < 0n) throw new OrdersFillsError("invalid_k_pend_usd", 400); + return formatUsdExact(dec); + } + if (event.side === "SELL") { + return usdQualified ? "0" : null; + } + // Never multiply non-USD qty * limit_price into USD even if usd_basis_qualified was set on another field. + if (currency !== "USD") return null; + + let qtyRemDec = null; + if (event.qty_remaining !== undefined && event.qty_remaining !== null) { + qtyRemDec = typeof event.qty_remaining === "string" ? parseDecimal(event.qty_remaining) : null; + } else if (event.qty_submitted !== undefined && event.qty_submitted !== null) { + const subDec = typeof event.qty_submitted === "string" ? parseDecimal(event.qty_submitted) : null; + const fillDec = event.qty_filled !== undefined && event.qty_filled !== null + ? parseDecimal(String(event.qty_filled)) + : { num: 0n, scale: 0 }; + const cancelDec = event.qty_canceled !== undefined && event.qty_canceled !== null + ? parseDecimal(String(event.qty_canceled)) + : { num: 0n, scale: 0 }; + if (subDec && fillDec && cancelDec) { + qtyRemDec = subDecimal(subDecimal(subDec, fillDec), cancelDec); + } + } + if (!qtyRemDec || qtyRemDec.num < 0n) { + return null; + } + if (qtyRemDec.num === 0n) { + const feeVal = event.estimated_fee_usd ?? event.reserved_fee_usd ?? null; + if (feeVal !== null && typeof feeVal === "string") { + const fDec = parseDecimal(feeVal); + if (fDec && fDec.num >= 0n) return formatUsdExact(fDec); + } + return "0"; + } + if (typeof event.limit_price !== "string") { + return null; + } + const limDec = parseDecimal(event.limit_price); + if (!limDec || limDec.num <= 0n) { + throw new OrdersFillsError("invalid_limit_price", 400); + } + const feeRaw = event.estimated_fee_usd ?? event.reserved_fee_usd ?? event.fee_usd ?? null; + if (feeRaw === null || feeRaw === undefined) { + return null; + } + if (typeof feeRaw !== "string") throw new OrdersFillsError("invalid_estimated_fee_usd", 400); + const feeDec = parseDecimal(feeRaw); + if (!feeDec || feeDec.num < 0n) throw new OrdersFillsError("invalid_estimated_fee_usd", 400); + const total = addDecimal(mulDecimal(qtyRemDec, limDec), feeDec); + return formatUsdExact(total); +} + +function validateLockRecord(raw) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new OrdersFillsError("invalid_order_unknown_lock_record", 400); + } + const identity = normalizeBrokerIdentity(raw); + const symbol = validateLockSymbol(raw.symbol); + const clientOrderId = validateSafeLockId(raw.client_order_id, "client_order_id"); + const brokerOrderId = validateSafeLockId(raw.broker_order_id ?? null, "broker_order_id", { allowNull: true }); + const lockedAt = validateLockTimestamp(raw.locked_at, "locked_at"); + if (raw.status !== "locked" || raw.allow_new_orders !== false || raw.query_before_retry_required !== true) { + throw new OrdersFillsError("invalid_order_unknown_lock_flags", 400); + } + if (raw.clear_condition !== "definitive_terminal_broker_evidence") { + throw new OrdersFillsError("invalid_order_unknown_clear_condition", 400); + } + const expectedQuery = buildOrderUnknownQueryTarget({ + ...identity, + client_order_id: clientOrderId, + broker_order_id: brokerOrderId, + }); + if (!raw.query_target || JSON.stringify(raw.query_target) !== JSON.stringify(expectedQuery)) { + throw new OrdersFillsError("invalid_order_unknown_query_target", 400); + } + let kPendUsd = null; + if (raw.k_pend_usd !== null && raw.k_pend_usd !== undefined) { + if (typeof raw.k_pend_usd !== "string") { + throw new OrdersFillsError("invalid_lock_k_pend_usd", 400); + } + const dec = parseDecimal(raw.k_pend_usd); + if (!dec || dec.num < 0n) throw new OrdersFillsError("invalid_lock_k_pend_usd", 400); + kPendUsd = formatUsdExact(dec); + } + return { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + symbol, + client_order_id: clientOrderId, + broker_order_id: brokerOrderId, + query_target: expectedQuery, + k_pend_usd: kPendUsd, + locked_at: lockedAt, + status: "locked", + allow_new_orders: false, + query_before_retry_required: true, + clear_condition: "definitive_terminal_broker_evidence", + }; +} + +function ensureLockStore(store) { + if (!store || typeof store !== "object" || store.schema_version !== ORDER_UNKNOWN_LOCK_STORE_SCHEMA) { + throw new OrdersFillsError("invalid_order_unknown_lock_store", 400); + } + if (!store.locks || typeof store.locks !== "object" || Array.isArray(store.locks)) { + throw new OrdersFillsError("invalid_order_unknown_lock_store", 400); + } + return store; +} + +/** + * Creates an empty or pre-seeded restart-persistent ORDER-UNKNOWN lock store. + */ +export function createOrderUnknownLockStore(initial = {}) { + const locks = {}; + const seenBrokerIds = new Set(); + const items = Array.isArray(initial?.locks) + ? initial.locks + : (initial?.locks && typeof initial.locks === "object" ? Object.values(initial.locks) : []); + for (const item of items) { + const clean = validateLockRecord(item); + const key = lockEntryKey(clean.broker, clean.environment, clean.account, clean.client_order_id); + if (clean.broker_order_id !== null) { + const brkKey = `${clean.broker}|${clean.environment}|${clean.account}|${clean.broker_order_id}`; + if (seenBrokerIds.has(brkKey) && locks[key]?.broker_order_id !== clean.broker_order_id) { + throw new OrdersFillsError("conflicting_broker_order_id_on_lock", 409); + } + seenBrokerIds.add(brkKey); + } + locks[key] = clean; + } + return { + schema_version: ORDER_UNKNOWN_LOCK_STORE_SCHEMA, + locks, + }; +} + +/** + * Serializes the lock store into deterministic, restart-persistent JSON without private locators. + */ +export function serializeOrderUnknownLockStore(store) { + ensureLockStore(store); + const locks = Object.entries(store.locks) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([, entry]) => structuredClone(validateLockRecord(entry))); + return { + schema_version: ORDER_UNKNOWN_LOCK_STORE_SCHEMA, + locks, + }; +} + +/** + * Restores and validates an ORDER-UNKNOWN lock store after simulated DO/store restart. + */ +export function deserializeOrderUnknownLockStore(raw) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new OrdersFillsError("invalid_serialized_lock_store", 400); + } + if (raw.schema_version !== ORDER_UNKNOWN_LOCK_STORE_SCHEMA || !Array.isArray(raw.locks)) { + throw new OrdersFillsError("invalid_serialized_lock_store", 400); + } + return createOrderUnknownLockStore({ locks: raw.locks }); +} + +/** + * Applies an order lifecycle observation to the lock store: + * - Enters/retains symbol lock on ORDER_UNKNOWN. + * - Never clears on non-terminal follow-ups (SUBMITTED / ACCEPTED / PARTIAL_FILL / PARTIAL_CANCEL). + * - Clears ONLY on definitive terminal broker evidence (FILLED / CANCELED / REJECTED). + */ +export function applyOrderUnknownObservation(store, event, options = {}) { + ensureLockStore(store); + if (!event || typeof event !== "object" || Array.isArray(event)) { + throw new OrdersFillsError("invalid_order_unknown_event", 400); + } + const identity = normalizeBrokerIdentity(event); + const symbol = validateLockSymbol(event.symbol); + if (!ORDER_STATE_SET.has(event.state)) { + throw new OrdersFillsError("invalid_order_state", 400); + } + if (event.side !== undefined && !ORDER_SIDE_SET.has(event.side)) { + throw new OrdersFillsError("invalid_order_side", 400); + } + const clientOrderId = validateSafeLockId(event.client_order_id, "client_order_id"); + const brokerOrderId = validateSafeLockId(event.broker_order_id ?? null, "broker_order_id", { allowNull: true }); + + const evalAtRaw = options?.evaluatedAt ?? options?.evaluated_at ?? null; + const evalAtNs = evalAtRaw !== null && evalAtRaw !== undefined ? parseInstantNs(evalAtRaw) : null; + if (evalAtRaw !== null && evalAtRaw !== undefined && evalAtNs === null) { + throw new OrdersFillsError("invalid_evaluated_at", 400); + } + const eventTsCandidates = [ + event.resolved_at, + event.canceled_at, + event.updated_at, + event.as_of, + event.executed_at, + event.submitted_at, + event.locked_at, + ]; + let maxEventNs = null; + for (const ts of eventTsCandidates) { + if (ts !== undefined && ts !== null) { + const parsedIso = validateLockTimestamp(ts, "event_timestamp"); + const ns = parseInstantNs(parsedIso); + if (maxEventNs === null || ns > maxEventNs) maxEventNs = ns; + } + } + + const nextLocks = structuredClone(store.locks); + let targetKey = lockEntryKey(identity.broker, identity.environment, identity.account, clientOrderId); + let existing = nextLocks[targetKey] ?? null; + + if (brokerOrderId !== null) { + for (const [key, entry] of Object.entries(nextLocks)) { + if ( + entry.broker === identity.broker + && entry.environment === identity.environment + && entry.account === identity.account + && entry.broker_order_id === brokerOrderId + && key !== targetKey + ) { + throw new OrdersFillsError("conflicting_broker_order_id_on_lock", 409); + } + } + } + + if (event.state === "ORDER_UNKNOWN") { + const lockedAtRaw = event.locked_at ?? event.submitted_at ?? event.as_of ?? event.updated_at ?? event.resolved_at; + const lockedAt = validateLockTimestamp(lockedAtRaw, "locked_at"); + const effectiveBrokerOrderId = brokerOrderId ?? existing?.broker_order_id ?? null; + if (existing && brokerOrderId !== null && existing.broker_order_id !== null && existing.broker_order_id !== brokerOrderId) { + throw new OrdersFillsError("conflicting_broker_order_id_on_lock", 409); + } + if (existing && existing.symbol !== symbol) { + throw new OrdersFillsError("conflicting_symbol_on_lock", 409); + } + const kPendUsd = computeOrderUnknownKPendUsd(event) ?? existing?.k_pend_usd ?? null; + nextLocks[targetKey] = { + broker: identity.broker, + environment: identity.environment, + account: identity.account, + symbol, + client_order_id: clientOrderId, + broker_order_id: effectiveBrokerOrderId, + query_target: buildOrderUnknownQueryTarget({ + ...identity, + client_order_id: clientOrderId, + broker_order_id: effectiveBrokerOrderId, + }), + k_pend_usd: kPendUsd, + locked_at: existing?.locked_at ?? lockedAt, + status: "locked", + allow_new_orders: false, + query_before_retry_required: true, + clear_condition: "definitive_terminal_broker_evidence", + }; + return { schema_version: ORDER_UNKNOWN_LOCK_STORE_SCHEMA, locks: nextLocks }; + } + + if (!existing) { + return { schema_version: ORDER_UNKNOWN_LOCK_STORE_SCHEMA, locks: nextLocks }; + } + + if (existing.symbol !== symbol) { + throw new OrdersFillsError("order_unknown_symbol_mismatch", 409); + } + if (brokerOrderId !== null && existing.broker_order_id !== null && existing.broker_order_id !== brokerOrderId) { + throw new OrdersFillsError("order_unknown_broker_id_mismatch", 409); + } + + if (TERMINAL_STATE_SET.has(event.state)) { + if (maxEventNs === null || (evalAtNs !== null && maxEventNs > evalAtNs)) { + return { schema_version: ORDER_UNKNOWN_LOCK_STORE_SCHEMA, locks: nextLocks }; + } + delete nextLocks[targetKey]; + return { schema_version: ORDER_UNKNOWN_LOCK_STORE_SCHEMA, locks: nextLocks }; + } + + // Non-terminal follow-up (SUBMITTED / ACCEPTED / PARTIAL_FILL / PARTIAL_CANCEL): + // retain symbol lock and K_pend, optionally linking broker_order_id if revealed. + const effectiveBrokerOrderId = brokerOrderId ?? existing.broker_order_id ?? null; + nextLocks[targetKey] = { + ...existing, + broker_order_id: effectiveBrokerOrderId, + query_target: buildOrderUnknownQueryTarget({ + ...identity, + client_order_id: existing.client_order_id, + broker_order_id: effectiveBrokerOrderId, + }), + }; + return { schema_version: ORDER_UNKNOWN_LOCK_STORE_SCHEMA, locks: nextLocks }; +} + +export function listActiveOrderUnknownLocks(store, identityFilter = null) { + ensureLockStore(store); + const norm = identityFilter ? normalizeBrokerIdentity(identityFilter) : null; + return Object.values(store.locks) + .filter((entry) => ( + !norm + || (entry.broker === norm.broker && entry.environment === norm.environment && entry.account === norm.account) + )) + .map((entry) => structuredClone(entry)) + .sort((a, b) => ( + a.broker.localeCompare(b.broker) + || a.environment.localeCompare(b.environment) + || a.account.localeCompare(b.account) + || a.symbol.localeCompare(b.symbol) + || a.client_order_id.localeCompare(b.client_order_id) + )); +} + +export function lockedSymbolsForAccount(store, identity) { + const locks = listActiveOrderUnknownLocks(store, identity); + return [...new Set(locks.map((l) => l.symbol))].sort(); +} + +/** + * Checks whether new orders on (broker, environment, account, symbol) are permitted under O4/Q5-2. + */ +export function checkSymbolOrderAllowed(store, params = {}) { + ensureLockStore(store); + const identity = normalizeBrokerIdentity(params); + const symbol = validateLockSymbol(params.symbol); + const matches = listActiveOrderUnknownLocks(store, identity).filter((l) => l.symbol === symbol); + if (matches.length > 0) { + const first = matches[0]; + return { + allowed: false, + reason: "order_unknown_lock", + lock: first, + query_target: first.query_target, + }; + } + return { + allowed: true, + reason: null, + lock: null, + query_target: null, + }; +} diff --git a/web/strategy-switch-console/application/sizing_unit/deployable_capital.js b/web/strategy-switch-console/application/sizing_unit/deployable_capital.js new file mode 100644 index 00000000..0ad334e0 --- /dev/null +++ b/web/strategy-switch-console/application/sizing_unit/deployable_capital.js @@ -0,0 +1,1868 @@ +/** + * C-SA-Q21: Exact-decimal deployable capital (C_inv, C_avail, R_cash, K_pend), + * whole-share ideal target, fee-and-collar-aware buyable share allocation, + * unblocked reductions, ORDER-UNKNOWN buy blocks, B_{min,tier}, and rho_order. + * + * Pure leaf module under application/sizing_unit/: + * - Imports only inward from ./nav.js and ../naming_canonical/helpers.js. + * - Never imports Worker/DO modules, runtime_support.js, storage, or network. + * - Zero IEEE floats for money, shares, fees, weights, or capital equations. + */ + +import { isRawAccountIdentifier, isUnsafePrivateLocator } from "../naming_canonical/helpers.js"; +import { evaluateFreshness } from "./freshness.js"; +import { + parseInstantNs, + ratAdd, + ratCmp, + ratDiv, + ratFromText, + ratMul, + ratSub, + ratToDecimalText, + stripPrivateLocators, + toUtcIsoFromNs, +} from "./nav.js"; + +export const DEPLOYABLE_CAPITAL_SCHEMA = "qsl.deployable_capital_sizing.v1"; + +const ZERO_RAT = { n: 0n, d: 1n }; +const ONE_RAT = { n: 1n, d: 1n }; +const TEN_RAT = { n: 10n, d: 1n }; +const BPS_DENOM = { n: 10000n, d: 1n }; + +const BROKER_SET = new Set(["schwab", "firstrade", "ibkr", "longbridge", "binance"]); +const ENV_SET = new Set(["live", "paper"]); +const FEE_PROVENANCE_SET = new Set(["synthetic_fixture", "research_prereg_amended", "venue_observed"]); +const SOURCE_CLASS_SET = new Set([ + "synthetic", + "historical_reconstruction", + "decision_time_market", + "operator_declared", + "authorized_operational", + "paper_broker", + "authorized_live_broker", +]); +const SYMBOL_RE = /^[A-Z0-9][A-Z0-9./_-]{0,63}$/; +const INTEGER_TEXT_RE = /^(?:0|[1-9][0-9]*)$/; +const SAFE_ACCOUNT_TUPLE_RE = /^(schwab|firstrade|ibkr|longbridge|binance):(live|paper):([a-z0-9][a-z0-9_-]{0,31})$/; +const SAFE_OPAQUE_ACCOUNT_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/; + +function exactTerminatingScale(r, minScale = 0, fallbackMaxScale = 12) { + let d = r.d; + let pow2 = 0; + let pow5 = 0; + while (d % 2n === 0n) { d /= 2n; pow2++; } + while (d % 5n === 0n) { d /= 5n; pow5++; } + return d === 1n ? Math.max(pow2, pow5, minScale) : Math.max(minScale, fallbackMaxScale); +} + +function formatUsdRat(r) { + if (r.n === 0n) return "0"; + return ratToDecimalText(r, { minScale: 2, maxScale: exactTerminatingScale(r, 2) }); +} + +function formatRatioRat(r) { + if (r.n === 0n) return "0"; + return ratToDecimalText(r, { minScale: 0, maxScale: 12 }); +} + +function ratAbs(r) { + return r.n < 0n ? { n: -r.n, d: r.d } : r; +} + +function ratMaxZero(r) { + return r.n > 0n ? r : ZERO_RAT; +} + +function ratFloorBigInt(r) { + if (r.n < 0n) { + throw new RangeError("negative_floor_unsupported"); + } + return r.n / r.d; +} + +function parseNonNegativeRat(val) { + if (typeof val !== "string") return null; + const r = ratFromText(val); + if (!r || r.n < 0n) return null; + return r; +} + +function parsePositiveRat(val) { + if (typeof val !== "string") return null; + const r = ratFromText(val); + if (!r || r.n <= 0n) return null; + return r; +} + +function parseNonNegativeIntBigInt(val) { + if (typeof val !== "string" || !INTEGER_TEXT_RE.test(val)) return null; + return BigInt(val); +} + +function parseAccountId(rawAccount, broker, environment) { + if (rawAccount === null || rawAccount === undefined) return { ok: true, value: null }; + if (typeof rawAccount !== "string" || rawAccount.length === 0 || rawAccount.length > 64) { + return { ok: false, reason: "invalid_account_id" }; + } + if (isUnsafePrivateLocator(rawAccount)) { + return { ok: false, reason: "unsafe_private_locator" }; + } + if (isRawAccountIdentifier(rawAccount)) { + return { ok: false, reason: "raw_account_id_prohibited" }; + } + let slot; + if (rawAccount.includes(":")) { + const match = SAFE_ACCOUNT_TUPLE_RE.exec(rawAccount); + if (!match) return { ok: false, reason: "invalid_account_id" }; + if (broker && match[1] !== broker) return { ok: false, reason: "account_broker_mismatch" }; + if (environment && match[2] !== environment) return { ok: false, reason: "account_environment_mismatch" }; + if (isRawAccountIdentifier(match[3])) return { ok: false, reason: "raw_account_id_prohibited" }; + slot = match[3]; + const resolvedBroker = broker ?? match[1]; + const resolvedEnv = environment ?? match[2]; + return { ok: true, value: `${resolvedBroker}:${resolvedEnv}:${slot}` }; + } + if (!SAFE_OPAQUE_ACCOUNT_RE.test(rawAccount)) { + return { ok: false, reason: "invalid_account_id" }; + } + if (broker && environment) { + return { ok: true, value: `${broker}:${environment}:${rawAccount}` }; + } + return { ok: true, value: rawAccount }; +} + +function validateSafeSymbol(sym) { + return ( + typeof sym === "string" + && SYMBOL_RE.test(sym) + && !isRawAccountIdentifier(sym) + && !isUnsafePrivateLocator(sym) + ); +} + +const SAFE_MACHINE_REASON_RE = /^[a-z][a-z0-9_]{0,127}$/; +const SENSITIVE_REASON_WORD_RE = /(?:token|secret|password|sig|auth)/i; +const SAFE_EVIDENCE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; +const SHA256_EVIDENCE_RE = /^sha256:[a-f0-9]{64}$/; + +function sanitizePublicReason(value, fallback = "unavailable") { + if (typeof value !== "string" || value.length === 0 || value.length > 128) return fallback; + if (isRawAccountIdentifier(value) || isUnsafePrivateLocator(value)) return fallback; + if (!SAFE_MACHINE_REASON_RE.test(value) || SENSITIVE_REASON_WORD_RE.test(value)) return fallback; + return value; +} + +function isSafeEvidenceRef(value) { + if (typeof value !== "string" || value.length === 0 || value.length > 128) return false; + if (isUnsafePrivateLocator(value)) return false; + if (SHA256_EVIDENCE_RE.test(value)) return true; + if (isRawAccountIdentifier(value)) return false; + return SAFE_EVIDENCE_ID_RE.test(value); +} + +function resolveEvaluatedAt(input, options) { + const candidate = options?.evaluated_at ?? input?.evaluated_at ?? input?.sizing_unit_nav?.evaluated_at ?? input?.orders_fills?.evaluated_at; + if (typeof candidate !== "string") return null; + const ns = parseInstantNs(candidate); + return ns === null ? null : toUtcIsoFromNs(ns); +} + +function validateNavAtSizingBoundary(nav, { evaluatedAt, sizingEvalNs, options, raw }) { + const topObserved = nav.observed_at ?? null; + const freshObserved = nav.freshness?.observed_at ?? null; + if (topObserved !== null && freshObserved !== null && parseInstantNs(topObserved) !== parseInstantNs(freshObserved)) { + return { ok: false, reason: "nav_timestamp_mismatch" }; + } + const navObservedRaw = topObserved ?? freshObserved ?? nav.as_of ?? nav.snapshot_at ?? null; + const navObservedNs = typeof navObservedRaw === "string" ? parseInstantNs(navObservedRaw) : null; + if (navObservedNs === null) { + return { ok: false, reason: "nav_missing_or_invalid_timestamp" }; + } + + const topEvaluated = nav.evaluated_at ?? null; + const freshEvaluated = nav.freshness?.evaluated_at ?? null; + if (topEvaluated !== null && freshEvaluated !== null && parseInstantNs(topEvaluated) !== parseInstantNs(freshEvaluated)) { + return { ok: false, reason: "nav_timestamp_mismatch" }; + } + const navEvaluatedRaw = topEvaluated ?? freshEvaluated ?? null; + const navEvaluatedNs = typeof navEvaluatedRaw === "string" ? parseInstantNs(navEvaluatedRaw) : null; + if (navEvaluatedNs === null) { + return { ok: false, reason: "nav_missing_or_invalid_timestamp" }; + } + + const topFetched = nav.fetched_at ?? null; + const freshFetched = nav.freshness?.fetched_at ?? null; + if (topFetched !== null && freshFetched !== null && parseInstantNs(topFetched) !== parseInstantNs(freshFetched)) { + return { ok: false, reason: "nav_timestamp_mismatch" }; + } + const navFetchedRaw = topFetched ?? freshFetched ?? null; + let navFetchedNs = null; + if (navFetchedRaw !== null) { + navFetchedNs = typeof navFetchedRaw === "string" ? parseInstantNs(navFetchedRaw) : null; + if (navFetchedNs === null) { + return { ok: false, reason: "nav_missing_or_invalid_timestamp" }; + } + } + + if (sizingEvalNs !== null) { + if (navObservedNs > sizingEvalNs) { + return { ok: false, reason: "nav_observed_after_sizing_boundary" }; + } + if (navFetchedNs !== null && navFetchedNs > sizingEvalNs) { + return { ok: false, reason: "nav_fetched_after_sizing_boundary" }; + } + if (navEvaluatedNs > sizingEvalNs) { + return { ok: false, reason: "nav_evaluated_after_sizing_boundary" }; + } + } + + if (nav.coverage_window?.end_utc !== undefined && nav.coverage_window?.end_utc !== null) { + const covEndNs = typeof nav.coverage_window.end_utc === "string" + ? parseInstantNs(nav.coverage_window.end_utc) + : null; + if (covEndNs === null) { + return { ok: false, reason: "nav_missing_or_invalid_timestamp" }; + } + if (sizingEvalNs !== null && covEndNs > sizingEvalNs) { + return { ok: false, reason: "nav_observed_after_sizing_boundary" }; + } + } + + if (Array.isArray(nav.observations)) { + for (const obs of nav.observations) { + if (obs && typeof obs === "object") { + if (obs.observed_at !== undefined && obs.observed_at !== null) { + const obsNs = typeof obs.observed_at === "string" ? parseInstantNs(obs.observed_at) : null; + if (obsNs === null || (sizingEvalNs !== null && obsNs > sizingEvalNs)) { + return { ok: false, reason: obsNs === null ? "nav_missing_or_invalid_timestamp" : "nav_observed_after_sizing_boundary" }; + } + } + if (obs.fetched_at !== undefined && obs.fetched_at !== null) { + const obsFetchedNs = typeof obs.fetched_at === "string" ? parseInstantNs(obs.fetched_at) : null; + if (obsFetchedNs === null || (sizingEvalNs !== null && obsFetchedNs > sizingEvalNs)) { + return { ok: false, reason: obsFetchedNs === null ? "nav_missing_or_invalid_timestamp" : "nav_fetched_after_sizing_boundary" }; + } + } + } + } + } + + if (typeof nav.freshness?.age_sessions === "number" && nav.freshness.age_sessions !== 0) { + return { ok: false, reason: "snapshot_stale" }; + } + + const maxAgeRaw = options?.max_nav_age_seconds ?? raw?.max_nav_age_seconds; + if (maxAgeRaw !== undefined && maxAgeRaw !== null) { + const maxAgeRat = typeof maxAgeRaw === "number" + ? (Number.isFinite(maxAgeRaw) && maxAgeRaw >= 0 ? ratFromText(String(maxAgeRaw)) : null) + : ratFromText(maxAgeRaw); + if (!maxAgeRat || maxAgeRat.n < 0n || sizingEvalNs === null) { + return { ok: false, reason: "invalid_max_nav_age_seconds" }; + } + const ageNsRat = { n: sizingEvalNs - navObservedNs, d: 1_000_000_000n }; + if (ratCmp(ageNsRat, maxAgeRat) > 0) { + return { ok: false, reason: "sizing_unit_nav_max_age_exceeded" }; + } + } + + if (options?.calendarProvider || (sizingEvalNs !== null && sizingEvalNs !== navEvaluatedNs)) { + const freshCheck = evaluateFreshness( + { + observed_at: toUtcIsoFromNs(navObservedNs), + fetched_at: toUtcIsoFromNs(navFetchedNs ?? navObservedNs), + evaluated_at: evaluatedAt, + }, + options ?? {}, + ); + if (freshCheck.data_status !== "fresh" || freshCheck.sizing_eligible !== true) { + return { ok: false, reason: sanitizePublicReason(freshCheck.reason, "sizing_unit_nav_stale") }; + } + } + + return { ok: true }; +} + +function normalizeFeeSchedule(rawSchedule) { + if (!rawSchedule || typeof rawSchedule !== "object" || Array.isArray(rawSchedule)) { + return { + ok: false, + reason: "oi_cost_3_fee_schedule_unavailable", + view: { + status: "unavailable", + provenance: null, + c_min_usd: null, + c_per_share_usd: null, + c_reg: null, + b_exec_usd: null, + oi_cost_3_resolved: false, + oi_cost_4_resolved: false, + }, + }; + } + const provenance = FEE_PROVENANCE_SET.has(rawSchedule.provenance) ? rawSchedule.provenance : null; + const cMinRat = parseNonNegativeRat(rawSchedule.c_min_usd); + const cPerShareRat = parseNonNegativeRat(rawSchedule.c_per_share_usd); + + let cRegSpec = null; + let cRegView = null; + if (typeof rawSchedule.c_reg === "string") { + const r = parseNonNegativeRat(rawSchedule.c_reg); + if (r) { + cRegSpec = { fixed: r, perShare: ZERO_RAT, notionalRate: ZERO_RAT }; + cRegView = formatUsdRat(r); + } + } else if (rawSchedule.c_reg && typeof rawSchedule.c_reg === "object" && !Array.isArray(rawSchedule.c_reg)) { + const fixed = parseNonNegativeRat(rawSchedule.c_reg.fixed_usd); + const perShare = parseNonNegativeRat(rawSchedule.c_reg.per_share_usd); + const notionalRate = parseNonNegativeRat(rawSchedule.c_reg.notional_rate); + if (fixed && perShare && notionalRate) { + cRegSpec = { fixed, perShare, notionalRate }; + cRegView = { + fixed_usd: formatUsdRat(fixed), + per_share_usd: formatUsdRat(perShare), + notional_rate: formatRatioRat(notionalRate), + }; + } + } + + let bExecRat = null; + let bExecValid = false; + if (rawSchedule.b_exec_usd !== undefined && rawSchedule.b_exec_usd !== null) { + const parsedBExec = parseNonNegativeRat(rawSchedule.b_exec_usd); + if (parsedBExec) { + bExecRat = parsedBExec; + bExecValid = true; + } + } + + let defaultCollarRat = null; + if (rawSchedule.default_collar_bps !== undefined && rawSchedule.default_collar_bps !== null) { + defaultCollarRat = parseNonNegativeRat(rawSchedule.default_collar_bps); + if (!defaultCollarRat) { + return { + ok: false, + reason: "oi_cost_4_price_collar_unavailable", + view: { + status: "unavailable", + provenance, + c_min_usd: cMinRat ? formatUsdRat(cMinRat) : null, + c_per_share_usd: cPerShareRat ? formatUsdRat(cPerShareRat) : null, + c_reg: cRegView, + b_exec_usd: bExecValid ? formatUsdRat(bExecRat) : null, + oi_cost_3_resolved: Boolean(provenance && cMinRat && cPerShareRat && cRegSpec && bExecValid), + oi_cost_4_resolved: false, + }, + }; + } + } + + if (!provenance || !cMinRat || !cPerShareRat || !cRegSpec || !bExecValid) { + return { + ok: false, + reason: "oi_cost_3_fee_schedule_unavailable", + view: { + status: "unavailable", + provenance: null, + c_min_usd: null, + c_per_share_usd: null, + c_reg: null, + b_exec_usd: null, + oi_cost_3_resolved: false, + oi_cost_4_resolved: false, + }, + }; + } + + return { + ok: true, + provenance, + cMinRat, + cPerShareRat, + cRegSpec, + bExecRat, + defaultCollarRat, + view: { + status: "available", + provenance, + c_min_usd: formatUsdRat(cMinRat), + c_per_share_usd: formatUsdRat(cPerShareRat), + c_reg: cRegView, + b_exec_usd: formatUsdRat(bExecRat), + oi_cost_3_resolved: true, + oi_cost_4_resolved: true, + }, + }; +} + +function computeOrderCostForQty(qtyBigInt, priceLimRat, feeModel) { + if (qtyBigInt <= 0n) { + return { + worstCaseNotional: ZERO_RAT, + commission: ZERO_RAT, + bExec: ZERO_RAT, + totalCost: ZERO_RAT, + }; + } + const qRat = { n: qtyBigInt, d: 1n }; + const worstCaseNotional = ratMul(qRat, priceLimRat); + const perShareTotal = ratMul(feeModel.cPerShareRat, qRat); + const ticketBase = ratCmp(feeModel.cMinRat, perShareTotal) >= 0 ? feeModel.cMinRat : perShareTotal; + const regFee = ratAdd( + feeModel.cRegSpec.fixed, + ratAdd( + ratMul(feeModel.cRegSpec.perShare, qRat), + ratMul(feeModel.cRegSpec.notionalRate, worstCaseNotional), + ), + ); + const commission = ratAdd(ticketBase, regFee); + const bExec = feeModel.bExecRat; + const totalCost = ratAdd(worstCaseNotional, ratAdd(commission, bExec)); + return { worstCaseNotional, commission, bExec, totalCost }; +} + +function maxAffordableShares(maxQtyBigInt, budgetRat, priceLimRat, feeModel) { + if (maxQtyBigInt <= 0n || budgetRat.n <= 0n) return 0n; + if (ratCmp(computeOrderCostForQty(1n, priceLimRat, feeModel).totalCost, budgetRat) > 0) { + return 0n; + } + let lo = 1n; + let hi = maxQtyBigInt; + while (lo < hi) { + const mid = (lo + hi + 1n) / 2n; + const cost = computeOrderCostForQty(mid, priceLimRat, feeModel).totalCost; + if (ratCmp(cost, budgetRat) <= 0) { + lo = mid; + } else { + hi = mid - 1n; + } + } + return lo; +} + +/** + * Evaluates B_{min,tier}: C_{fixed,ann}(W) < 0.10 * DeltaG_{ex,ann}^$(W). + * Keeps unset expected excess growth explicitly unavailable rather than inventing growth. + */ +export function evaluateWorkableBankrollBminTier(params = {}) { + const bankrollW = params.bankroll_w_usd !== undefined && params.bankroll_w_usd !== null + ? parseNonNegativeRat(params.bankroll_w_usd) + : null; + if (params.bankroll_w_usd !== undefined && params.bankroll_w_usd !== null && !bankrollW) { + return { + status: "unavailable", + workable: null, + bankroll_w_usd: null, + c_fixed_ann_usd: null, + expected_excess_growth_ann_usd: null, + threshold_ratio: "0.1", + friction_ratio: null, + reason: "invalid_bankroll_w_usd", + }; + } + + let cFixedCostFailureReason = null; + let cFixedRat = null; + if (params.c_fixed_ann_usd !== undefined && params.c_fixed_ann_usd !== null) { + cFixedRat = parseNonNegativeRat(params.c_fixed_ann_usd); + if (!cFixedRat) { + return { + status: "unavailable", + workable: null, + bankroll_w_usd: bankrollW ? formatUsdRat(bankrollW) : null, + c_fixed_ann_usd: null, + expected_excess_growth_ann_usd: null, + threshold_ratio: "0.1", + friction_ratio: null, + reason: "invalid_c_fixed_ann_usd", + }; + } + } else if ( + Number.isInteger(params.annual_ticket_count) + && params.annual_ticket_count >= 0 + && params.fee_schedule_resolved + && params.fee_schedule_resolved.ok + ) { + const rawRounding = params.annual_rounding_friction_usd !== undefined + ? params.annual_rounding_friction_usd + : params.rounding_friction_ann_usd; + const rawPassthrough = params.annual_passthrough_usd !== undefined + ? params.annual_passthrough_usd + : params.fixed_passthrough_ann_usd; + if (rawRounding === undefined || rawRounding === null || rawPassthrough === undefined || rawPassthrough === null) { + cFixedCostFailureReason = "incomplete_fixed_annual_cost_inputs"; + } else { + const roundingAnn = parseNonNegativeRat(rawRounding); + const passthroughAnn = parseNonNegativeRat(rawPassthrough); + if (!roundingAnn || !passthroughAnn) { + cFixedCostFailureReason = "invalid_fixed_annual_cost_inputs"; + } else { + const ticketFee = ratAdd(params.fee_schedule_resolved.cMinRat, params.fee_schedule_resolved.cRegSpec.fixed); + const ticketsTotal = ratMul({ n: BigInt(params.annual_ticket_count), d: 1n }, ticketFee); + cFixedRat = ratAdd(ticketsTotal, ratAdd(roundingAnn, passthroughAnn)); + } + } + } + + if (params.expected_excess_growth_ann_usd === null || params.expected_excess_growth_ann_usd === undefined) { + return { + status: "unavailable", + workable: null, + bankroll_w_usd: bankrollW ? formatUsdRat(bankrollW) : null, + c_fixed_ann_usd: cFixedRat ? formatUsdRat(cFixedRat) : null, + expected_excess_growth_ann_usd: null, + threshold_ratio: "0.1", + friction_ratio: null, + reason: cFixedCostFailureReason ?? "expected_excess_growth_unset", + }; + } + + if (typeof params.expected_excess_growth_ann_usd !== "string") { + return { + status: "unavailable", + workable: null, + bankroll_w_usd: bankrollW ? formatUsdRat(bankrollW) : null, + c_fixed_ann_usd: cFixedRat ? formatUsdRat(cFixedRat) : null, + expected_excess_growth_ann_usd: null, + threshold_ratio: "0.1", + friction_ratio: null, + reason: "invalid_expected_excess_growth", + }; + } + const deltaGRat = ratFromText(params.expected_excess_growth_ann_usd); + if (!deltaGRat) { + return { + status: "unavailable", + workable: null, + bankroll_w_usd: bankrollW ? formatUsdRat(bankrollW) : null, + c_fixed_ann_usd: cFixedRat ? formatUsdRat(cFixedRat) : null, + expected_excess_growth_ann_usd: null, + threshold_ratio: "0.1", + friction_ratio: null, + reason: "invalid_expected_excess_growth", + }; + } + + if (!cFixedRat) { + return { + status: "unavailable", + workable: null, + bankroll_w_usd: bankrollW ? formatUsdRat(bankrollW) : null, + c_fixed_ann_usd: null, + expected_excess_growth_ann_usd: formatUsdRat(deltaGRat), + threshold_ratio: "0.1", + friction_ratio: null, + reason: cFixedCostFailureReason ?? "c_fixed_ann_unset", + }; + } + + if (deltaGRat.n <= 0n) { + return { + status: "available", + workable: false, + bankroll_w_usd: bankrollW ? formatUsdRat(bankrollW) : null, + c_fixed_ann_usd: formatUsdRat(cFixedRat), + expected_excess_growth_ann_usd: formatUsdRat(deltaGRat), + threshold_ratio: "0.1", + friction_ratio: null, + reason: "non_positive_expected_excess_growth", + }; + } + + const ratioRat = ratDiv(cFixedRat, deltaGRat); + const workable = ratCmp(ratMul(cFixedRat, TEN_RAT), deltaGRat) < 0; + return { + status: "available", + workable, + bankroll_w_usd: bankrollW ? formatUsdRat(bankrollW) : null, + c_fixed_ann_usd: formatUsdRat(cFixedRat), + expected_excess_growth_ann_usd: formatUsdRat(deltaGRat), + threshold_ratio: "0.1", + friction_ratio: formatRatioRat(ratioRat), + reason: null, + }; +} + +function buildUnavailableResult({ + reason, + accountId = null, + broker = null, + environment = null, + evaluatedAt = "1970-01-01T00:00:00.000Z", + feeScheduleView = null, + bMinTier = null, + orderUnknownSymbols = [], + origin = "synthetic", + sourceClass = "synthetic", + evidenceRef = "sa2:q21:unavailable", +}) { + const safeReason = sanitizePublicReason(reason, "unavailable"); + const safeEvidenceRef = isSafeEvidenceRef(evidenceRef) ? evidenceRef : "sa2:q21:unavailable"; + return stripPrivateLocators({ + schema_version: DEPLOYABLE_CAPITAL_SCHEMA, + status: "unavailable", + reason: safeReason, + account_id: accountId, + broker, + environment, + currency: "USD", + currency_coercion: "prohibited", + fx_inferred: false, + margin_enabled: false, + h_usd: "0", + kelly_applied: false, + live_trading_enabled: false, + stop_loss_return_enabled: false, + fractional_shares: "prohibited", + evaluated_at: evaluatedAt, + capital: { + equity_usd: null, + c_inv_usd: null, + cash_settled_usd: null, + proceeds_eligible_usd: null, + r_cash_usd: null, + k_pend_usd: null, + k_pend_release_allowed: false, + raw_deployable_cash_usd: null, + c_avail_usd: null, + total_buy_commit_usd: null, + remaining_deployable_cash_usd: null, + }, + fee_schedule: feeScheduleView ?? { + status: "unavailable", + provenance: null, + c_min_usd: null, + c_per_share_usd: null, + c_reg: null, + b_exec_usd: null, + oi_cost_3_resolved: false, + oi_cost_4_resolved: false, + }, + order_unknown_symbols: orderUnknownSymbols, + orders: [], + b_min_tier: bMinTier ?? { + status: "unavailable", + workable: null, + bankroll_w_usd: null, + c_fixed_ann_usd: null, + expected_excess_growth_ann_usd: null, + threshold_ratio: "0.1", + friction_ratio: null, + reason: safeReason, + }, + origin, + source_class: sourceClass, + evidence_ref: safeEvidenceRef, + }); +} + +/** + * Evaluates C-SA-Q21 exact-decimal deployable capital, whole-share targets, fee-and-collar + * buy allocation, unblocked reductions, ORDER-UNKNOWN buy blocks, B_min,tier, and rho_order. + */ +export function evaluateDeployableCapitalSizing(input = {}, options = {}) { + const raw = input && typeof input === "object" && !Array.isArray(input) ? input : {}; + const nav = raw.sizing_unit_nav ?? null; + const ordersFills = raw.orders_fills ?? null; + + const evaluatedAt = resolveEvaluatedAt(raw, options) ?? "1970-01-01T00:00:00.000Z"; + const origin = raw.origin === "production" ? "production" : "synthetic"; + const sourceClass = SOURCE_CLASS_SET.has(raw.source_class) + ? raw.source_class + : (SOURCE_CLASS_SET.has(nav?.source_class) ? nav.source_class : "synthetic"); + const feeParsed = normalizeFeeSchedule(raw.fee_schedule); + + const rawEvidenceUnsafe = raw.evidence_ref !== undefined && raw.evidence_ref !== null && !isSafeEvidenceRef(raw.evidence_ref); + const evidenceRefCandidate = raw.evidence_ref ?? nav?.evidence_ref ?? ordersFills?.evidence_ref ?? "sa2:q21:eval"; + const evidenceRef = isSafeEvidenceRef(evidenceRefCandidate) ? evidenceRefCandidate : "sa2:q21:eval"; + + const rawBrokerSpec = raw.broker ?? null; + const navBrokerSpec = nav?.platform ?? null; + const ordersBrokerSpec = ordersFills?.broker ?? null; + const effectiveBrokerSpec = rawBrokerSpec ?? navBrokerSpec ?? ordersBrokerSpec ?? null; + const broker = typeof effectiveBrokerSpec === "string" && BROKER_SET.has(effectiveBrokerSpec) ? effectiveBrokerSpec : null; + + const rawEnvSpec = raw.environment ?? raw.broker_environment ?? null; + const navEnvSpec = nav?.broker_environment ?? null; + const ordersEnvSpec = ordersFills?.environment ?? null; + const effectiveEnvSpec = rawEnvSpec ?? navEnvSpec ?? ordersEnvSpec ?? null; + const environment = typeof effectiveEnvSpec === "string" && ENV_SET.has(effectiveEnvSpec) ? effectiveEnvSpec : null; + + const rawAccountSpec = raw.account_id ?? null; + const navAccountSpec = nav?.account_id ?? null; + const ordersAccountSpec = ordersFills?.account ?? null; + const effectiveAccountRaw = rawAccountSpec ?? navAccountSpec ?? ordersAccountSpec ?? null; + const parsedAccount = parseAccountId(effectiveAccountRaw, broker, environment); + const accountId = parsedAccount.ok ? parsedAccount.value : null; + + if (rawEvidenceUnsafe) { + return buildUnavailableResult({ + reason: "unsafe_evidence_ref", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols: [], + origin, + sourceClass, + evidenceRef: "sa2:q21:unavailable", + }); + } + + const unknownSet = new Set(); + for (const list of [raw.order_unknown_symbols, ordersFills?.order_unknown_symbols]) { + if (list !== undefined && list !== null && !Array.isArray(list)) { + return buildUnavailableResult({ + reason: "invalid_order_unknown_symbols", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols: [], + origin, + sourceClass, + evidenceRef, + }); + } + if (Array.isArray(list)) { + for (const sym of list) { + if (!validateSafeSymbol(sym)) { + return buildUnavailableResult({ + reason: "invalid_order_unknown_symbol", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols: [], + origin, + sourceClass, + evidenceRef, + }); + } + unknownSet.add(sym); + } + } + } + const orderUnknownSymbols = [...unknownSet].sort(); + + if (!resolveEvaluatedAt(raw, options)) { + return buildUnavailableResult({ + reason: "missing_or_invalid_evaluated_at", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (!parsedAccount.ok) { + return buildUnavailableResult({ + reason: parsedAccount.reason, + accountId: null, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (effectiveBrokerSpec !== null && broker === null) { + return buildUnavailableResult({ + reason: "invalid_broker", + accountId, + broker: null, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (effectiveEnvSpec !== null && environment === null) { + return buildUnavailableResult({ + reason: "invalid_environment", + accountId, + broker, + environment: null, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + // Pairwise (broker, environment, account) consistency across raw, sizing_unit_nav, and orders_fills. + const identityMismatchChecks = [ + [rawBrokerSpec && navBrokerSpec && rawBrokerSpec !== navBrokerSpec, "raw_nav_broker_mismatch"], + [rawBrokerSpec && ordersBrokerSpec && rawBrokerSpec !== ordersBrokerSpec, "raw_orders_broker_mismatch"], + [navBrokerSpec && ordersBrokerSpec && navBrokerSpec !== ordersBrokerSpec, "nav_orders_broker_mismatch"], + [rawEnvSpec && navEnvSpec && rawEnvSpec !== navEnvSpec, "raw_nav_environment_mismatch"], + [rawEnvSpec && ordersEnvSpec && rawEnvSpec !== ordersEnvSpec, "raw_orders_environment_mismatch"], + [navEnvSpec && ordersEnvSpec && navEnvSpec !== ordersEnvSpec, "nav_orders_environment_mismatch"], + ]; + for (const [cond, mismatchReason] of identityMismatchChecks) { + if (cond) { + return buildUnavailableResult({ + reason: mismatchReason, + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } + + const parsedNavAccount = navAccountSpec ? parseAccountId(navAccountSpec, navBrokerSpec ?? broker, navEnvSpec ?? environment) : { ok: true, value: null }; + const parsedOrdersAccount = ordersAccountSpec ? parseAccountId(ordersAccountSpec, ordersBrokerSpec ?? broker, ordersEnvSpec ?? environment) : { ok: true, value: null }; + if (!parsedNavAccount.ok || !parsedOrdersAccount.ok) { + return buildUnavailableResult({ + reason: !parsedNavAccount.ok ? parsedNavAccount.reason : parsedOrdersAccount.reason, + accountId: null, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (accountId && parsedNavAccount.value && accountId !== parsedNavAccount.value) { + return buildUnavailableResult({ + reason: "raw_nav_account_mismatch", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (accountId && parsedOrdersAccount.value && accountId !== parsedOrdersAccount.value) { + return buildUnavailableResult({ + reason: "raw_orders_account_mismatch", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (parsedNavAccount.value && parsedOrdersAccount.value && parsedNavAccount.value !== parsedOrdersAccount.value) { + return buildUnavailableResult({ + reason: "nav_orders_account_mismatch", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + const sizingEvalNs = parseInstantNs(evaluatedAt); + if (ordersFills) { + const ordersEvalNs = typeof ordersFills.evaluated_at === "string" + ? parseInstantNs(ordersFills.evaluated_at) + : null; + if (ordersEvalNs === null) { + return buildUnavailableResult({ + reason: "orders_fills_missing_or_invalid_evaluated_at", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (sizingEvalNs !== null && ordersEvalNs > sizingEvalNs) { + return buildUnavailableResult({ + reason: "orders_fills_evaluated_after_sizing_boundary", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (ordersFills.as_of !== undefined && ordersFills.as_of !== null) { + const ordersAsOfNs = typeof ordersFills.as_of === "string" + ? parseInstantNs(ordersFills.as_of) + : null; + if (ordersAsOfNs === null || (sizingEvalNs !== null && ordersAsOfNs > sizingEvalNs)) { + return buildUnavailableResult({ + reason: ordersAsOfNs === null + ? "orders_fills_invalid_as_of" + : "orders_fills_as_of_after_sizing_boundary", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } + } + if (ordersFills?.account_binding) { + const ab = ordersFills.account_binding; + const expectedAccount = parsedOrdersAccount.value ?? accountId; + if ( + (broker && ab.broker !== broker) + || (environment && ab.environment !== environment) + || (expectedAccount && parseAccountId(ab.account, ab.broker, ab.environment).value !== expectedAccount) + ) { + return buildUnavailableResult({ + reason: "orders_fills_account_binding_mismatch", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } + + if (raw.emergency_bypass !== undefined && raw.emergency_bypass !== null && typeof raw.emergency_bypass !== "boolean") { + return buildUnavailableResult({ + reason: "invalid_emergency_bypass", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + // Standing safety locks (OA-10 / pilot boundaries) + if (raw.margin_enabled === true || nav?.margin_enabled === true) { + return buildUnavailableResult({ + reason: "margin_prohibited", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (raw.h_usd !== undefined) { + const hRat = typeof raw.h_usd === "string" ? ratFromText(raw.h_usd) : null; + if (!hRat || hRat.n !== 0n) { + return buildUnavailableResult({ + reason: "nonzero_h_prohibited_in_pilot", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } + if (raw.kelly_applied === true) { + return buildUnavailableResult({ + reason: "kelly_prohibited", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (raw.live_trading_enabled === true) { + return buildUnavailableResult({ + reason: "live_trading_prohibited", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (raw.stop_loss_return_enabled === true) { + return buildUnavailableResult({ + reason: "stop_loss_return_prohibited", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + // Currency check (single-USD sizing unit, zero invented FX) + const inputCurrency = raw.currency ?? nav?.currency ?? "USD"; + if (inputCurrency !== "USD") { + return buildUnavailableResult({ + reason: "fx_unavailable", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (nav && (nav.status !== "available" || nav.freshness?.data_status !== "fresh" || nav.currency !== "USD")) { + return buildUnavailableResult({ + reason: sanitizePublicReason(nav.reason, "sizing_unit_nav_unavailable"), + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (nav) { + const navBoundaryCheck = validateNavAtSizingBoundary(nav, { + evaluatedAt, + sizingEvalNs, + options, + raw, + }); + if (!navBoundaryCheck.ok) { + return buildUnavailableResult({ + reason: navBoundaryCheck.reason, + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } + + // Fee schedule (OI-COST-3) must be explicitly provided with provenance + if (!feeParsed.ok) { + return buildUnavailableResult({ + reason: feeParsed.reason, + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + const equityRat = parseNonNegativeRat(raw.equity_usd ?? nav?.nav_usd); + const cashSettledRat = parseNonNegativeRat(raw.cash_settled_usd ?? nav?.settled_cash_usd); + const proceedsEligibleRat = raw.proceeds_eligible_usd === undefined + ? ZERO_RAT + : parseNonNegativeRat(raw.proceeds_eligible_usd); + const rCashRat = parseNonNegativeRat(raw.r_cash_usd); + + if (!equityRat || !cashSettledRat || !proceedsEligibleRat || !rCashRat) { + return buildUnavailableResult({ + reason: "incomplete_capital_inputs", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + let kPendRat = null; + let kPendReleaseAllowed = true; + let kPendUnknown = false; + if (ordersFills) { + const cutoffDom = ordersFills.domains?.cutoff_open_orders; + const cutoffDomAsOfNs = cutoffDom?.as_of ? parseInstantNs(cutoffDom.as_of) : null; + const cutoffCoverageUnproven = Boolean( + cutoffDom && ( + cutoffDom.domain_capability !== "supported" + || cutoffDom.completeness !== "complete" + || cutoffDom.truncated !== false + || (cutoffDomAsOfNs !== null && sizingEvalNs !== null && cutoffDomAsOfNs > sizingEvalNs) + || (typeof cutoffDom.cap === "number" && typeof cutoffDom.count === "number" && cutoffDom.count >= cutoffDom.cap) + ), + ); + const rawOfKPend = ordersFills.summary?.k_pend_usd; + if (rawOfKPend === null || rawOfKPend === undefined || (cutoffCoverageUnproven && rawOfKPend === "0")) { + kPendUnknown = true; + kPendRat = null; + kPendReleaseAllowed = false; + } else { + const ofKPend = parseNonNegativeRat(rawOfKPend); + if (!ofKPend) { + return buildUnavailableResult({ + reason: "invalid_k_pend_usd", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + kPendRat = ofKPend; + kPendReleaseAllowed = Boolean(ordersFills.summary.k_pend_release_allowed); + if (raw.k_pend_usd !== undefined && raw.k_pend_usd !== null) { + const explicitK = parseNonNegativeRat(raw.k_pend_usd); + if (!explicitK) { + return buildUnavailableResult({ + reason: "invalid_k_pend_usd", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + if (ratCmp(explicitK, kPendRat) > 0) kPendRat = explicitK; + } + if (raw.k_pend_release_allowed === false) kPendReleaseAllowed = false; + } + } else if (raw.k_pend_usd === null && raw.k_pend_release_allowed === false) { + kPendUnknown = true; + kPendRat = null; + kPendReleaseAllowed = false; + } else { + kPendRat = parseNonNegativeRat(raw.k_pend_usd); + if (!kPendRat) { + return buildUnavailableResult({ + reason: "missing_or_invalid_k_pend_usd", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + kPendReleaseAllowed = raw.k_pend_release_allowed !== false; + } + + let bBandRat = ZERO_RAT; + if (raw.b_band !== undefined && raw.b_band !== null) { + const parsedBand = parseNonNegativeRat(raw.b_band); + if (!parsedBand || ratCmp(parsedBand, ONE_RAT) > 0) { + return buildUnavailableResult({ + reason: "invalid_b_band", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + bBandRat = parsedBand; + } + + if (!Array.isArray(raw.targets)) { + return buildUnavailableResult({ + reason: "missing_targets", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + const seenSymbols = new Set(); + let weightSum = ZERO_RAT; + let cInvRat = ZERO_RAT; + const preparedTargets = []; + + for (const t of raw.targets) { + if (!t || typeof t !== "object" || Array.isArray(t) || !validateSafeSymbol(t.symbol) || seenSymbols.has(t.symbol)) { + return buildUnavailableResult({ + reason: "invalid_or_duplicate_target", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + seenSymbols.add(t.symbol); + + const qPreInt = parseNonNegativeIntBigInt(t.q_pre); + if (qPreInt === null) { + return buildUnavailableResult({ + reason: "fractional_shares_prohibited", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + const priceRefRat = parsePositiveRat(t.price_ref); + const wTargetRat = parseNonNegativeRat(t.w_target); + if (!priceRefRat || !wTargetRat || ratCmp(wTargetRat, ONE_RAT) > 0) { + return buildUnavailableResult({ + reason: "invalid_target_price_or_weight", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + weightSum = ratAdd(weightSum, wTargetRat); + if (ratCmp(weightSum, ONE_RAT) > 0) { + return buildUnavailableResult({ + reason: "target_weights_exceed_one", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + if (t.emergency_bypass !== undefined && t.emergency_bypass !== null && typeof t.emergency_bypass !== "boolean") { + return buildUnavailableResult({ + reason: "invalid_emergency_bypass", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + const idealNotional = ratMul(wTargetRat, equityRat); + const qIdealInt = ratFloorBigInt(ratDiv(idealNotional, priceRefRat)); + const deltaQRawInt = qIdealInt - qPreInt; + + // Resolve O5 worst-case limit price (OI-COST-4) + let priceLimRat = null; + let o5CollarMissing = false; + if (t.price_lim !== undefined && t.price_lim !== null) { + priceLimRat = parsePositiveRat(t.price_lim); + if (!priceLimRat || ratCmp(priceLimRat, priceRefRat) < 0) { + return buildUnavailableResult({ + reason: "invalid_o5_price_collar", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: { ...feeParsed.view, oi_cost_4_resolved: false }, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } else if (t.collar_bps !== undefined && t.collar_bps !== null) { + const collarBps = parseNonNegativeRat(t.collar_bps); + if (!collarBps) { + return buildUnavailableResult({ + reason: "invalid_o5_price_collar", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: { ...feeParsed.view, oi_cost_4_resolved: false }, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + priceLimRat = ratMul(priceRefRat, ratAdd(ONE_RAT, ratDiv(collarBps, BPS_DENOM))); + } else if (t.price_lim !== null && feeParsed.defaultCollarRat) { + priceLimRat = ratMul(priceRefRat, ratAdd(ONE_RAT, ratDiv(feeParsed.defaultCollarRat, BPS_DENOM))); + } else if (deltaQRawInt > 0n) { + o5CollarMissing = true; + } + + const prePosRat = ratMul({ n: qPreInt, d: 1n }, priceRefRat); + cInvRat = ratAdd(cInvRat, prePosRat); + + const wCurRat = equityRat.n > 0n ? ratDiv(prePosRat, equityRat) : ZERO_RAT; + const bandThreshold = ratMul(bBandRat, wTargetRat); + const withinBand = bBandRat.n > 0n && ratCmp(ratAbs(ratSub(wCurRat, wTargetRat)), bandThreshold) <= 0; + const emergencyBypass = (t.emergency_bypass ?? raw.emergency_bypass) === true; + + preparedTargets.push({ + symbol: t.symbol, + qPreInt, + priceRefRat, + priceLimRat, + o5CollarMissing, + wTargetRat, + wCurRat, + idealNotional, + qIdealInt, + deltaQRawInt, + withinBand, + emergencyBypass, + isOrderUnknown: unknownSet.has(t.symbol), + }); + } + + // Reconcile targets & held positions against any complete positions lists (nav.positions / raw.positions), + // treating an absent symbol in a supplied positions list as zero holdings so stale q_pre cannot oversell. + const targetBySymbol = new Map(preparedTargets.map((item) => [item.symbol, item])); + const hasRawPositions = Array.isArray(raw.positions); + const hasNavPositions = Array.isArray(nav?.positions); + + const parsePositionsList = (list) => { + const map = new Map(); + if (list === undefined || list === null) return { ok: true, map }; + if (!Array.isArray(list)) return { ok: false, reason: "invalid_position_entry" }; + for (const pos of list) { + if (!pos || typeof pos !== "object" || Array.isArray(pos) || !validateSafeSymbol(pos.symbol)) { + return { ok: false, reason: "invalid_position_entry" }; + } + const qtyInt = parseNonNegativeIntBigInt(pos.qty); + if (qtyInt === null) { + return { ok: false, reason: "fractional_shares_prohibited" }; + } + const prev = map.get(pos.symbol); + if (prev && prev.qtyInt !== qtyInt) { + return { ok: false, reason: "positions_qty_mismatch" }; + } + if (!prev) { + map.set(pos.symbol, { symbol: pos.symbol, qtyInt, pos }); + } + } + return { ok: true, map }; + }; + + const rawPosParsed = parsePositionsList(raw.positions); + if (!rawPosParsed.ok) { + return buildUnavailableResult({ + reason: rawPosParsed.reason, + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + const navPosParsed = parsePositionsList(nav?.positions); + if (!navPosParsed.ok) { + return buildUnavailableResult({ + reason: navPosParsed.reason, + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + if (hasRawPositions && hasNavPositions) { + for (const sym of new Set([...rawPosParsed.map.keys(), ...navPosParsed.map.keys()])) { + const rq = rawPosParsed.map.get(sym)?.qtyInt ?? 0n; + const nq = navPosParsed.map.get(sym)?.qtyInt ?? 0n; + if (rq !== nq) { + return buildUnavailableResult({ + reason: "positions_qty_mismatch", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } + } + + for (const item of preparedTargets) { + if (hasNavPositions) { + const navQty = navPosParsed.map.get(item.symbol)?.qtyInt ?? 0n; + if (item.qPreInt !== navQty) { + return buildUnavailableResult({ + reason: "positions_target_q_pre_mismatch", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } + if (hasRawPositions) { + const rawQty = rawPosParsed.map.get(item.symbol)?.qtyInt ?? 0n; + if (item.qPreInt !== rawQty) { + return buildUnavailableResult({ + reason: "positions_target_q_pre_mismatch", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } + } + + // Fold any held non-target positions into C_inv without double counting; + // reject unpriced or zero-valued held non-zero positions fail-closed. + const allNonTargetEntries = [...rawPosParsed.map.values(), ...navPosParsed.map.values()]; + for (const { symbol, qtyInt, pos: extraPos } of allNonTargetEntries) { + if (targetBySymbol.has(symbol) || seenSymbols.has(symbol)) continue; + + let mvRat = null; + if (extraPos.market_value_usd !== undefined && extraPos.market_value_usd !== null) { + mvRat = parseNonNegativeRat(extraPos.market_value_usd); + if (!mvRat || (qtyInt > 0n && mvRat.n === 0n)) { + return buildUnavailableResult({ + reason: "held_position_valuation_unavailable", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + } else if (extraPos.price_ref !== undefined && extraPos.price_ref !== null) { + const refPriceRat = parsePositiveRat(extraPos.price_ref); + if (!refPriceRat) { + return buildUnavailableResult({ + reason: "held_position_valuation_unavailable", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + mvRat = ratMul({ n: qtyInt, d: 1n }, refPriceRat); + } else if (qtyInt === 0n) { + mvRat = ZERO_RAT; + } else { + return buildUnavailableResult({ + reason: "held_position_valuation_unavailable", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + seenSymbols.add(symbol); + cInvRat = ratAdd(cInvRat, mvRat); + } + + if (ratCmp(cInvRat, equityRat) > 0) { + return buildUnavailableResult({ + reason: "invested_exceeds_equity_margin_prohibited", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: feeParsed.view, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + + const anyBuyMissingCollar = preparedTargets.some((item) => item.deltaQRawInt > 0n && item.o5CollarMissing); + const anyReductionTarget = preparedTargets.some((item) => item.deltaQRawInt < 0n); + if (anyBuyMissingCollar && !anyReductionTarget) { + return buildUnavailableResult({ + reason: "oi_cost_4_price_collar_unavailable", + accountId, + broker, + environment, + evaluatedAt, + feeScheduleView: { ...feeParsed.view, oi_cost_4_resolved: false }, + orderUnknownSymbols, + origin, + sourceClass, + evidenceRef, + }); + } + const oiCost4AllBuysResolved = !anyBuyMissingCollar; + + const rawAvailRat = kPendUnknown + ? null + : ratSub(ratAdd(cashSettledRat, proceedsEligibleRat), ratAdd(rCashRat, kPendRat)); + const cAvailRat = kPendUnknown ? ZERO_RAT : ratMaxZero(rawAvailRat); + + // First pass: classify holds, reductions, band-suppressed, missing-collar / ORDER-UNKNOWN / unknown-K_pend blocks, and active buys. + const buyCandidates = []; + for (const item of preparedTargets) { + item.bandSuppressed = false; + item.emergencyBypassApplied = false; + item.buyBlockedReason = null; + item.deltaQFinalInt = 0n; + + if (item.deltaQRawInt === 0n) { + item.action = "HOLD"; + continue; + } + + if (item.deltaQRawInt < 0n) { + if (item.emergencyBypass) { + item.emergencyBypassApplied = true; + item.deltaQFinalInt = item.deltaQRawInt; + item.action = "SELL"; + } else if (item.withinBand) { + item.bandSuppressed = true; + item.deltaQFinalInt = 0n; + item.action = "HOLD"; + } else { + item.deltaQFinalInt = item.deltaQRawInt; + item.action = "SELL"; + } + continue; + } + + // Buy path (deltaQRawInt > 0n): reductions above NEVER depend on K_pend, C_avail, or O5 collars. + if (item.isOrderUnknown) { + item.deltaQFinalInt = 0n; + item.action = "BLOCKED_BUY"; + item.buyBlockedReason = "order_unknown_lock"; + continue; + } + if (item.o5CollarMissing) { + item.deltaQFinalInt = 0n; + item.action = "BLOCKED_BUY"; + item.buyBlockedReason = "oi_cost_4_price_collar_unavailable"; + continue; + } + if (kPendUnknown) { + item.deltaQFinalInt = 0n; + item.action = "BLOCKED_BUY"; + item.buyBlockedReason = "k_pend_unavailable_open_orders"; + continue; + } + if (item.withinBand) { + item.bandSuppressed = true; + item.deltaQFinalInt = 0n; + item.action = "HOLD"; + item.buyBlockedReason = "no_trade_band"; + continue; + } + if (cAvailRat.n === 0n) { + item.deltaQFinalInt = 0n; + item.action = "BLOCKED_BUY"; + item.buyBlockedReason = "zero_deployable_cash"; + continue; + } + const demandCost = computeOrderCostForQty(item.deltaQRawInt, item.priceLimRat, feeParsed).totalCost; + item.demandCostRat = demandCost; + buyCandidates.push(item); + } + + // Second pass: exact fee-and-collar-constrained whole-share allocation within C_avail. + if (buyCandidates.length > 0) { + let totalDemandCost = ZERO_RAT; + for (const c of buyCandidates) totalDemandCost = ratAdd(totalDemandCost, c.demandCostRat); + + if (ratCmp(totalDemandCost, cAvailRat) <= 0) { + for (const c of buyCandidates) { + c.deltaQFinalInt = c.deltaQRawInt; + c.action = "BUY"; + } + } else { + for (const c of buyCandidates) { + const shareBudget = ratMul(cAvailRat, ratDiv(c.demandCostRat, totalDemandCost)); + const maxQ = maxAffordableShares(c.deltaQRawInt, shareBudget, c.priceLimRat, feeParsed); + c.deltaQFinalInt = maxQ; + if (maxQ === 0n) { + c.action = "BLOCKED_BUY"; + c.buyBlockedReason = "budget_insufficient_for_one_share"; + } else { + c.action = "BUY"; + } + } + } + } + + let totalBuyCommitRat = ZERO_RAT; + const orderItems = preparedTargets.map((item) => { + const deltaQBuyInt = item.deltaQFinalInt > 0n ? item.deltaQFinalInt : 0n; + const deltaQSellInt = item.deltaQFinalInt < 0n ? -item.deltaQFinalInt : 0n; + const qTargetInt = item.qPreInt + item.deltaQFinalInt; + + const absDeltaInt = item.deltaQFinalInt < 0n ? -item.deltaQFinalInt : item.deltaQFinalInt; + const estNotionalRefRat = ratMul({ n: absDeltaInt, d: 1n }, item.priceRefRat); + + let estWorstCaseNotionalRat = ZERO_RAT; + let estCommRat = ZERO_RAT; + let estBExecRat = ZERO_RAT; + let estTotalBuyCommitRat = ZERO_RAT; + + if (deltaQBuyInt > 0n) { + const buyCost = computeOrderCostForQty(deltaQBuyInt, item.priceLimRat, feeParsed); + estWorstCaseNotionalRat = buyCost.worstCaseNotional; + estCommRat = buyCost.commission; + estBExecRat = buyCost.bExec; + estTotalBuyCommitRat = buyCost.totalCost; + totalBuyCommitRat = ratAdd(totalBuyCommitRat, estTotalBuyCommitRat); + } else if (deltaQSellInt > 0n) { + const sellPriceBasis = item.priceLimRat ?? item.priceRefRat; + const sellCost = computeOrderCostForQty(deltaQSellInt, sellPriceBasis, feeParsed); + estCommRat = sellCost.commission; + estBExecRat = sellCost.bExec; + } + + const idealRoundedNotional = ratMul({ n: item.qIdealInt, d: 1n }, item.priceRefRat); + const roundingFrictionRat = ratAbs(ratSub(item.idealNotional, idealRoundedNotional)); + + let rhoOrder; + if (absDeltaInt === 0n || estNotionalRefRat.n === 0n) { + rhoOrder = { + value: null, + threshold: null, + status: "not_applicable_zero_order", + numerator_usd: null, + denominator_usd: null, + rounding_friction_usd: formatUsdRat(roundingFrictionRat), + }; + } else { + const numRat = ratAdd(estCommRat, roundingFrictionRat); + rhoOrder = { + value: formatRatioRat(ratDiv(numRat, estNotionalRefRat)), + threshold: null, + status: "diagnostic_only_threshold_unset", + numerator_usd: formatUsdRat(numRat), + denominator_usd: formatUsdRat(estNotionalRefRat), + rounding_friction_usd: formatUsdRat(roundingFrictionRat), + }; + } + + return { + symbol: item.symbol, + price_ref: formatUsdRat(item.priceRefRat), + price_lim: item.priceLimRat ? formatUsdRat(item.priceLimRat) : null, + w_target: formatRatioRat(item.wTargetRat), + w_cur: formatRatioRat(item.wCurRat), + q_pre: item.qPreInt.toString(), + q_ideal: item.qIdealInt.toString(), + delta_q_raw: item.deltaQRawInt.toString(), + delta_q_final: item.deltaQFinalInt.toString(), + delta_q_buy: deltaQBuyInt.toString(), + delta_q_sell: deltaQSellInt.toString(), + q_target: qTargetInt.toString(), + action: item.action, + band_suppressed: item.bandSuppressed, + emergency_bypass_applied: item.emergencyBypassApplied, + buy_blocked_reason: item.buyBlockedReason, + est_notional_ref_usd: formatUsdRat(estNotionalRefRat), + est_worst_case_notional_usd: formatUsdRat(estWorstCaseNotionalRat), + est_commission_usd: formatUsdRat(estCommRat), + est_b_exec_usd: formatUsdRat(estBExecRat), + est_total_buy_commit_usd: formatUsdRat(estTotalBuyCommitRat), + rho_order: rhoOrder, + }; + }); + + const remainingAvailRat = kPendUnknown ? ZERO_RAT : ratSub(cAvailRat, totalBuyCommitRat); + const bMinInput = raw.b_min_tier && typeof raw.b_min_tier === "object" ? raw.b_min_tier : {}; + const bMinTier = evaluateWorkableBankrollBminTier({ + bankroll_w_usd: bMinInput.bankroll_w_usd ?? formatUsdRat(equityRat), + c_fixed_ann_usd: bMinInput.c_fixed_ann_usd ?? null, + annual_ticket_count: bMinInput.annual_ticket_count, + annual_rounding_friction_usd: bMinInput.annual_rounding_friction_usd, + rounding_friction_ann_usd: bMinInput.rounding_friction_ann_usd, + annual_passthrough_usd: bMinInput.annual_passthrough_usd, + fixed_passthrough_ann_usd: bMinInput.fixed_passthrough_ann_usd, + expected_excess_growth_ann_usd: bMinInput.expected_excess_growth_ann_usd ?? null, + fee_schedule_resolved: feeParsed, + }); + + const topReason = kPendUnknown + ? "k_pend_unavailable_buys_blocked" + : (!oiCost4AllBuysResolved ? "oi_cost_4_price_collar_unavailable_buys_blocked" : null); + + return stripPrivateLocators({ + schema_version: DEPLOYABLE_CAPITAL_SCHEMA, + status: "available", + reason: topReason, + account_id: accountId, + broker, + environment, + currency: "USD", + currency_coercion: "prohibited", + fx_inferred: false, + margin_enabled: false, + h_usd: "0", + kelly_applied: false, + live_trading_enabled: false, + stop_loss_return_enabled: false, + fractional_shares: "prohibited", + evaluated_at: evaluatedAt, + capital: { + equity_usd: formatUsdRat(equityRat), + c_inv_usd: formatUsdRat(cInvRat), + cash_settled_usd: formatUsdRat(cashSettledRat), + proceeds_eligible_usd: formatUsdRat(proceedsEligibleRat), + r_cash_usd: formatUsdRat(rCashRat), + k_pend_usd: kPendUnknown ? null : formatUsdRat(kPendRat), + k_pend_release_allowed: kPendReleaseAllowed, + raw_deployable_cash_usd: kPendUnknown ? null : formatUsdRat(rawAvailRat), + c_avail_usd: formatUsdRat(cAvailRat), + total_buy_commit_usd: kPendUnknown ? "0" : formatUsdRat(totalBuyCommitRat), + remaining_deployable_cash_usd: formatUsdRat(remainingAvailRat), + }, + fee_schedule: { + ...feeParsed.view, + oi_cost_4_resolved: oiCost4AllBuysResolved, + }, + order_unknown_symbols: orderUnknownSymbols, + orders: orderItems, + b_min_tier: bMinTier, + origin, + source_class: sourceClass, + evidence_ref: evidenceRef, + }); +}