stock-bot/docs/development/FIRST-WAVE.md

16 KiB

First development wave: four independent assignments

Owner authorized the planning commit and first-wave implementation on 2026-10-22. The canonical manifest records that scope. Its four tasks may now run in isolated worktrees; this does not authorize pushes, PRs, trading operations or subsequent implementation commits.

Choose C01, C03, C04, W01. They have no code/ADR prerequisites beyond global execution approval and no shared authored source files. Recommend three implementers plus one coordinator/read-only reviewer; start C01/C03/W01 and rotate C04 into the first free slot. If runtime cleanup is more urgent than the interim funding fix, start C04 before C03. This is capacity management, not a dependency.

Common execution contract

Each prompt below incorporates this contract:

  • Read repository instructions, the task file, relevant ADRs and docs/development/QUALITY-GATES.md. Scope is the task, not permission to implement neighboring tasks.
  • Planner claims the ID/write locks in the canonical manifest; implementation agents do not edit scheduling metadata. Use one branch/worktree per task from the recorded integration base.
  • Inspect existing changes before editing. Preserve user work. Use only assigned writable files; additional required edits must be reported to the coordinator before expanding scope.
  • Keep native builds, dependency symlinks and disposable test resources worktree-local. Verify workspace imports resolve into your worktree, not the original checkout. Do not share mutable addon/target output between concurrent agents.
  • Before tests that import native code, build the addon from the assigned worktree if absent/stale, record its resolved path/hash, and do not count a pre-existing binary as validation. Generated native binaries/declarations are not authored changes.
  • Do not alter shared financial contracts, schemas, root scripts, shared fixtures or another task's files. W01 alone may add a minimal frontend test dev dependency if necessary and must explain it.
  • Run exact listed checks. Report baseline failures, unavailable dependencies and skipped checks honestly; do not install/provision resources beyond execution authorization. No tests against the development trading account/database.
  • Supply focused diff, numerical expectations, test commands/results, risks and handoff notes. Independent review plus tests on the integrated change are required before “done.” Do not commit or create a PR without explicit approval.

Ownership and integration

Task Writable implementation scope Dedicated tests Dependencies / later impact
C01 Legacy Rust backtest engine/results Inline Rust; optional native-terminal-equity.test.ts No prerequisite; arithmetic fixture retained during later financial migration
C03 TS execution model/SimulationExecution fee-funding.test.ts No prerequisite; closes a current fee hole without deciding the new account model
C04 ModeManager mode-lifecycle.test.ts No prerequisite; unlocks C06 fail-closed composition
W01 Backtest detail/control/API hook and shared websocket hook backtest-run-controls.test.tsx No prerequisite; unlocks W02 then W04 web release

Each has disjoint authored files. C01/C03 may both run account tests, but against their own fixtures/resources. Do not parallelize W02 with W01 or C06 with C04. Shared financial contracts F01 onward have one coordinated owner, unlike these isolated legacy fixes.

C01 — Native terminal valuation

Role: Rust financial-correctness engineer. Task. Priority P0.

Exact Codex implementation prompt

Implement only C01 under the Common execution contract in
docs/development/FIRST-WAVE.md. Read backlog/tasks/C01.md and the relevant quality gates.

Inspect the current native terminal liquidation and result projection. Preserve current
sizing, matching, liquidation thresholds, order policy and fee policy. After terminal
closing fills, recompute final account equity and replace the existing terminal-time
curve sample; do not append a duplicate timestamp or charge closing costs twice.

Add a deterministic internal fixture that buys exactly one share at4 from cash10,
with1% entry and exit fees and zero slippage. Liquidation at4 must leave cash,
final equity and finalValue at9.92, with total fees0.08. Do not derive fixture quantity
from production sizing. Add no-position, zero-fee, multiple-symbol and terminal
timestamp-uniqueness cases. Positions eligible for liquidation in these fixtures
must be flat. Preserve the existing micro-position liquidation threshold; if a
residual remains under that existing policy, its marked value still belongs in equity.

Writable files:
- apps/stock/engine/src/backtest/engine.rs
- apps/stock/engine/src/backtest/simple_results.rs
- inline Rust tests in those modules
- optionally test/integration/native-terminal-equity.test.ts, only if the existing
  public API can exercise the same fixture without a testing-only exported API.

Read existing result-mapping/backtest-ledger integration tests but do not edit them
independently. Do not implement next-open matching, the new ledger, new ownership,
new risk policies or other backlog tasks.

Run the C01 commands below, building this worktree's addon before native integration
tests. Report exact results, fixture arithmetic and any existing limitations.
Do not commit, push or create a PR without explicit approval.

Tests

Run from the assigned repository root:

cargo test -p engine --lib --offline
bun run --cwd apps/stock/engine build:debug
bun test test/integration/backtest-result-mapping.test.ts test/integration/backtest-ledger.test.ts

If the optional public-surface test is added, also run:

bun test test/integration/native-terminal-equity.test.ts

Definition of done: 9.92/0.08 fixture passes; closing fills counted once; curve/report reconcile; one terminal timestamp; no-position and multi-symbol behavior covered; existing adapters pass against the current worktree addon; no other economic policy changed.

C03 — Fee-inclusive legacy funding check

Role: TS trading infrastructure/financial correctness. Task. Priority P0.

Exact Codex implementation prompt

Implement only C03 under the Common execution contract in
docs/development/FIRST-WAVE.md. Read backlog/tasks/C03.md and ADR-002's explicit
legacy-versus-canonical distinction before editing.

Keep the current TypeScript gross-exposure capital model, short/reversal behavior
and reducing-order exemption. Correct only the missing unpaid fee liability in
its non-reducing capital check. Include the proposed remaining order plus other
pending remaining commitments, using each order's frozen commission policy.
At fill, exclude the current order from the "other pending" set. Fees already paid
are already reflected in equity: do not count them again. Reuse existing decimal
helpers and existing pending-order state; no new reservation schema or cash-only model.

Writable files:
- apps/stock/orchestrator/src/execution/model.ts
- apps/stock/orchestrator/src/execution/SimulationExecution.ts
- test/integration/fee-funding.test.ts (new).

Use test/fixtures/execution.ts and existing execution/recovery tests as read-only
context. If another file is genuinely required, report it before expanding scope.

Required deterministic cases, with other existing risk limits configured so they
do not mask this capital guard:
1. Cash10000, buy100@100,1% fees rejects without financial mutation.
2. Buy99@100 succeeds; total fee99; cash1.
3. With no fill liquidity, one pending buy50@100 has computed commitment5050;
   another50 would require10100 total and rejects. Cancellation releases the
   first commitment and allows a valid replacement.
4. Fill the99-share order as10 then89 shares; total fees99 and final cash1.
   Duplicate order/market events cannot add fees again.
5. Changing runtime commission configuration cannot alter a stored order's policy.
6. Existing short/reversal and reducing-order behavior is unchanged.

Do not implement canonical Rust reservations, new financing semantics, migrations,
strategy changes or new account models. Do not claim this patch prevents every form
of legacy borrowing; short-cover insolvency is outside this narrow scope.
Run the C03 commands below and provide exact outcomes. Do not commit or create a
PR without explicit approval.

Tests

bun test test/integration/fee-funding.test.ts test/integration/order-execution.test.ts test/integration/strategy-recovery.test.ts
bun run typecheck
bun run test:contracts

Before merge, the integration owner also runs bun run test:postgres using the repository's disposable safety-database/Redis configuration in QUALITY-GATES.md. This is an integration gate, not authorization to touch the developer's DB.

Definition of done: exact numerical cases above; existing shorts/reducing-order tests unchanged; partial/cancel/duplicate/frozen-policy cases pass; no new schema or alternative simulator; disposable transaction/recovery checks pass before integration is accepted.

C04 — Recoverable partial initialization

Role: TS lifecycle/reliability engineer. Task. Priority P1.

Exact Codex implementation prompt

Implement only C04 under the Common execution contract in
docs/development/FIRST-WAVE.md. Read backlog/tasks/C04.md and the existing ModeManager
and mode-lifecycle tests.

Make initialization recoverable at the resource-lifecycle boundary. Validate before
side effects. Register cleanup for every stage that may partially acquire resources,
not only after it reports success. On failure stop admission/market feed first,
then attempt all applicable cleanup even if one cleanup throws. Preserve the
original initialization error. Clear failed readiness/config/engine state and allow
a later initialize call to succeed. Preserve the current successful ordering and
the live-disabled guard.

Writable files:
- apps/stock/orchestrator/src/core/ModeManager.ts
- test/integration/mode-lifecycle.test.ts.

Inject failures separately in execution initialization, storage initialization,
strategy restoration and market-feed initialization. Cover cleanup of the failing
stage as well as previously completed stages; cleanup exceptions; successful retry;
no modeChanged success event on failure; live rejection before side effects.

Do not redesign dependency injection, container composition, research isolation or
C06. Do not invent a native dispose API that does not exist. Keep the change focused
on real lifecycle resources and existing methods. Run the C04 commands below and
report outcomes and remaining limitations. Do not commit or create a PR without
explicit approval.

Tests

bun test test/integration/mode-lifecycle.test.ts
bun run typecheck
bun run test:contracts

The existing fixture may load the native TradingEngine; build the assigned worktree addon if required without editing Rust source.

Definition of done: all four failure stages clean up acquired resources, feed cleanup precedes dependent teardown, one cleanup failure does not skip others or mask the original error, retry succeeds, success-path order/live-disabled behavior unchanged, no C06 composition changes.

W01 — Reliable existing web run controls

Role: React asynchronous-state/test engineer. Task. Priority P1.

Exact Codex implementation prompt

Implement only W01 under the Common execution contract in
docs/development/FIRST-WAVE.md. Inspect existing run selection, cancellation,
polling/websocket behavior and native control limitations before editing.

Preserve the existing v2 APIs and persisted run state as authority. Wire cancel
into the detail controls. A202 acknowledgement is not terminal cancellation:
show requested state until persisted cancellation/completion/failure is read.
Use one nonoverlapping poll authority and selection-generation/abort guards so
late status, results, errors or finally handlers for A cannot replace selected B.
Clean subscriptions/timers on selection change and unmount. Websocket messages
invalidate/refetch authoritative state; do not create a second state store.
Fix the existing reconnect reference/cleanup bug or demonstrate a reliable polling
fallback, with tests covering the chosen recovery behavior.

Expose only supported shared execution controls. Hide/disable native-unsupported
server pause/resume/speed controls without implementing those features or a
capability registry. Preserve chart playback and legacy backend endpoints.
Distinguish loading, retriable error, cancelled/failed, successful zero-trade data,
and completed-but-missing result.

Writable files:
- apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx
- apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts
- apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx
- apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts
- apps/stock/web-app/src/hooks/useWebSocket.ts
- test/integration/backtest-run-controls.test.tsx (new)
- apps/stock/web-app/package.json and bun.lock only if one minimal DOM test
  dev dependency is necessary; explain the choice first.

Read backend backtest-v2.service.ts, backtests-v2.routes.ts, websocket/run-updates.ts
and RustBacktestAdapter.ts as context only. Do not change backend source, economics,
provenance, database schemas, queues, strategy contracts or other screens.

Add focused tests with deferred requests, controlled timers and actual component/
hook interactions. Existing analytics-ui tests use server rendering; do not claim
they prove interactions. Reuse Bun/React; no second end-to-end framework. W04 owns
real browser E2E. Run the W01 commands below and report exact results and missing
coverage. Do not commit, push or create a PR without explicit approval.

Context and tests

Read-only backend context:

  • apps/stock/web-api/src/services/backtest-v2.service.ts
  • apps/stock/web-api/src/routes/backtests-v2.routes.ts
  • apps/stock/web-api/src/websocket/run-updates.ts
  • apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts
bun test test/integration/backtest-run-controls.test.tsx test/integration/analytics-ui.test.tsx test/integration/backtest-result-mapping.test.ts test/integration/backtest-workflow.test.ts
bun run typecheck
bun run test:contracts

Definition of done:

  • Deferred getRun(A) and getResults(A), including their error/finally paths, never overwrite B.
  • At most one poll in flight per mounted selection; prior requests cannot publish after switch/unmount.
  • Pending cancellation may be immediately terminal; active cancellation remains requested until persisted acknowledgement.
  • Failure/cancellation never render as success; zero trades and unavailable result are different.
  • Unsupported execution controls absent/disabled; chart playback preserved.
  • Reconnect or polling recovers persisted status; interaction regressions pass.
  • No browser-coverage claim without a browser run; W04 remains the release gate.

Combined wave gate

Independent reviewer checks scope and exact fixtures, then the integrator runs relevant native, TS, contracts and disposable SQL checks on the combined branch. Run full bun run check once at integration, reporting unrelated baseline failures explicitly. No economic/provenance certification is implied by this wave; same-bar timing and canonical Rust ownership/risk remain subsequent work.

The planner records accepted evidence/commit references only when commit authority exists, updates dependencies once integrated, and then offers C02/P01/O01 plus C06 (after C04) and W02 (after W01). F01/D01 also require their ADR approvals.