stock-bot/docs/development/backlog/tasks/F02.md
Boki b65acccd91 feat(research): add owner-aware ledger and intraday storage
Implement reviewed F02/D02: exact owner accounting, atomic funding checks, idempotent receipts and ledger checkpoints; connect existing EOD intraday storage through validated research admission without active financial-engine cutover.
2026-10-22 21:16:53 -04:00

7 KiB

F02 — Implement one owner-aware financial ledger

Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Rust accounting.

Scheduling source of truth: manifest entry F02. No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.

Evidence and root cause

Intended behavior and implementation scope

Implement one owner-keyed ledger from its first version; absorb F03 rather than building aggregate cost basis and replacing it later. Adapt existing Rust position calculations. Store owned quantity and remaining cost amount; derive average price and account aggregates. For a partial disposal, round the proportional released basis at posting precision; final disposal releases the exact residual. Fees are separate postings. Use one internal apply(state,command) kernel for resident research and staged durable transactions.

Seventh-wave implementation boundary

F01 is committed in b4af840. Keep this ledger additive: no replacement of active legacy position/accounting code, native binding, SQL transaction integration or paper migration. ADR-005 remains unapproved; F02 provides the in-memory transition/checkpoint seam, not its durable adapter.

  • A ledger checkpoint is distinct from F01's economic projection. It retains genesis, books including closed-position realized P&L, cash/fees, marks, risk-session identity, revision and ordered accepted receipts/aliases. Restore verifies by replay and canonical state comparison. It is not an order/replay/strategy/RNG session snapshot.
  • Exact multiplication and proportional release use maintained arithmetic with a single final half-away posting boundary, not precision-losing decimal intermediates. Account valuation sums owner-level marked postings; missing marks reject valuation instead of inventing zero or cost-based prices.
  • Invalid commands fail atomically without changing balances, books, marks or receipts. Basic cash funding includes fees. Reservation and portfolio risk policies remain F04, including recording accepted risk-rejection outcomes.
  • Identical command retry returns its original receipt even after later transitions. Identical fill under a new command ID aliases that receipt, explicitly marked replayed: compare event time and the entire canonical fill body, excluding only command ID. Different fill content or reuse of a fee ID by another fill rejects. Never emit duplicate economic deltas.
  • Normal transitions stage only affected state; checkpoint serialization/replay is explicit. Record repeatable scoped transition and checkpoint/restore measurements without claiming end-to-end research throughput.

Exclusions

No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.

Likely files and ownership

  • apps/stock/engine/src/financial/ledger.rs (new)
  • apps/stock/engine/src/financial/ownership.rs (only if separate module improves cohesion)
  • apps/stock/engine/src/positions/mod.rs

Write locks: financial-contract, rust-ledger. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md.

Dependencies and blockers

Implementation requires F01 integrated.

Architecture decisions: ADR-002. Agents may not independently amend their policies.

Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.

Acceptance criteria

  • Cash + marked holdings = equity; initial capital + net cashflows + realized gross P&L + unrealized P&L - fees = equity at declared posting precision.
  • A buys10@100, B buys10@200, A sells10@200 => A gross realized1000, B retains10@200. Only A receives A's fill; wrong-owner disposal rejects.
  • Total basis5 for quantity3 is not reconstructed as5.00000001 from display average. All partial/final disposals release exactly5.
  • Duplicate identical fills are idempotent; conflicting ID payload fails; snapshot restore/replay yields identical canonical economic postings.
  • Resident transitions do not serialize/clone the entire account every observation. Durable staging uses the same kernel and emits required ordered effect views.

Mandatory tests

  • owner_basis_A_B, basis_residual_partial_final, owner_quantity_sum, wrong_owner_disposal, per_fill_fee_once, conflicting_fill_id, snapshot_restore_parity.
  • Seeded randomized valid transition sequences reconcile; terminal mark retains open positions without inventing a fill.

Apply relevant quality gates. Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.

Regression risks and rollback

Financial or compatibility regression; preserve existing fixtures and version changed semantics. Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.

Handoff

Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.