Skip to content

feat(sa2): authoritative orders/fills state machine and deployable capital sizing - #1221

Merged
Pigbibi merged 11 commits into
mainfrom
feat/sa2-orders-fills-deployable-capital
Nov 24, 2026
Merged

Pigbibi merged 11 commits into
mainfrom
feat/sa2-orders-fills-deployable-capital

Conversation

@Pigbibi

@Pigbibi Pigbibi commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

AI assistance

Assisted by OpenAI Codex CLI (gpt-6.2-astra reasoning high pre-push blocker review) and Coordinator/subagent orchestration (sa2-orders-capital-engineer); all SA-2/schema/broker/naming/SA-1/gitleaks checks were re-verified on exact HEAD ec7b145a31dfbcfc3457a6a6453867ccbf396a8b, with full js (including read_contract_boundaries_validation.mjs and test:operations) and python suites run by PR CI.

What changed

Implements SUPPLY-A SA-2 (C-SA-25 authoritative orders/fills state machine, multi-broker normalizer, and C-SA-Q21 deployable capital & whole-share sizing) cleanly on main (bcd52987), with zero live order submission and strict read-only ADR 0002 isolation:

  • Schemas & Frozen Matrix Fixtures (schemas/qsl-authoritative-orders-fills.v1.schema.json, schemas/qsl-deployable-capital-sizing.v1.schema.json, tests/fixtures/sa2/*.json):
    • Adds draft-2020-12 closed contracts for authoritative orders/fills reconciliation (with nullable executionRecord.executed_at when legacy timestamps omit local time/zone rather than fabricating midnight UTC) and C-SA-Q21 deployable capital / whole-share sizing (K_eff, K_pend, q_final, collar/bypass/cap metadata), plus frozen demo, C-SA-25, and Q21 validation fixtures with zero raw account IDs or private locators.
  • Multi-Broker Normalizer, Coverage & Fail-Closed Dedup State (web/strategy-switch-console/application/orders_fills/*):
    • Implements deterministic multi-broker order/fill normalization (IBKR Flex / CPAPI, Longbridge, Schwab), domain-cap (cap=500) and completeness fail-closed coverage guards (including treating positive count with omitted records as incomplete and rejecting future as_of > evaluated_at cutoff snapshots from releasing K_pend), same-batch/cross-symbol/future-event ORDER_UNKNOWN locks (lockStore), canonical identity preservation, and fail-closed K_pend tracking (including null K_pend on first unproven open-orders read and additive non-overlapping visible reserves).
    • Pre-links client/broker order IDs across executions, excludes untimed executions (executed_at: null) from releasing BUY k_pend_usd or marking FILLED when cutoff evidence is absent, retains active ORDER_UNKNOWN locks on untimed terminal observations (maxEventNs === null || maxEventNs > evalAtNs), reconciles definitive non-future FILLED quantities (qty_filled = submitted, qty_remaining = "0") while keeping execution-derived avg_fill_price/unbacked fees null when execution details lag, honors normalized effective_at_ns on post-cutoff terminal transitions, converts legacy local_time + IANA time_zone accurately, sums qualified fee_usd independently of mixed native fee currencies, rejects conflicting non-USD notional_usd / mixed-currency qty * price, and avoids zero-fee coercion when fees are missing.
  • Deployable Capital & Whole-Share Sizing (web/strategy-switch-console/application/sizing_unit/deployable_capital.js):
    • Implements C-SA-Q21 deployable capital deduction, validates supplied orders_fills.evaluated_at / as_of / cutoff_open_orders.as_of and nav.observed_at / fetched_at / evaluated_at + freshness at sizing's evaluated_at boundary (re-evaluating freshness via ./freshness.js when needed and failing closed on future-evaluated or post-close stale inputs), checks B_min,tier and b_exec_usd cost items, preserves SELL when BUY fails collar or K_pend, enforces strict boolean emergency_bypass validation, fails closed on unpriced held positions, enforces cross-source identity checks, reconciles target q_pre against complete positions lists (treating absent symbols as 0 shares to prevent oversells), and sanitizes nav.reason/evidence outputs.
  • Read-Only Console Helper & Validation Harness (web/strategy-switch-console/application/console_api/executions.js, tests/sa2_*.mjs, .github/workflows/validate.yml):
    • Adds pure read-only buildConsoleOrdersFillsReadModel() helper and wires tests/sa2_demo_validation.mjs, tests/sa2_orders_fills_validation.mjs, and tests/sa2_deployable_capital_validation.mjs into .github/workflows/validate.yml.

How verified

Verified on exact HEAD ec7b145a31dfbcfc3457a6a6453867ccbf396a8b (after remediating both Codex 6049055796 P1 findings PRRT_kwDOSZeN-M67pKBv, pKB0 on top of aec773fd, 1dce8271, 81233062, and 8f5eecc0):

  • node tests/sa2_demo_validation.mjs: PASS (7/7)
  • node tests/sa2_orders_fills_validation.mjs: PASS (SA-A12)
  • node tests/sa2_deployable_capital_validation.mjs: PASS (SA-A13)
  • node tests/schema_validators_validation.mjs: PASS (3/3)
  • node tests/broker_executions_validation.mjs, node tests/naming_canonical_validation.mjs, node tests/sa1_sizing_contracts_validation.mjs: PASS
  • gitleaks (11 commits, 0 leaks), git diff --check, commit line-width <= 72, and static raw-account/private-locator/workstation-path scan: PASS
  • Prior verified baselines on 8f5eecc0 / aec773fd (re-validated on ec7b145a by PR CI): js GitHub Actions suite (SUCCESS), npm --prefix web/strategy-switch-console run test:operations (PASS), python3 -m unittest discover -s python/tests (1239 tests OK, skipped=10), read_contract_boundaries_validation.mjs (110 route branches, 112 internal operations, 10 exceptions; ok).

Why

Delivers the fail-closed authoritative orders/fills state machine (C-SA-25) and deployable capital whole-share sizing unit (C-SA-Q21) needed downstream for SUPPLY-A SA-3 / SA-4 while guaranteeing non-double-counted reserves, look-ahead/post-cutoff/untimed-execution safety, anti-oversell position reconciliation, accurate timezone/currency handling, and zero unsafe identity leaks.

Risk

Tier: R2 / Fail-closed sizing & authoritative orders/fills accounting library (offline pure computation; zero broker submission or live/paper flag unlock).

  • ADR 0002 answers:
    1. Operation classification: buildConsoleOrdersFillsReadModel() in web/strategy-switch-console/application/console_api/executions.js and the underlying orders_fills / sizing_unit/deployable_capital helpers are pure read-only observations (no command endpoints added; no new registered exceptions).
    2. Can a read write, migrate, refresh, or schedule work? No. Reads invoke no KV/SQLite mutations, no state migrations, no refresh triggers, and no scheduled work (lockStore is optional caller-supplied injection).
    3. Does any name, label, or key become identity? No. All domain state keys and outputs validate canonical opaque account_id / deployment_id and reject raw broker account IDs (isRawAccountIdentifier) or unsafe storage locators (isUnsafePrivateLocator).
    4. Does each projection state its scope, cap, and completeness? Yes. evaluateAuthoritativeOrdersAndFills and buildConsoleOrdersFillsReadModel explicitly emit scope, per-domain cap (500 records, fail-closed partial_domain_truncated & incomplete positive-count/missing-records guard), and completeness metadata (failing closed to K_pend: null, k_pend_release_allowed: false on future as_of or untimestamped executions, or ORDER-UNKNOWN, plus orders_fills_evaluated_after_sizing_boundary fail-closed boundary checks).
  • Rollback: Revert the PR merge commit on main; existing SA-1 contracts, console_api routes, and live/paper gates remain untouched.

Slice SA2-W1: freeze Draft 2020-12 schemas and pre-implementation
test vectors before normalizer, lock, or sizing code.

- schemas/qsl-authoritative-orders-fills.v1.schema.json (C-SA-25)
- schemas/qsl-deployable-capital-sizing.v1.schema.json (C-SA-Q21)
- tests/fixtures/sa2/sa2_demo_cases.json (SA2-D1..SA2-D7)
- tests/fixtures/sa2/sa2_orders_fills_matrix.json (SA-A12)
- tests/fixtures/sa2/sa2_q21_matrix.json (SA-A13)
- tests/sa2_{demo,orders_fills,deployable_capital}_validation.mjs
Slice SA2-W2: add pure leaf orders_fills constants, domain coverage,
and multi-broker normalizer under application/orders_fills/.

- constants.js: zero-import enums, caps (256/512/2048), regexes
- coverage.js: proven-empty & non-release K_pend coverage gates
- normalize.js: (broker, environment, account) separation, null fees,
  non-USD unavailability, and pure adaptLegacyBrokerExecutionPayload
Slice SA2-W3: implement execution deduplication, conflict rejection,
order lifecycle reconciliation, restart-persistent ORDER-UNKNOWN
symbol locks (O4/Q5-2), and helpers.js composition entrypoint.

- dedup_state.js: (broker, environment, account) key binding, dedup vs
  conflicting-duplicate throw, partial fill/cancel & K_pend math
- order_unknown_lock.js: pure serializable lock store with query_target
  and terminal-evidence-only clearing
- helpers.js & normalize.js: WeakMap submission metadata + entrypoint
Slice SA2-W4: implement exact-decimal deployable capital, whole-share
sizing, fee/collar-constrained buy allocation, unblocked reductions,
B_min,tier < 10% check, and rho_order diagnostic under sizing_unit/.

- deployable_capital.js: C_inv, C_avail, q^ideal, delta_q^buy,
  emergency bypass, ORDER-UNKNOWN buy block, unset OI-COST fail-closed
- normalize.js: accept resolved_at/updated_at fallback on submissions
- Add pure buildConsoleOrdersFillsReadModel in console_api/executions.js
- Validate order_unknown_symbols array and symbol inputs in sizing_unit
- Preserve zero new routes, DO actions, SQLite tables, and B0 contract
- Run sa2_demo, sa2_orders_fills, and sa2_deployable_capital checks
- Validate workflow YAML with actionlint
- Enforce null K_pend on first unproven open-orders read and add
  non-overlapping visible orders without dropping prior reserves
- Reject records > cap regardless of truncated flag and fail closed
  incomplete count != records.length domains
- Harden ORDER_UNKNOWN same-batch, cross-symbol, and future-event
  locks; unify canonical account keys and forbid broker_order_id theft
- Deduplicate IBKR Flex across observed_at, reject conflicting non-USD
  notional_usd, never mix non-USD qty*price or coerce zero missing fees
- Fix TDZ ReferenceError, enforce cross-source identity consistency,
  require b_exec_usd and B_min,tier cost items, keep SELLs unblocked
  when buys fail collar/K_pend, validate boolean emergency_bypass, and
  fail closed on unpriced held positions
- Tighten schema currency regex, sanitize nav.reason/evidence outputs,
  and remove static raw account/locator literals from sa2 JSON fixture
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T23:43:49.095327Z ec7b145 Manual request
🔒 Security Review ✅ Completed 2026-11-24T23:45:06.214894Z ec7b145 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: aec773fd90

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aec773fd90

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

- Reject K_pend release on future empty cutoff domains (as_of > eval)
- Partition executions at cutoff.as_of so later fills advance
  remaining qty without triggering false cutoff mismatches
- Reconcile every sizing target q_pre against supplied positions
  lists (treating absent symbols as 0 shares to block oversells)
- Downgrade supported domains with count > 0 and omitted records
  to incomplete so unexamined open orders cannot release K_pend
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 1dce82714f

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1dce82714f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

- Link client_order_id executions first before retrying
  broker_order_id-only fills so two-pass matching reconciles cleanly.
- Advance post-cutoff terminal transitions using effective_at_ns
  (including updated_at) and set accurate order updated_at.
- Convert legacy local_time + time_zone deterministically to UTC
  or emit null executed_at without fabricating midnight UTC.
- Sum execution fee_usd independently when mixed fee currencies occur.
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 81233062aa

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 81233062aa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

- Exclude untimed (executed_at: null) executions from effective fills
  so unproved buys without a cutoff keep conservative/null K_pend.
- Reject orders_fills evaluated or dated after sizing evaluated_at
  (orders_fills_evaluated_after_sizing_boundary) to block look-ahead.
- Reconcile definitive FILLED qty_filled/qty_remaining when fill
  records lag while keeping execution-derived avg_fill_price null.
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8f5eecc0a9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 8f5eecc0a9

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

- Validate sizing_unit_nav observed/fetched/evaluated timestamps against
  the sizing evaluated_at boundary and re-check freshness at boundary.
- Retain active ORDER_UNKNOWN locks when terminal evidence omits all
  timestamps rather than clearing without proven event ordering.
@Pigbibi

Pigbibi commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: ec7b145a31

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: ec7b145a31

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@Pigbibi Pigbibi added the agent-approved An agent cleared this high-risk change on the current head; not an owner confirmation label Nov 24, 2026
@Pigbibi
Pigbibi merged commit ca787b3 into main Nov 24, 2026
22 of 24 checks passed
@Pigbibi
Pigbibi deleted the feat/sa2-orders-fills-deployable-capital branch November 24, 2026 23:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-approved An agent cleared this high-risk change on the current head; not an owner confirmation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant