diff --git a/docs/development/FIRST-WAVE.md b/docs/development/FIRST-WAVE.md new file mode 100644 index 00000000..20da2f08 --- /dev/null +++ b/docs/development/FIRST-WAVE.md @@ -0,0 +1,270 @@ +# 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](backlog/tasks/C01.md). Priority P0. + +### Exact Codex implementation prompt + +```text +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: + +```sh +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: + +```sh +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](backlog/tasks/C03.md). Priority P0. + +### Exact Codex implementation prompt + +```text +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 + +```sh +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](backlog/tasks/C04.md). Priority P1. + +### Exact Codex implementation prompt + +```text +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 + +```sh +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](backlog/tasks/W01.md). Priority P1. + +### Exact Codex implementation prompt + +```text +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` + +```sh +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. diff --git a/docs/development/QUALITY-GATES.md b/docs/development/QUALITY-GATES.md new file mode 100644 index 00000000..014a1b59 --- /dev/null +++ b/docs/development/QUALITY-GATES.md @@ -0,0 +1,72 @@ +# Mandatory quality and integration gates + +All gates apply to the scoped change; unrelated failing baseline checks must be reported, not hidden. No claim of successful validation without the exact command/result. The plan itself does not certify current engine behavior. + +## G0 — Scope and architecture + +Approved plan/task, satisfied dependencies and ADRs, isolated branch/worktree, reserved write locks, clean knowledge of pre-existing changes. No application change beyond the task. Contract changes require the designated contract owner and dependent-task update before implementation. + +## G1 — Economic invariants + +For every canonical financial transition: + +- Equity = cash + marked signed position value; available cash subtracts reservations and cannot be negative under cash policy. +- Every fill/fee ID applies once; conflicting reuse fails. Fees, cash, remaining reservations and positions reconcile after partial/rejected/cancelled orders. +- Owner quantities and derived aggregate basis reconcile; owner realized/unrealized P&L + allocated reserve reconcile to account totals. +- No unsupported short/borrowing, negative quantity, non-finite input, overflow or hidden rounding path. +- All accepted intents (including explicit orders and direct native calls) pass Rust risk; risk hints cannot override account limits. +- No observation/feature/fit artifact is visible before availableAt. Future-suffix mutation cannot change earlier decisions. +- Same versioned data/config/seed/strategy/engine produces the same economic hash; fixed decision traces reproduce identical financial transitions. +- Research sessions cannot modify paper accounts, clocks, subscriptions or checkpoints. +- No-result/undefined risk metric is null/diagnosed, not a fabricated zero. + +Required named regressions: C01 terminal_fee_equity, C03 fee_budget_10000 and computed fee commitments, F02 same_asset_two_owners, F05 same_bar_forbidden and zero available volume, F06 future_suffix_mutation, F08 session-end returns and exposure union. + +Timing/risk policy regressions also include adjacent_open_zero_latency, positive_latency_skips_open, future_ohlcv_does_not_change_open_fill, feature_timeframe_does_not_duplicate_liquidity, daily_close_target_survives_to_open, out_of_session_DAY_rejected and drawdown_halt_survives_rollover_restore. + +## G2 — Durability and recovery + +Existing [order execution](../../test/postgres/order-execution.test.ts), [strategy recovery](../../test/postgres/strategy-recovery.test.ts) and [durable backtest](../../test/postgres/durable-backtest.test.ts) cases are mandatory for touching those boundaries. Inject failures before/after decision, intent, fill, snapshot, result commits and publication. Verify stale attempt fencing, duplicate IDs, pending inputs, cancellation and restore-before-each-decision. Recovery must preserve per-effect context, not just final balances. + +No tests against a development trading account/database. `bun run test:postgres` requires a disposable `stock_bot_safety*` database and dedicated Redis DB15 via `PIPELINE_TEST_DATABASE_URL` and `BACKTEST_TEST_REDIS_URL`. Provision/start containers only when execution and resource use are authorized. + +## G3 — Product/API contracts + +Verify existing v2 consumers and old saved results. Test request schema, immutable snapshots, idempotent submit, errors/status transitions and actor permissions. Browser tests cover navigation/reload, late-response selection races, loading/error/empty states, cancellation acknowledgement and failed/incomplete trials. No client financial simulator. New metric fields have units/null semantics; stored historical rows are not rewritten. + +## G4 — Research integrity and isolation + +Chronological train/validation/test boundaries. When fit artifacts or overlapping forward labels are supported, require retained fit windows and horizon-dependent embargo/purge; R08 initially rejects uncontracted models instead of building a generic ML pipeline. Record trials/selection/holdout access, no preprocessing fit on future windows. AI assertions are separate from evidence. Sandbox malicious/looping code, deny secrets/network/future datasets and prohibit research-token paper/live writes. Paper activation requires independent readiness and human approval. + +## G5 — Performance + +Changes to hot loops, storage layouts, buffers, caches, concurrency or declarative execution include P01 workload measurements, build/host metadata and economic hash equality. A faster but different result fails. No unstable timing assertion in ordinary unit tests; repeated benchmark evidence and explicit release budget are separate. + +## G6 — Repository checks and release cutover + +Existing commands (not all equivalent): + +```sh +bun run test:contracts +bun run typecheck +bun run test:calculations +bun run test:integration +bun run test:native +bun run check +bun run test:postgres +``` + +`bun run check` runs build/types/contracts/tooling/utils/calculations/integration/native/lint and secret audit; it **does not include** disposable PostgreSQL, browser E2E or Python analytics. Run new browser task command after W04; `bun run test:analytics-api` if Python API behavior is touched. Native command is `cargo test -p engine --lib --offline`; missing dependencies are a reported blocker, not a pass. + +Before making canonical Rust the default: all in-scope approved economic fixtures pass, every implemented strategy mode shares the same financial transition semantics/hashes (an unimplemented DSL is not a gate), canonical results render/reopen/reproduce, and paper migration passes fault tests if paper is switched. Keep a versioned rollback route for software deployment, but never silently downgrade a failed run's economics or mutate accounts between incompatible schemas. + +Independent reviewer signs off G1/G2 for financial work; integration owner runs combined branch gates. Only then may planning mark done with commit and evidence references. + +## Revised gate interpretation + +- Implementation dependencies block coding/integration. `release_gates` block enabling the complete feature, not integrating a tested component; this avoids the F05-matcher/F06-replay deadlock. Conditional gates apply only when the named feature is enabled. +- C03 deliberately preserves legacy reducing/short financing semantics; canonical cash-only invariants apply to F04 onward. No new borrowing claim is made for the interim patch. +- Exact owner remaining cost/residuals and per-strategy RNG/decision cursors are tested. Rounded display average is never reconstructed into authoritative basis. +- Determinism is scoped to controlled inputs and pinned supported artifacts/platform. Trace replay and strategy recomputation are tested separately; no finite conformance suite proves arbitrary code deterministic. +- Fixes need no switch to restore a bug. Compatibility adapters apply only to actual schema/engine cutovers and historical readers. +- Before native integration tests, build the addon from the assigned worktree and verify resolution/hash. Generated native artifacts are not authored changes. Shared writable build output or workspace symlinks pointing at another agent's source invalidate isolation. diff --git a/docs/development/REVIEW.md b/docs/development/REVIEW.md new file mode 100644 index 00000000..f85fc836 --- /dev/null +++ b/docs/development/REVIEW.md @@ -0,0 +1,80 @@ +# Independent skeptical backlog review + +Reviewed against repository baseline `b7aeca4`, 2026-10-22. **Planning changes only.** Evidence below is code inspection, not a claim that tests/benchmarks ran. Verified = directly visible code/plan behavior; Likely = engineering consequence not benchmarked; Needs investigation = requires execution or product approval. + +## Verdict + +The direction is sound, but the original backlog made several optional optimizations prerequisites, sequenced financial ownership after the ledger, and left agents to resolve monetary/timing semantics. Those are more important than adding abstractions or increasing task count. + +Keep the modular monolith, TypeScript authoring and current product/durability infrastructure. Establish one small Rust financial kernel with two adapters: resident research sessions and transactional paper transitions. Do not force statistical reports, orchestration or every indicator into Rust. + +## Ranked findings and dispositions + +| Severity / evidence | Problem | Revision and acceptance consequence | +| --- | --- | --- | +| Critical / Verified contract gap | Rounded average price was insufficient as authoritative cost basis; partial disposals could create residual money | ADR-002/F02 store remaining cost amount; partial proportional allocation, exact final residual. Fixture cost5/quantity3 must release5 exactly | +| Critical / Verified plan contradiction | F02 built aggregate positions before F03 introduced ownership | Merge F03 into F02. Owner books exist at first fill; A/B attribution and aggregate reconciliation are initial ledger tests | +| Critical / Verified boundary gap | Paper pure snapshot API could imply full serialization/cloning per research event | ADR-005 specifies one internal apply kernel. Resident research mutates private state directly; paper stages and persists within existing SQL transactions. Preserve ordered effects/checkpoints | +| Critical / Verified ambiguity | Arbitrary TS callback determinism was treated too broadly; barrier state/RNG/intent semantics were incomplete | ADR-004/F07/S01 use progress/decisionBatch/complete, same ledger revision for all callbacks, staged state and per-strategy RNG; exceptions fail the attempt; no target/order mixing in v1. Trace replay is not proof of arbitrary-code determinism | +| High / Verified scope conflict | C03 mixed a narrow fee bug with a new financing policy | Keep legacy nonreducing gross-capital model/reducing exemption; add unpaid remaining fees only. Canonical cash reservations belong to F04 | +| High / Verified dependency contradiction | F05 acceptance needed F06 replay, while F06 depended on F05 completion | Matcher tests complete F05; replay-dependent release assertions belong to F06. Release gates are separate from implementation prerequisites | +| High / Verified timing gaps | Multi-timeframe feeds could duplicate execution liquidity; DAY targets and account risk-session clock were ambiguous | ADR-003/F04–F06 require one execution series per instrument, feature-only additional frames, explicit DAY/target expiry and account calendar; next-open and persistent halt fixtures | +| High / Verified avoidable work | A new legacy research runtime would be replaced again after Rust cutover | Narrow C06 to fail-closed composition: shared paper accepts existing isolated native research only; standalone legacy TS research cannot initialize/activate paper. Preserve current busy guard | +| High / Verified artificial prerequisites | Shared cache, all builtins, resident dataset reuse and reporting blocked useful strategy/paper/batch work | Remove D04→S01, F08→S03, P03→P04; S02 ports one SMA first. Actual isolation and provenance gates remain | +| High / Verified repeated work | F06 introduced replay then P02 replaced its queue | Merge P02 into F06: sorted immutable event cursor once; deterministic ties and scaling evidence | +| High / Verified product sequencing | Workspace/catalog/picker completion blocked independent experiment/backend/AI work | Remove unrelated UI prerequisites. Keep W04 browser coverage as release gates; R06 offers summary projections, R09 only gates regime panels on S05 | +| High / Verified missing dependency | Validation artifacts/findings referenced R03 despite experiments no longer depending on research metadata | R08 persists immutable experiment-owned reports; R09 save/link-finding requires R03 only when enabled. Basic validation remains independent | +| Medium / Verified ambiguous evidence | Publishing, retrying and walk-forward semantics allowed inconsistent interpretations | R01 distinguishes idempotent publish from intentional revision; R06 retries use fenced attempts; R08 declares reset-segment capital/state and excludes warmup from performance | +| Medium / Verified excess infrastructure | Generic capabilities, metric-validation store, migrations framework and blanket bug toggles could grow from vague criteria | W01 uses existing APIs; R03 references retained metric paths; O01 locks existing migration transaction; no toggles restoring known defects | +| Medium / Likely optimization overreach | Universal caching/native analytics and arbitrary DSL speed thresholds increased work before measurement | F08 reuses reviewed TS statistics; five optional tasks stay conditional; P01 measures existing paths only | +| Needs investigation | Actual callback cost, resident-cache benefit, decimal throughput, platform bitwise feature reproducibility | Measure P01 then instrument F06/F07/S01/P04; no invented speedup/throughput claims | + +## Repository anchors behind the decisions + +- Terminal liquidation follows the last mark: [engine.rs:135](../../apps/stock/engine/src/backtest/engine.rs#L135); result reads the curve: [simple_results.rs:308](../../apps/stock/engine/src/backtest/simple_results.rs#L308). C01 remains a narrow current defect fix. +- Legacy financing checks gross exposure without unpaid fees: [model.ts:234](../../apps/stock/orchestrator/src/execution/model.ts#L234). Fill-time policy and existing TIF handling: [SimulationExecution.ts:92](../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L92), [line168](../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L168). C03 must not replace that entire model. +- Initialization readiness precedes a shutdown early return: [ModeManager.ts:33](../../apps/stock/orchestrator/src/core/ModeManager.ts#L33), [line157](../../apps/stock/orchestrator/src/core/ModeManager.ts#L157). C04 owns lifecycle, C06 owns composition. +- Shared TS research preparation changes ModeManager: [container.ts:101](../../apps/stock/orchestrator/src/container.ts#L101). The existing [NativeBacktestWorker](../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts) and [fenced dataset runner](../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190) are reusable. +- Historical events use repeated queue insertion: [backtest/mod.rs:138](../../apps/stock/engine/src/backtest/mod.rs#L138). Implement efficient traversal during replay replacement, not in a later task. +- Reviewed reporting math already exists: [return-statistics.ts:24](../../libs/calculations/src/analytics/return-statistics.ts#L24). Reuse it over authoritative ledger/session projections instead of rewriting statistics in Rust. +- Websocket close clears the reference before a reconnect equality check: [useWebSocket.ts:124](../../apps/stock/web-app/src/hooks/useWebSocket.ts#L124). Existing [detail controls](../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L379) and [durable submission](../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211) need focused repair, not replacement. +- Migration checking is outside the application transaction: [migration-runner.ts:59](../../apps/stock/web-api/src/migrations/migration-runner.ts#L59). O01 must acquire the lock and check/apply on the same client. +- Preserve transaction/recovery behavior: [StrategyRecovery.ts:151](../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151), [Postgres execution tests](../../test/postgres/order-execution.test.ts), [strategy recovery tests](../../test/postgres/strategy-recovery.test.ts). + +## Scope accounting + +| Disposition | IDs | Rationale | +| --- | --- | --- | +| Merge into financial contract | C05 → F01 | Economic fixture corpus and protocol evolve together; no separate expected-failure harness project | +| Merge into owner-aware ledger | F03 → F02 | Avoid migrating a ledger immediately after writing it | +| Merge into dataset v2 | D03 → D01 | Availability, coverage and eligibility are one schema migration | +| Merge into replay | P02 → F06 | Implement traversal once | +| Conditional after measurements | D04, P03, P05, P06 | Shared features, cross-trial reuse, large details, DSL respectively | +| Conditional after real operational need | O02 | Mandatory run/paper diagnostics already belong to W01/F07/S04 | + +Result: **43 scheduled + 5 conditional work items**, with four merged traceability records. This does not promise a percentage reduction in engineering time: larger surviving tasks still contain the essential tests. Eliminated work is duplicated migration, needless porting, optional framework scope and artificial waiting. + +## Financial/strategy boundary that agents must not reinterpret + +1. Rust accepts validated intent envelopes, applies risk/matching/ledger transitions and emits owned effects. +2. TS chooses strategy logic and allocation preferences, not cash/P&L/fill calculations. +3. All due callbacks see one immutable account revision; admission order is stable and declared. +4. Strategy state and RNG are staged at barriers. A risk rejection is a committed decision outcome; a thrown callback is an attempt failure. +5. Paper SQL remains durability authority; Rust remains financial authority. Do not publish uncommitted staged effects. +6. One execution source per instrument; higher-timeframe observations are features, not extra liquidity. +7. Deterministic financial replay uses fixed inputs/decisions. Strategy recomputation additionally requires controlled APIs and pinned runtime/artifacts; same-process arbitrary JS is not a sandbox. +8. Statistical analytics can remain TS without being a competing simulator. Reports must consume canonical ledger/session values, never reconstruct a second account. + +## Revised ordering + +Critical path: F01 → F02 → F04 → F05 → F06 → F07 → S01 → S02 → R05 → R06. D01/P01 join replay, C02 joins NAPI, F08 and immutable retained artifacts join R05. S03 branches from S01/C06 without waiting for report/UI work. Parallel trials P04 need canonical sessions/experiments and measurement, not caches. AI A01/A02/A03 need bounded APIs/isolation/validation, not a browser IDE. + +First wave: **C01, C03, C04, W01**. See [exact prompts and definitions of done](FIRST-WAVE.md). Use three implementation slots and a separate review/integration role. All four can be assigned independently; rotate the fourth to preserve review capacity. + +## Remaining decisions and limitations + +Approve monetary rounding/long-only scope, execution timing/terminal policy and AI trust model before dependent tasks. First-wave fixes do not settle those policies and do not make the legacy backtester suitable for performance claims. + +No application tests or benchmarks were run for this review. Source inspection establishes the cited control-flow issues; numerical acceptance fixtures are specifications for implementation. The plan must be revalidated if source/contracts change before execution. + +Planning validation passed: 75 planning files; 52 unique task IDs (43 scheduled, 5 conditional, 4 merged); 77 implementation edges with no cycle; no scheduled dependency on deferred/merged work; first-wave readiness; task/manifest dependency consistency; 749 relative link references and source line bounds; whitespace checks. Git changes remain confined to docs/development, HEAD remains b7aeca4, and execution_authorized remains false. Independent read-only core/product reviews found no remaining first-wave blocker; the product review's report-storage dependency gap was corrected as described above. diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md new file mode 100644 index 00000000..5b7f6394 --- /dev/null +++ b/docs/development/ROADMAP.md @@ -0,0 +1,100 @@ +# Revised development roadmap + +Baseline `b7aeca4` · reviewed 2026-10-22 · **First-wave implementation authorized by the owner; see manifest execution_scope** + +Authorization update: the owner requested a planning commit and implementation start. Execute only C01/C03/C04/W01 now; later economic/timing/trust-model decisions remain gated. Historical review statements describe the planning phase, not current authorization. No push, PR, trading operation or subsequent implementation commit is authorized. + +## Strategy and review outcome + +Use TypeScript for strategies, research and the web product; one Rust kernel owns money, risk, matching and replay. Preserve durable decisions/checkpoints, transactional execution, frozen datasets, reviewed calculations and failure-oriented tests. + +The skeptical review consolidates **52 separate task definitions into 43 scheduled tasks plus 5 conditional tasks**. Four old IDs remain merged redirects, not extra work. This is a smaller delivery plan, not a smaller correctness standard. See [review findings and dispositions](REVIEW.md), [complete index](backlog/README.md) and [canonical manifest](backlog/manifest.json). + +The existing web workbench improves during engine migration. Legacy results remain labelled; fixing controls or terminal valuation does not make same-bar economics trustworthy. C06 blocks shared-runtime legacy research rather than building another soon-to-be-retired simulator runtime. + +## Decisions to approve + +| Decision | Direction | Approval | +| --- | --- | --- | +| [ADR-001](architecture/decisions/001-ownership.md) | TS product/strategy code; Rust financial authority; retain monolith and workers | User-mandated | +| [ADR-002](architecture/decisions/002-financial-policy.md) | Maintained checked decimal; 8-place half-up postings; authoritative remaining cost; owner books from day one; initial cash-funded long-only account | Explicit economic approval | +| [ADR-003](architecture/decisions/003-time-and-datasets.md) | Availability/event phases; open-only next-interval matching; explicit zero-latency convention; mark-open terminal policy; account risk-session clock | Explicit execution/data approval | +| [ADR-004](architecture/decisions/004-strategy-boundary.md) | NAPI pull sessions in existing workers; tagged decision barriers; IPC for untrusted code; no embedded JS | Plan approval | +| [ADR-005](architecture/decisions/005-durable-cutover.md) | One Rust transition kernel; resident research state; private staged paper state under existing SQL transactions | Plan approval | +| [ADR-006](architecture/decisions/006-research-product.md) | Existing API/queue/database; immutable versions, provenance and evidence retention; no laboratory framework | Plan approval | +| [ADR-007](architecture/decisions/007-ai-boundary.md) | Isolated untrusted code, research-only permissions/budgets; human-only paper promotion; live disabled | Explicit trust-model approval | +| [ADR-008](architecture/decisions/008-performance.md) | Measure actual paths; cursor replay and bounded trials; caching/DSL only when measured | Plan approval; later optimization go/no-go | + +Long-only is a proposed first canonical model, not deletion of short history or a silent change to current paper accounts. If first-release shorts are required, approve borrowing/margin policy and fixtures before F01. C01/C03/C04/W01 do not depend on those unresolved economic choices. + +## Milestones + +| Milestone | Tasks | Exit criterion | +| --- | --- | --- | +| M0: safe interim behavior | C01/C02/C03/C04/C06; O01; P01 | Scoped terminal/funding/input fixes; failed init cleans up; shared-runtime research rejected; migration lock and honest baseline measurements | +| M1: usable current workbench | W01–W04 | Save, submit, cancel, inspect and reopen tested in browser; unsupported controls hidden; legacy economic limitations visible | +| M2: canonical Rust/TS research | F01/F02/F04–F08, D01, S01/S02; R01/R10/W03/C06 then R05 | Owner-aware finance, deterministic replay, one TS strategy and retained input provenance work through durable runs | +| M3: useful research product | R02/R03/R04/R11/R12 | Catalog/workspace/dataset selection and original reproduction; metadata/UI proceed alongside engine work | +| M4: batch research and validation | R06–R09, P04; S05 when ready | Bounded sweeps, summary comparisons, OOS/reset-segment walk-forward and measured worker scaling; regime panels only with S05 | +| M5: paper parity and AI research | S03/S04, A01–A04 | Recovery parity, operator readiness, isolated bounded AI experiments and evidence-linked human paper promotion | +| M6: remove duplicates / optional speed | S06; conditional D04/P03/P05/P06/O02 | Retire duplicate economics only after cutover proof; optional work requires demonstrated need | + +Rows are outcomes, not a sequential waterfall. S03 does not wait for research UI or statistical reporting; basic experiments do not wait for regime models or feature caches. + +## Critical path and parallel lanes + +```mermaid +flowchart LR + F01[Contract + economic fixtures] --> F02[Owned ledger] --> F04[Risk + reservations] --> F05[Matcher] + F05 --> F06[Deterministic cursor replay] + D01[Availability-aware eligible datasets] --> F06 + P01[Existing-path measurements] --> F06 + F06 --> F07[Bounded NAPI sessions] --> S01[TS decisions] --> S02[One SMA] + C02[Boundary integrity] --> F07 + F06 --> F08[Canonical projections + reviewed TS statistics] + S02 --> R05[Durable canonical runs] + F08 --> R05 + PRODUCT[Versions / retained artifacts / safe submission] --> R05 + C06[Runtime containment] --> R05 + R05 --> R06[Bounded experiments] --> P04[Measured parallel trials] + R06 --> R08[Chronological validation] + R06 --> A01[Research authorization] --> A02[Untrusted code isolation] + R08 --> A03[AI evidence loop] + A02 --> A03 + S01 --> S03[Durable Rust paper adapter] +``` + +The full [dependency graph](backlog/dependencies.mmd) includes all code and decision gates. Solid task edges are implementation prerequisites. Dotted task edges are release/conditional gates, not blockers to integrating component work. + +After approval, run one financial-core owner alongside one web/product owner and one data/benchmark/metadata owner. Serialize shared DTOs, migration registry, worker protocol and actual overlapping files. Core tasks F01/F02/F04/F05 must not be split among agents simultaneously. + +## First wave: four independent assignments + +Exact copy-ready prompts, paths, commands and completion criteria: [FIRST-WAVE.md](FIRST-WAVE.md). + +| Task | Why now | Ownership / unlock | +| --- | --- | --- | +| [C01](backlog/tasks/C01.md) | Final native equity currently omits liquidation costs | Legacy Rust engine/results only; preserves a known arithmetic fixture for migration | +| [C03](backlog/tasks/C03.md) | Existing gross-capital guard ignores fee liability | TS execution model only; safer interim paper behavior without a new financing model | +| [C04](backlog/tasks/C04.md) | Partially initialized runtime can retain resources | ModeManager lifecycle only; unlocks C06 containment | +| [W01](backlog/tasks/W01.md) | Current user-facing cancellation/status can mislead | Frontend controls/hooks only; unlocks W02 and the tested workbench | + +Recommend **3 simultaneous implementers**, reserving one slot for coordination/independent review. Start C01 + C03 + W01; rotate C04 into the first freed slot, or start C04 first if runtime containment is the immediate operational need. These four have no mutual code dependencies and disjoint writable files. Four concurrent implementers are technically possible but not recommended without separate review capacity. + +Next-ready work: C02, P01 and O01; F01/D01 after their ADR approvals. W02 follows W01 because they edit the same detail page, not because it requires the new engine. + +## Deferred and rejected + +Conditional: shared feature cache D04; cross-trial resident datasets P03; large-detail pagination/storage P05; tiny DSL P06; expanded cross-service monitoring O02. Each has a measured/real-need trigger and is not a prerequisite for scheduled work. + +Deferred economics: short/margin/borrow, multicurrency, full corporate actions, intrabar stops/OCO, detailed market impact and live brokers. Reject unsupported datasets/orders explicitly. The model is not generalized by pretending unsupported behavior exists. + +Later product/research: embedded IDE, advanced optimizers, generalized ML training, Monte Carlo significance tooling. Basic immutable versions, chronological validation and evidence links are not deferred. + +Rejected: competing TS/web simulators, wholesale Rust rewrite, hand-written decimal engine, new service/message bus/workflow framework, generic signal DSL, compatibility switches that re-enable defects, deleting reviewed calculations because they are currently unused. Keep existing local environment-file policy; no WCAG or cosmetic-dashboard scope here. + +## Execution governance + +Only [manifest.json](backlog/manifest.json) owns status/assignment/dependencies. [Task files](backlog/README.md) own scope/acceptance. Read the reusable [implementation](agents/implementation.md), [review](agents/review.md), [integration](agents/integration.md), [planning](agents/planning.md) briefs and [quality gates](QUALITY-GATES.md). + +Approval of planning artifacts is not permission to commit, push or create PRs. No application changes, runtime benchmarks or application-test pass claims are made by this revision. diff --git a/docs/development/agents/implementation.md b/docs/development/agents/implementation.md new file mode 100644 index 00000000..3cb9bd0d --- /dev/null +++ b/docs/development/agents/implementation.md @@ -0,0 +1,26 @@ +# Reusable implementation-agent brief + +This is a role instruction, not a new agent framework. It authorizes nothing on its own. + +## Invocation packet + +Planner supplies: task ID/file, manifest revision, approved ADR IDs, base commit, branch/worktree path, reserved file locks, predecessor merge commits, acceptance scenarios, baseline failures and authorized test/commit/PR permissions. + +## Procedure + +1. Confirm global execution authorization, task readiness/claim and architecture approval. Read the task, relevant ADRs, quality gates and actual code. If evidence has drifted, report it before changing scope. +2. Work only in the assigned worktree. Preserve user/unrelated changes. Do not edit canonical task status or shared contracts owned by another agent. +3. Reproduce the defect or establish the current behavior. Implement the smallest cohesive change and its regression tests. Keep useful calculations, fixtures and recovery behavior. +4. Use the approved financial core and contracts. Do not create fallback accounting, change rounding/clock/ownership policy or expose broker execution to strategies. +5. Run mandatory task tests plus relevant gates; use disposable DB/queues. Record exact commands and failures. A missing dependency or skipped test is not success. +6. Review your own diff for unrelated edits, stale documentation, artifacts/secrets and backward compatibility. +7. If commits/PRs are authorized, produce a focused commit and PR against the assigned integration branch, referencing task ID, dependency commits, tests and limitations. Otherwise leave changes uncommitted and hand off a diff; do not infer permission. +8. Request independent review. Do not merge yourself or mark done. + +## Stop / handoff conditions + +Architecture ambiguity, blocked dependency, unexpected shared-contract change, failing economic invariant, unavailable isolation or irreconcilable baseline drift: report task ID, evidence, attempted checks, smallest decision needed and safe remaining work. Do not silently widen scope. + +Unfinished handoff includes branch/worktree, base and latest commit or uncommitted diff, files touched, tests run, failing case, fixture expectations and next concrete step. Do not discard unfinished work. + +First-wave prompts and exact writable/read-only boundaries are in [FIRST-WAVE.md](../FIRST-WAVE.md). Merged IDs are not work items. Do not add a compatibility toggle to preserve a correctness defect, or populate missing benchmark counters with zeros. diff --git a/docs/development/agents/integration.md b/docs/development/agents/integration.md new file mode 100644 index 00000000..074dad92 --- /dev/null +++ b/docs/development/agents/integration.md @@ -0,0 +1,30 @@ +# Reusable integration-agent brief + +One integrator owns the shared integration branch and canonical contract sequencing. No two agents modify tightly coupled canonical financial contracts concurrently. The first-wave Rust legacy terminal fix and TS legacy fee guard are disjoint corrections, not concurrent design of the new contract. + +## Isolation and claim rules + +After owner approval, planner atomically assigns one task and write locks in the canonical manifest on the coordination branch. Create a branch/worktree from the recorded integration commit, for example `plan/C01-terminal-equity` and a sibling worktree. These are examples for later execution, not commands run by this planning task. + +Each implementation worktree edits only its code scope, never task status. The planner alone writes status/assignment changes; implementation PRs cannot overwrite a stale manifest. Acquire both symbolic locks and concrete-file ownership. SQL migration numbering/registry is assigned by the integrator. + +## Integration sequence + +1. Require dependencies merged and ADRs approved. Shared contract tasks merge before their consumers; no “probably compatible” simultaneous F01/F02/F04 changes. +2. Require independent review and exact task acceptance evidence. +3. Rebase/merge onto current integration base in dependency order; handle textual and semantic conflicts together. For contract overlap, pause a branch and let the contract owner resolve the design—never choose a side blindly. +4. Run relevant combined native/TS/SQL/browser gates, plus economic/decision hash fixtures. Test mixed old/new stored data where compatibility is claimed. +5. Update task completion through planning owner only after tests pass on the integrated commit. Record commit, review and gate references. +6. Recompute readiness and release locks. Do not unlock downstream implementation merely because a PR exists. + +PR creation, commits and merges require explicit execution authorization; this plan does not grant it. No force-reset of user work. Rollback uses a deliberate compatible deployment/commit, not destructive rewriting of historical financial state. + +## Safe concurrency + +Recommend **3 implementation agents maximum**, with one of them holding the single financial-core lane. A fourth concurrent slot can be a read-only reviewer when available; otherwise rotate review between implementation batches. Do not independently spawn nested implementation teams. + +Typical parallel lanes: Rust financial owner; web/product owner; data/tests/benchmark or metadata owner. See [FIRST-WAVE.md](../FIRST-WAVE.md) for the four exact independent assignments; rotate the fourth through the three implementation slots. Shared API DTOs, `libs/core/types`, worker protocol, run service and SQL registry serialize when they overlap—even if task lock names differ. + +## Failed integration + +Leave task in review/blocked with explicit failing combined test and owner. Preserve worktree and artifacts. No status “done except integration.” Paper/live state is never used as an integration fixture. diff --git a/docs/development/agents/planning.md b/docs/development/agents/planning.md new file mode 100644 index 00000000..d12dc951 --- /dev/null +++ b/docs/development/agents/planning.md @@ -0,0 +1,23 @@ +# Reusable planning-agent brief + +Maintain the backlog, not application code. Read manifest, completed/reviewed changes, approved ADRs and newly discovered evidence. + +## Source of truth and state + +Only `backlog/manifest.json` owns scheduling state, dependencies, assignments, priorities and write locks. Task files own behavior/scope/acceptance. Roadmap/index/graphs are views; update them after metadata changes, never use them as a competing status board. + +Merged IDs are traceability redirects and may never be claimed. Deferred optimization requires its measured activation decision. `dependencies` gate implementation; `release_gates` gate feature activation, not component integration/done. + +States: ready -> claimed -> in_progress -> review -> done. blocked is for an actual unmet code/approval/environment prerequisite with a recorded reason; deferred requires its explicit future gate. All tasks also obey global `execution_authorized`. Initial ready means code-ready **after plan approval**, not permission to act. + +## Work cycle + +1. Check repository/task evidence drift and dependency completion. A task is ready only when required commits are integrated, ADRs approved and resources available. +2. Select a small ready batch with disjoint actual files and locks; prioritize economic correctness and early web value. +3. Assign owner/worktree/base/lock metadata in one serialized coordination update. Supply the implementation invocation packet. +4. Track blockers with evidence, smallest unblock decision and safe alternatives. Do not call a difficult task blocked merely to abandon it. +5. On accepted integration, record commit/review/test references, mark done and recalculate the DAG. On scope split, create a stable new ID and update edges; do not reuse IDs. +6. For an ADR change, obtain owner approval and identify every affected contract/task before reopening work. +7. Keep the first-wave/dependency views consistent; validate unique IDs, all references, no cycles, valid statuses and approved decision gates. + +Do not launch coding agents, commit, open PRs or change application files unless the owner has separately authorized execution. P06 remains deferred until the measured gate and owner go/no-go are recorded. diff --git a/docs/development/agents/review.md b/docs/development/agents/review.md new file mode 100644 index 00000000..ccddfbe1 --- /dev/null +++ b/docs/development/agents/review.md @@ -0,0 +1,21 @@ +# Reusable independent review-agent brief + +Review the assigned task/approved ADRs and implementation diff independently. Do not implement fixes or approve your own financial change. + +## Required review + +- Re-derive financial fixture expectations; do not accept the engine output as its own oracle. +- Inspect time availability, same-bar execution, pending reservations, fees/rounding, owner basis, risk bypasses, ordering, partial failure and terminal marking. +- Check crash boundaries, idempotent identities, restore-before-decision and per-effect state. Native state must not advance past a rolled-back SQL transaction. +- Check API/schema compatibility, legacy provenance, data immutability and loading/error/empty UX. New browser pages must use the same API/core. +- Check sandbox boundary, actor permissions and no AI-to-live path. +- Look for unnecessary abstractions, duplicated calculation/simulation, unjustified deletions and scope creep. +- Re-run focused tests independently where available. Verify benchmark comparison uses identical semantics and inputs. + +## Output + +Return Accept / Changes requested / Blocked, with severity, file/line evidence, violated task criterion and required test. State what was and was not run. Approval requires all in-scope mandatory gates or an explicit owner-approved waiver that does not waive financial correctness. + +A reviewer may suggest a future task but cannot silently amend ADRs or expand this PR. Communicate contract-impacting findings to integration/planning owner. + +Check that remaining-cost residuals, target/order-mode exclusivity, immutable decision barriers and RNG restore are explicit. Distinguish component tests from release gates; do not require later UI/metrics/cache work to approve an independently correct component. Do not call statistical reporting outside Rust a competing simulator when it only consumes authoritative financial outputs. diff --git a/docs/development/architecture/benchmarks.md b/docs/development/architecture/benchmarks.md new file mode 100644 index 00000000..95263830 --- /dev/null +++ b/docs/development/architecture/benchmarks.md @@ -0,0 +1,38 @@ +# Benchmark plan: staged measurement, one small harness + +P01 starts with available code. No application benchmark was run during this planning review. + +## Stage0: available now + +Extend [benchmark-dataset.ts](../../../scripts/benchmark-dataset.ts) and add a small research driver: + +- Fresh process/addon startup; existing native load/run/result parse. +- Single asset at1k/10k/100k bars; multi-asset fixture with equal-time events. +- Several repeated parameter trials using an existing supported native strategy. +- Dataset preparation/repeated prepared-object handoff measured separately from native/IPC work. + +Record host/runtime/source/native-binary hash, seed, dataset/config identity, raw elapsed samples, returned bytes and RSS. Fresh-process and reused-input results are different; neither implies cross-trial resident data. Report startup/load/run/parse phases only where observable. DB/queue/allocations/TS-callback metrics are explicitly unavailable until their owning tasks instrument them. + +Use deterministic fixtures and an economic-field hash excluding UUIDs, logs and wall time. Existing bad economics remain labelled limitations; benchmark parity does not validate alpha or accounting. + +## Extend when the capability exists + +| Owner | Added workload/counter | +| --- | --- | +| F06 |1k/10k/100k replay scaling; tie-order/hash equality; logging cost | +| F07/S01 | Tagged-step and real TS decisions; crossings, context bytes, decision time | +| R06 | Summary/result storage/query latency and batch queue wait | +| P04 |1/2/4 isolated workers; trials/s, tail latency, total RSS and hash equality | +| P03, if justified | Load-count reduction and resident dataset state-reset/lifetime | +| D04, if justified | Same-feature request count and incremental/batch parity | +| A02 | Restricted strategy IPC cost and timeout cleanup | + +Later representative profiles:100 assets x10k observations;10 strategies over20 assets;100–1000 trials; high-turnover100k-fill result. Run them only when those semantics exist. Do not build missing features to make P01's benchmark matrix appear complete. + +## Protocol + +Short measurements: warmups plus repeated raw samples, medians/p95 where sample count supports them. Long sweeps: at least3 measured runs with load disclosed. Release native builds for performance; verify the actual addon hash. Cold OS/DB caches are claimed only when controlled; do not disrupt shared services to force them. + +Compare equal economic/decision policies, inputs and outputs. Report bars/s for replay and end-to-end separately, trials/s, CPU time where available, RSS/bytes and parallel efficiency. Establish budgets from variance, not invented throughput targets. No timing-flaky unit tests or arbitrary dataset caps. + +Optimization approval must estimate time saved across real research workloads against implementation/maintenance cost. The declarative path is optional, not a milestone every project must reach. diff --git a/docs/development/architecture/decisions/001-ownership.md b/docs/development/architecture/decisions/001-ownership.md new file mode 100644 index 00000000..86db1e46 --- /dev/null +++ b/docs/development/architecture/decisions/001-ownership.md @@ -0,0 +1,25 @@ +# ADR-001 — Application versus financial authority + +Status: **user-mandated direction**; the detailed backlog still awaits approval. + +## Selected approach + +TypeScript owns product/application logic, strategy authoring, signal/regime composition and research orchestration. Rust owns authoritative financial state transitions, deterministic replay, matching and risk. Keep a modular monolith, existing durable dispatch/runner, shared public contracts and existing web product. + +## Rationale and evidence + +Current TypeScript [applyFill](../../../../apps/stock/orchestrator/src/execution/model.ts#L108) and Rust [process_fill](../../../../apps/stock/engine/src/backtest/engine.rs#L426) are competing authorities. Consolidation removes behavioral drift; moving all authoring to Rust would reduce flexibility without proving a throughput benefit. + +## Alternatives and tradeoffs + +- All TypeScript: simpler language footprint, conflicts with required native financial authority. +- All Rust: less runtime crossing, conflicts with flexible TS development goals. +- Separate services per stage: more operational overhead without demonstrated need. + +## Migration consequences + +Preserve all existing recovery/data/registry/calculation behavior. Keep explicit legacy readers and paths until cutover tests pass, but never auto-fallback from a failed canonical run to legacy economics. Gates: F01–F08, S01–S03, R05; delete duplicate execution only in S06. + +## Skeptical revision + +Do not port reviewed statistical reporting to Rust solely for language uniformity. F08 consumes Rust financial postings/session marks through one existing TS calculation path; this is analysis, not competing cash/fill accounting. C06 uses a fail-closed legacy composition guard instead of building another soon-to-be-retired research runtime. One canonical SMA path is sufficient for initial cutover. diff --git a/docs/development/architecture/decisions/002-financial-policy.md b/docs/development/architecture/decisions/002-financial-policy.md new file mode 100644 index 00000000..83f36ef6 --- /dev/null +++ b/docs/development/architecture/decisions/002-financial-policy.md @@ -0,0 +1,27 @@ +# ADR-002 — Money, cost basis, ownership and funding + +Status: **owner approval required**. This revision replaces the unimplemented half-even/rounded-average proposal; it does not alter current code. + +## Selected minimal policy + +- Use a maintained checked decimal implementation (for example a pinned Rust decimal crate), not hand-written fixed-point arithmetic. Monetary postings and quantities use8 fractional digits initially. Explicit half-up/away-from-zero tie rounding matches the current TS `amount()` policy; tick/lot rules may be stricter. Reject unsupported precision, non-finite values and overflow. +- Decimal strings are financial command/snapshot transport. Market observations and statistical feature arrays need not become strings or be copied through the boundary per observation. +- **Remaining cost amount is authoritative. Average price is derived.** For a partial disposal release the proportional basis rounded at posting precision; the final disposal releases the exact remaining residual. Example: cost5 for3 shares must release exactly5 over all sales, not5.00000001 reconstructed from average1.66666667. +- Store owner-keyed quantity/cost/P&L from the first ledger implementation (F02 absorbs F03). Account quantities/basis aggregate those books. Fees are explicit separate postings; initial unallocated capital belongs to a reserve owner. Broker suspense handling is deferred with broker integration, not a generalized suspense-account subsystem now. +- First project-gated model is single-base-currency cash-funded long-only, no borrowing. Fee-inclusive reservations and fill-time checks live in Rust. Adverse gaps reject unaffordable remaining quantity rather than borrow or silently resize. +- No internal crossing/netting. Stable owner/intent admission priority; one owner cannot sell/cancel another's inventory. A strategy instance selects target OR explicit-order mode; mixing modes rejects in v1. +- Account daily-loss reset follows one declared account risk-session calendar, not each asset's venue or UTC date. Explicit boundary commands roll only the daily baseline. Drawdown peak/halt survives sessions and restore; authorized operator reset records its baseline. + +## Legacy correction is different + +C03 only adds unpaid-fee liability to the **existing non-reducing gross-capital test**. It preserves existing short/reducing behavior and8-place rounding. It is not the new cash-only account model and makes no claim to eliminate all debt in legacy short covers. + +## Evidence / alternative costs + +[TS amount/cost basis](../../../../apps/stock/orchestrator/src/execution/model.ts#L81), [aggregate owner attribution problem](../../../../apps/stock/orchestrator/src/execution/model.ts#L108), [native fill broadcast](../../../../apps/stock/engine/src/backtest/engine.rs#L489). Exact postings fix arithmetic, not market modeling. A full multicurrency double-entry/margin/borrow engine is not required for v1. + +## Migration and tests + +F01 owns scalar/command fixtures; F02 implements owned books once; F04 owns funding/risk. Preserve old results; account conversion must reconcile quantities, cost residuals, cash and fees or refuse an implicit migration. No switch restoring a correctness defect. Required tests: positive/negative rounding ties, partial/final residual, A/B owner basis, duplicate fees, overflow and persisted daily/drawdown state. + +“Project-gated” means the specified regression tests passed on declared modeling policies. It is not independent certification, proof of alpha, a broker guarantee or a generic certification framework. diff --git a/docs/development/architecture/decisions/003-time-and-datasets.md b/docs/development/architecture/decisions/003-time-and-datasets.md new file mode 100644 index 00000000..f639fb40 --- /dev/null +++ b/docs/development/architecture/decisions/003-time-and-datasets.md @@ -0,0 +1,35 @@ +# ADR-003 — Information availability and execution timing + +Status: **owner approval required**. + +## Selected policy + +- Dataset v2 records instrument, timeframe, interval start/end, event time, availability time and deterministic source sequence; dates and calendars are versioned. Replay derives a separate open-only execution event at interval start, exposing only open/time, and a completed-bar observation at its availability time. The full stored OHLCV row is never exposed at its open. +- A completed-bar decision cannot trade at its own close. Default bar mode fills at the **next eligible open**; quote mode uses the next eligible observed quote. Default terminal treatment marks open positions, not invented liquidation. +- V1 bar matching uses open-only market/limit crossing. It does not invent an OHLC path, intrabar stop order or within-bar limit touch. Explicit unsupported order types reject. +- Pin exactly one execution series (source/timeframe) per instrument per run. Only that series supplies matching opportunities, liquidity capacity and authoritative financial marks. Other timeframes are feature observations, not duplicate executable volume. Strategies declare a decision cadence; adding an unused feature series must not add decision triggers or alter fills. +- Target-generated orders are GTC until replaced/cancelled by their owner or cancelled at run termination. Explicit DAY orders are accepted only during an open venue session and expire at that session's close; out-of-session DAY submission rejects. A daily-close target therefore survives to the next session's open. No fill is invented for an order cancelled at run termination. +- Liquidity capacity at an open is a declared model using **previously available** volume (e.g. last completed bar volume times participation), never the new bar's future total volume. Quote mode uses available quote size. No known capacity means no simulated fill; zero capacity cannot fill. Report this approximation. +- Stable event ordering uses availability time, phase, instrument and source sequence. For bar mode at equal timestamps: publish completed prior-interval observations, update marks/features, create synchronized decisions, then process next-interval open-only events. The default assumes zero modeled decision/order latency. A decision can therefore fill at the immediately adjacent bar's open even when prior close and next open share the same timestamp, but never at the prior close. The next open's price is not in the decision context. Persist this zero-latency assumption explicitly; positive configured latency or delayed data skips opens occurring before decision availability plus latency. Quote mode instead requires a strictly subsequent eligible quote identity, not reuse of the quote just observed. Orders cannot be inserted retroactively into a completed event phase. +- Keep quote timestamps unchanged when the simulation clock advances. Missing/stale inputs are explicit. Equal-time cross-asset decisions use the same snapshot; execution priority is deterministic. +- Daily session labels become actual venue session boundaries using a retained calendar revision, including DST/half days. Unknown mappings reject project-gated execution. +- Warmup observations are available for features but cannot generate fills. Fit data and test data remain separately bounded. +- Raw prices are required for executable share/cash semantics. Provider-adjusted data may be an explicitly labelled signal input, not a replacement for action accounting. V1 project correctness-gate evidence requires supported action coverage or action-free eligibility; unknown coverage remains a limitation. + +## Evidence and rationale + +[Current same-event execution](../../../../apps/stock/engine/src/backtest/engine.rs#L249), [bar-close bid/ask](../../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224), [v1 timestamp contract](../../../../libs/core/types/src/historical-data.ts#L90), [invented VWAP](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L230). + +## Alternatives / tradeoffs + +Same-close fills are allowed only as an explicitly named legacy assumption, not default evidence. Full tick/order-book replay and stochastic intrabar paths are deferred. Next-open open-only matching is limited but traceable; zero modeled latency is optimistic and must be disclosed. Using the new bar's total volume to constrain a fill at its open would itself leak future information. + +## Migration + +D01 creates new hashes without rewriting v1 snapshots. F05/F06 consume v2 timing. C01 fixes existing liquidation accounting without silently changing policy. F08/R05 record execution-policy versions and retain old result semantics. New economics will change backtest returns; that is an intentional correction, not a parity failure to hide. + +## Implementation boundaries + +F05 tests matcher transitions against explicit execution-event keys. F06 owns derived open events, calendars, decision barriers and end-to-end latency tests; those release gates must not force F05 to implement replay first. D01 includes availability and coverage/eligibility in one versioned manifest change (D03 merged). + +At each barrier all due strategy contexts share one immutable ledger revision; submit decisions as a batch in stable admission priority. Explicit IOC/FOK semantics are retained for paper compatibility. Account risk-session reset is a separate declared clock from individual instrument session expiry. diff --git a/docs/development/architecture/decisions/004-strategy-boundary.md b/docs/development/architecture/decisions/004-strategy-boundary.md new file mode 100644 index 00000000..6c018771 --- /dev/null +++ b/docs/development/architecture/decisions/004-strategy-boundary.md @@ -0,0 +1,33 @@ +# ADR-004 — One pull-session boundary, not two strategy frameworks + +Status: proposed for approval. + +## Selected approach + +Reuse NAPI-RS in the existing research worker. TS drives a synchronous bounded pull loop, not a reentrant Rust-to-JS callback. Web/API processes never execute the native loop. IPC stays at worker supervision and, later, the untrusted-strategy boundary. + +The first strategy path uses reviewed incremental TS calculations directly. A cache/feature DAG is not a prerequisite. Port one SMA strategy first; retain other strategies as explicit legacy artifacts until needed. Do not port every native built-in just to validate NAPI. + +## Minimal contract + +`advance(eventBudget)` returns one of: + +- `progress`: no decision; allow cancellation/supervisor progress. +- `decisionBatch`: barrier ID/revision, immutable prefix contexts for due strategy instances. +- `complete`: canonical ledger/mark/result inputs. + +At a decision barrier, collect all due strategies' intents/next states against the **same** portfolio revision. Submit the batch once; Rust validates owner identity, mode, IDs and admits in the pinned priority order. No early callback can mutate the next callback's view. Target versus explicit-order mode is fixed per strategy instance; duplicate targets consider existing owned commitments. + +Each strategy has its own seed/RNG cursor and decision sequence. Stage next state/RNG until submission. An exception discards the staged barrier and fails the attempt; a risk rejection is a valid committed outcome, with feedback to the strategy. On an ambiguous process failure, discard/restart the attempt rather than reuse half-advanced resident state. + +## Determinism claim, precisely + +Controlled clock/random inputs, prefix observations and pinned strategy/runtime/native artifacts produce repeatable fixture traces on the supported platform. Repeated conformance tests **cannot prove arbitrary JavaScript deterministic**. Trusted code can violate conventions; this is not a security sandbox. Economic replay of a recorded decision trace and recomputation of strategy decisions are separate tests. + +A snapshot sufficient for decision recomputation includes ledger/open orders/reservations, replay cursor, decision IDs, strategy states and RNG cursors; any incremental indicators must be checkpointed or deterministically rebuilt from the recorded warmup prefix. + +## Alternatives and tradeoffs + +NAPI already exists; [callback registration explicitly fails](../../../../apps/stock/engine/src/api/backtest.rs#L63). The existing [native worker](../../../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts) supplies killable process isolation. Keep it. No embedded JS runtime, generic transport adapter or mandatory per-observation IPC. A typed native plan remains deferred P06. + +F07 introduces the session; S01 drives it; S02 ships one real strategy. F07/S01 extend P01 measurements for actual crossings, context bytes and decisions. P03 cross-trial resident data is optional; loading once per session is ordinary behavior. diff --git a/docs/development/architecture/decisions/005-durable-cutover.md b/docs/development/architecture/decisions/005-durable-cutover.md new file mode 100644 index 00000000..f26dee7a --- /dev/null +++ b/docs/development/architecture/decisions/005-durable-cutover.md @@ -0,0 +1,25 @@ +# ADR-005 — Shared kernel, distinct persistence boundaries + +Status: proposed for approval; preservation of existing recovery is required. + +## One implementation + +Use one internal Rust `apply(state, command) -> effects` financial kernel. + +- Research keeps state resident and applies events directly. Do **not** serialize, clone or rehydrate a full account snapshot per observation. +- Paper loads the committed snapshot into private staged native state inside the existing SQL transaction, invokes the same kernel, persists snapshot/orders/fills/ordered journal effects atomically, commits, then publishes. Failed SQL work discards the staged state. +- Snapshot encoding is a boundary operation, not the hot-loop algorithm. Exact per-effect views remain available where the existing recovery journal requires them; do not replace them with a final batch state. + +TS owns SQL custody, not independent accounting. No native/DB two-phase commit and no new event-sourcing framework. + +## Decision durability + +Preserve [restore-before-each-step and intent transactions](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151), [account locks and duplicate/conflict handling](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46), and existing failure tests. Paper strategy contexts use committed event views; never substitute a later account state. Restore RNG/decision cursors along with checkpoint state. + +All currently supported paper order policies must be preserved or a migration explicitly refused. F05 covers market/limit and DAY/GTC/IOC/FOK; do not silently drop IOC/FOK at cutover. + +## Migration + +C06 contains unsafe legacy research/paper composition; it does not build a temporary second worker framework. F02 builds owner accounting once. S03 adopts the kernel and durable recovery without waiting for Sharpe/Sortino or web pages. S04 verifies paper feed/readiness. S06 retires competing active execution after those gates, retaining result readers/research algorithms. + +Compare financial transitions for the **same event and intent trace**. Research and paper receive different real-world prices/availability; identical P&L is not promised for different inputs. Broker fills remain future external facts to reconcile, not simulated orders that can be rejected after occurrence. diff --git a/docs/development/architecture/decisions/006-research-product.md b/docs/development/architecture/decisions/006-research-product.md new file mode 100644 index 00000000..48a9c1cb --- /dev/null +++ b/docs/development/architecture/decisions/006-research-product.md @@ -0,0 +1,27 @@ +# ADR-006 — Web-first research product and minimal persistence + +Status: **proposed for plan approval**; web as primary product is user-mandated. + +## Selected approach + +Extend current React features, Hono v2 APIs, SQL definitions/runs/results, durable outbox/queue, frozen datasets and websocket projection. The browser and AI clients use the same business APIs. + +Add only strategies, immutable strategy_versions, research_projects, hypotheses, experiments and analysis_artifacts. Attach candidate/experiment identity to existing runs; keep backtests as editable templates. A later paper deployment record is optional. Store stable single-owner/agent identity without implementing full multi-tenancy. + +Retain artifact bytes or immutable retained references, not hashes alone. Archive referenced evidence; no automatic purge by default. Future operator retention must respect references and explicit consent. + +## Evidence + +[Existing submission transaction](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211), [existing result contract](../../../../libs/core/types/src/backtest-run.ts#L4), [schema deletion cascade](../../../../database/postgres/init/08-create-runs-table.sql#L13), [existing UI routes](../../../../apps/stock/web-app/src/app/App.tsx#L24). + +## Alternatives / tradeoffs + +A separate research database, job service, AI-only APIs or general laboratory/workflow system duplicates working infrastructure. SQL metadata and bounded job expansion suffice. Existing JSONB results are acceptable until measurement warrants paged/normalized detail. Source editing initially uses repository/artifact submission plus schema forms and version diff; no browser IDE prerequisite. + +## Migration + +W01–W04 deliver the existing exploratory workflow while engine work proceeds. R01–R04 add strategy/workspace value independently of Rust cutover. R05 turns that same workbench into a reproducible canonical-engine workflow; R06–R09 add experiments/validation. Legacy results stay read-only and visibly qualified. See [product contracts](../research-product.md). + +## Reduced product dependencies + +API/data contracts gate implementation, not unrelated screens. Catalog/workspace/experiment/dataset UI tasks can use focused tests before W04 is complete, but shared browser coverage remains a feature-release gate. Basic experiment comparison needs a frozen dataset ID, not the entire project workspace or dataset picker. Findings reference immutable metric paths rather than creating another metric store. R06 ships summary projections; P05 is only a later measured detail optimization. diff --git a/docs/development/architecture/decisions/007-ai-boundary.md b/docs/development/architecture/decisions/007-ai-boundary.md new file mode 100644 index 00000000..d2ce756d --- /dev/null +++ b/docs/development/architecture/decisions/007-ai-boundary.md @@ -0,0 +1,23 @@ +# ADR-007 — AI authorization, code isolation and promotion + +Status: **owner approval required** for the execution trust model; quotas/isolation/no autonomous live access are user requirements. + +## Selected approach + +Use existing operator authentication plus explicit research-agent identity/scope. AI may create hypotheses/candidate artifacts and submit bounded experiments, but cannot loosen account risk, choose its own privileges or invoke paper/live administration. + +Unreviewed code is built/imported/evaluated in an OS-restricted process or container with no network, secrets, database, broker credentials, shared writable paper state or full future dataset. The financial supervisor sends prefix-only contexts over IPC. Require CPU/wall/memory/process limits and safe cancellation. A JS `vm` or a separate unrestricted process alone is insufficient. + +Trusted registered/reviewed artifacts can run beside NAPI in a worker for speed. Moving an artifact into that tier requires an explicit operator action, never an AI-supplied trust flag. If the sandbox is unavailable, reject untrusted execution; do not silently downgrade. + +## Evidence + +[Current role model](../../../../libs/core/di/src/http/security.ts#L4) is a small operator boundary, not research isolation. [Current registry dependencies](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7) expose execution services that the new decision API must not expose. + +## Alternatives / tradeoffs + +Running all AI code in the API/engine process is fast but not a meaningful protection against future-data reads or credential access. Sandboxing all reviewed code unnecessarily penalizes the trusted fast path. IPC has a cost; P01/A02 measure it separately. + +## Migration + +A01 adds actor/budget admission; A02 adds isolation; A03 composes existing research APIs; A04 permits only human-reviewed paper promotion after paper gates. Limits apply to autonomous job budgets and resource use, **not arbitrary truncation of the owner's datasets**. Local dev .env policy is not changed by this plan, but sandboxed code must never receive its contents. diff --git a/docs/development/architecture/decisions/008-performance.md b/docs/development/architecture/decisions/008-performance.md new file mode 100644 index 00000000..def12301 --- /dev/null +++ b/docs/development/architecture/decisions/008-performance.md @@ -0,0 +1,20 @@ +# ADR-008 — Performance work earns its complexity + +Status: proposed; P06 requires a separate measured go/no-go. + +## Sequence + +1. P01 measures currently available dataset/native execution paths. Missing counters are unavailable, not zero; getters are not callback benchmarks. +2. F06 constructs sorted historical replay once and measures scaling. P02 is merged, not a second queue rewrite. +3. F07/S01 add real step/TS-decision/context-byte measurements. +4. P04 runs independent trials with the existing one-shot workers. It need not wait for resident cross-trial datasets. +5. P03 shared datasets, D04 shared feature caching and P05 detail-storage/pagination remain deferred until profiles identify meaningful repeated work. +6. P06 may prototype a tiny plan only with owner-approved budget and representative end-to-end benefit target. + +## Why change the old gate + +A removable20% fraction permits at most1.25x speedup; a simultaneous1.5x condition is not a useful universal rule. Record the actual fraction, Amdahl upper bound, end-to-end timings and maintenance cost. The owner chooses whether the benefit warrants a bounded prototype. No automatic language/framework project is authorized by a microbenchmark. + +## Constraints + +Correctness/policy hashes must match. Keep financial event processing serial within one portfolio; parallelize independent trials. No GPU/distributed scheduler/feature service/embedded JS or Arrow-everywhere conversion without evidence. Existing [queue insertion scan](../../../../apps/stock/engine/src/backtest/mod.rs#L138) is a concrete reason to choose a sorted cursor, not a reason to rewrite unrelated infrastructure. diff --git a/docs/development/architecture/overview.md b/docs/development/architecture/overview.md new file mode 100644 index 00000000..23accf01 --- /dev/null +++ b/docs/development/architecture/overview.md @@ -0,0 +1,150 @@ +# Architecture baseline and target + +Planning baseline: commit `b7aeca4`, inspected 2026-10-22. This is a proposed plan, not an implementation or project correctness-gate evidence. [Decisions](../backlog/manifest.json) and [verified findings](../backlog/findings.md) distinguish user mandates, proposed policies and uncertainties. + +## What exists + +The React/Vite application already has saved backtest definitions, run selection, charts, trades and metrics. The Hono/Bun API writes a request snapshot and dispatch outbox in one PostgreSQL transaction. The existing dispatcher/queue and fenced runner claim attempts, freeze datasets, heartbeat leases and persist results. PostgreSQL-backed websocket projections and polling support status updates. + +There are currently two economic implementations: a TypeScript simulation with durable account/decision recovery, and a native Rust backtester with its own fill/accounting behavior. The TS path can switch the shared paper ModeManager. Native TS callback registration is unsupported. Neither path should currently be treated as project-gated research performance. + +```mermaid +flowchart LR + UI[Existing React backtest pages] --> API[Hono v2 backtest API] + API --> PG[(Postgres definitions / runs / dispatch / results)] + PG --> DIS[Existing dispatcher and queue] + DIS --> RUN[Fenced durable runner] + STORE[Provider storage] --> DATA[Frozen hashed datasets] + DATA --> RUN + RUN --> TS[TS BacktestEngine and SimulationExecution] + RUN --> NW[Native worker / NAPI] + NW --> OLD[Rust BacktestEngine] + TS --> MODE[Shared paper ModeManager: interference risk] + TS --> RESULT[Result adapters] + OLD --> RESULT + RESULT --> PG + PG --> WS[Websocket run projection / polling] + WS --> UI +``` + +Evidence: [transactional submission](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211), [dataset freeze](../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190), [recovery](../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151), [shared mode mutation](../../../apps/stock/orchestrator/src/container.ts#L101). + +## Target: one product, one financial core + +```mermaid +flowchart TB + WEB[Primary React research workbench] --> API[TS research / strategies / experiments API] + AI[Authorized AI research client] --> API + API --> PG[(Existing Postgres metadata / immutable provenance / results)] + API --> Q[Existing dispatch + durable queue] + Q --> SUP[TS run supervisor / bounded worker pool] + DATA[Frozen datasets + retained model artifacts] --> SUP + SUP --> STR[TS strategy decisions / signal and regime composition] + SUP --> CORE[Rust replay + matching + owner ledger + risk] + STR -->|intents only| CORE + CORE -->|available context and effects| STR + PLAN[Optional small declarative plan] -.-> CORE + UNTRUSTED[Restricted TS process: no secrets or future dataset] -->|validated intents via IPC| SUP + CORE --> RES[Canonical economics / metrics / diagnostic artifacts] + RES --> PG + PAPER[TS paper adapter + durable transaction custody] --> CORE + PAPER --> JOURNAL[(Existing checkpoints / intents / execution journal)] + PG --> WEB + LIVE[Future broker adapter: disabled] -.-> CORE +``` + +This remains a modular monolith with existing operational processes and bounded computation workers—not a new service topology. + +## Responsibility boundaries + +| Boundary | TypeScript owns | Rust owns | +| --- | --- | --- | +| Product | UI/API, strategies/versions, projects, experiments, findings, configuration | No web business logic | +| Research | Candidate expansion, bounded scheduling, validation recipes, AI clients; reviewed statistical analytics over canonical results | Deterministic replay and authoritative financial result inputs | +| Strategy | Arbitrary compatible author logic, feature/signal composition, regime integration, checkpoint payload | Validated read-only context and decision admission | +| Features | Definitions, metadata, reviewed TS calculations when fast enough | Existing/bulk native calculation where profiling and parity justify it | +| Finance | Display/transport only; allocation preferences and intent proposals | Accepted quantities, reservations, positions, cost basis, cash, fees, order transitions, risk limits | +| Durability | Existing PostgreSQL transactions, leases, idempotency custody, retained artifacts | One financial kernel, versioned boundary snapshots and ordered effects | +| Execution | Provider/broker connectivity and reconciliation orchestration | Simulation semantics; canonical accounting/risk for observed broker facts | + +A future broker's fills are external facts, not simulated prices. They must be accounted for even when a risk limit is breached, then trigger a halt/reconciliation workflow; they must not be silently discarded to make an invariant look satisfied. + +## Minimal module shape + +Keep current app and library boundaries. Add focused modules, not another package/service for every noun: + +- `apps/stock/engine/src/financial/`: scalar types, ledger, ownership, risk, matching, replay. Adapt `positions/`, `risk/`, `backtest/` and `indicators/`; do not replace all Rust code. +- `apps/stock/orchestrator/src/strategies/`: versioned TS decision API, registry, built-ins, signals/regime functions. +- `apps/stock/orchestrator/src/backtest/`: existing durable runner/native worker, session adapter and later pool. +- `apps/stock/orchestrator/src/execution/`: existing transaction/recovery adapters, eventually without independent arithmetic. +- `apps/stock/web-api/src/{routes,services}/`: strategy/research/experiment additions alongside current backtests. +- `apps/stock/web-app/src/features/{backtest,strategies,research,experiments}/`: coherent research journeys. +- `libs/core/types/src/`: public versioned contracts. `libs/calculations/`: preserve reviewed semantics and migration inventory. + +## Minimal decision contract + +Illustrative contract to be implemented by F01/S01, not a new framework: + +```ts +type Decimal = string; // validated fixed-scale transport, not JS money arithmetic +type Intent = + | { kind: "targetQuantity"; instrumentId: string; quantity: Decimal } + | { kind: "order"; instrumentId: string; side: "buy" | "sell"; + quantity: Decimal; type: "market" | "limit"; limitPrice?: Decimal; + timeInForce: "DAY" | "GTC" | "IOC" | "FOK" }; + +interface DecisionContext { + decisionId: string; + nowMs: number; // engine availability clock + strategyInstanceId: string; + features: Readonly; // only available prefix; includes regime inputs + positions: Readonly; + portfolio: Readonly; + risk: Readonly; // context, not a mutable policy object + random(): number; // run/strategy seeded stream +} +interface Strategy { + decisionCadence: { executionSeriesId: string; event: "barClose" }; + initialState(params: Params): State; + onDecision(ctx: DecisionContext, state: Readonly, params: Params): + { nextState: State; intents: readonly Intent[] }; + checkpointVersion: string; +} +// Trusted worker drives a pull loop; Rust never needs a reentrant JS callback. +const step = engine.advance(session, eventBudget); +switch (step.kind) { + case "progress": yieldToSupervisor(); break; + case "decisionBatch": { + // All contexts are from one immutable ledger revision; RNG is per strategy. + const staged = step.contexts.map(ctx => evaluateAndStage(ctx)); + engine.submitDecisions(session, step.barrierId, staged.map(x => ({ + strategyInstanceId: x.strategyInstanceId, decisionId: x.decisionId, + intents: x.intents, + }))); + commitStagedStates(staged); // business rejections are committed outcomes + break; + } + case "complete": persistCanonicalResult(step.result); break; +} +// On exception/ambiguous crash: discard the attempt, never reuse half-advanced state. +``` + +S01 initially uses prefix-only observations and reviewed incremental calculations; D04 shared caching is optional. S02 ports one SMA first, not every builtin. All due callbacks finish against the same portfolio snapshot before admission. + +The supervisor stamps owner identity; a strategy cannot forge another owner's ID. Target quantity is an **absolute desired holding**, not an additive order. Rust subtracts owned inventory plus outstanding commitments and applies risk. Repeated target decisions cannot duplicate orders. V1 cancels/replaces owned outstanding target orders deterministically; explicit orders use unique decision-derived IDs. + +A strategy instance uses target OR explicit-order mode; mixed intent styles reject in v1. The ledger stores remaining cost amounts, not reconstructed rounded-average basis. Statistical report functions reuse reviewed TS calculations over authoritative Rust values; only profiling justifies a native port. + +Portfolio allocation is initially an explicit TS policy producing per-strategy budgets, not a new optimizer class. Rust enforces both those registered budgets and stricter account constraints. No cross-strategy netting in v1; order priority is stable strategy-instance/intent sequence. Independent models can produce ordinary typed scores; a universal signal schema is unnecessary. + +## Example end-to-end lifecycle + +A TS strategy requests SMA20/SMA60, momentum and realized volatility. A volatility classifier consumes the same feature snapshot. After warmup, the strategy combines momentum and trend scores with a mean-reversion score; high-volatility regime lowers its desired quantity. It compares that target with its own holdings and returns one target intent. It cannot modify cash or bypass risk. + +Rust resolves the target against existing owned orders, reserves fee-inclusive cash and validates portfolio limits. A completed-bar decision becomes eligible at the next interval's open or a subsequent quote, never the just-observed close. Adjacent bars may share a timestamp: ADR-003 explicitly orders close/decision before the next open under a disclosed zero-latency model; the strategy cannot inspect that open in advance. Matching emits an owned fill, fee and account/position effects; strategy state observes committed effects at the next decision. An exit is target zero and follows the same path. Reports reconcile to the ledger, including open terminal positions. + +Research replays frozen data into this core. Paper sends normalized live observations into the same core through durable SQL transactions. Clock sources and liquidity inputs differ; financial transition rules do not. AI/untrusted decisions run outside the data/engine supervisor, receiving only the available prefix. + +## What remains intentionally simple + +No microservices rewrite, event-sourcing platform, generic workflow DAG runtime, universal plugin hierarchy, mandatory Rust strategy rewrite, browser IDE or optimizer framework. Existing journals remain where they already protect recovery. Shorting, corporate-action execution, intrabar stop paths and real brokers require explicit later policies, not permissive defaults. diff --git a/docs/development/architecture/research-product.md b/docs/development/architecture/research-product.md new file mode 100644 index 00000000..d0bde189 --- /dev/null +++ b/docs/development/architecture/research-product.md @@ -0,0 +1,107 @@ +# Integrated research product contracts + +Status: proposed under ADR-006. This is the minimum product model, not a general laboratory system. + +## Existing paths to preserve + +- [BacktestListPageV2](../../../apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx#L17) already lists/creates definitions. +- [BacktestDetailPageV2](../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L24) already selects runs, renders charts/trades/configuration and links saved URLs. +- [backtestApiV2](../../../apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts#L54) already exposes definitions, runs, results and controls. +- [createRun](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211) already freezes a request and creates dispatch in one transaction. +- [run-updates](../../../apps/stock/web-api/src/websocket/run-updates.ts#L68) projects committed SQL state; reuse it. +- [SQL migrations 06–13](../../../database/postgres/init/) already contain definitions, runs/results, dispatch, execution ledger, datasets and recovery. +- [strategy/analytics placeholders](../../../apps/stock/web-app/src/app/App.tsx#L24) are not a strategy/research product today. + +## Minimum entities + +| Entity | Minimum contents / relationships | Mutability | +| --- | --- | --- | +| strategies (new) | ID, owner principal, name/status/docs, clone lineage, optional project | Metadata editable/archiveable | +| strategy_versions (new) | Strategy ID, version ID, source/bundle and retained artifact, hashes, parameter schema, checkpoint/API version, review status | Published executable content immutable; review decisions audited separately | +| research_projects (new) | ID, owner, title/description/status | Editable/archiveable | +| hypotheses (new) | Project ID, proposition, author kind/ID, state, validation criteria | Revisioned narrative; evidence state cannot be self-asserted by AI | +| backtests (existing) | Saved editable configuration template, optional version/project links | Edits do not change historical runs | +| experiments (new) | Optional project/hypothesis links, version(s), bounded grid, seed, partitions, cost/risk policies, selection rule; immutable validation report when completed | Inputs frozen at submission; reports append-only; clone to change | +| runs (existing) | Existing request/attempt/lease/cancel fields; experiment ID, trial key, frozen version/provenance, actor | Inputs immutable; execution state fenced | +| backtest_results (existing) | One terminal result per run, economics/metrics versions, full retained provenance, limitations and correctness-test policy/version references | Append-only; no silent metric rewrites | +| analysis_artifacts (new) | Kind (note/finding), revisioned narrative, authorship, exact run/version/retained-artifact references; reference experiment validation reports rather than storing a second copy | Versioned; evidence refs protected | +| paper_deployments (later) | Human approval, version/account/policy/evidence IDs, activation history | Explicit transitions; no live deployment in this plan | + +Project/hypothesis links are optional. Add their nullable foreign keys only when the referenced tables exist; R01/R06 must work without R03 or placeholder research rows. Keep any cross-epic additive link migration under one integrator-owned SQL lock. + +A run is a durable logical trial; attempts already exist on it. Do not add a competing job/attempt table. Run/experiment many-strategy configuration is a frozen list of strategy-version + instance + parameter + budget records. Artifact hashes alone are insufficient: retain retrievable source/bundle/model bytes and dependency/build identity. + +```mermaid +erDiagram + RESEARCH_PROJECT ||--o{ HYPOTHESIS : contains + RESEARCH_PROJECT o|--o{ STRATEGY : organizes + STRATEGY ||--o{ STRATEGY_VERSION : versions + RESEARCH_PROJECT o|--o{ EXPERIMENT : contains + HYPOTHESIS o|--o{ EXPERIMENT : motivates + BACKTEST_TEMPLATE ||--o{ RUN : snapshots + EXPERIMENT o|--o{ RUN : groups + STRATEGY_VERSION }o--o{ RUN : frozen_configuration + RUN ||--o| BACKTEST_RESULT : produces + RUN }o--o{ ANALYSIS_ARTIFACT : supports +``` + +The many-version/run relationship can initially live in validated frozen configuration JSON with referential validation; introduce a join table only if query or referential-integrity needs justify it. Findings' run references must have DB-enforced retention/integrity (small reference relation if needed), not only free-text links. + +## API rules shared by browser and AI + +Keep `/api/v2` and current operator sessions. New APIs follow the task-specific contracts, not a parallel `/ai/backtests` path. + +- IDs are stable opaque IDs; every write records owner/actor. Server derives actor, never trusts submitted privilege fields. +- Save template and submit run are explicit separate actions. Submit uses an idempotency key + input fingerprint; identical retry returns same run, different payload returns409. +- Use typed errors:400/422 input,401/403 auth,404 missing,409 immutable/conflict/reference,429 AI budget,503 unavailable dependency. Async accepted work returns202 + run/experiment URL. +- Persisted state is authoritative. Cancel acceptance is not completed cancellation; failed/incomplete runs cannot masquerade as successful zero return. +- Existing run diagnostics remain authoritative. W01 exposes shared cancellation; native-unsupported pause/resume/speed controls are absent/disabled. Add per-run support metadata only when a real second supported control path needs it, not a generic capability registry. +- Results distinguish financial engine, strategy execution mode, metrics/economics policy versions and provenance completeness. Maintain compatibility fields for old clients. +- Reproduce-original pins original inputs; rerun-current creates a new request. Missing original code/dataset/model is a clear failure, not a fallback. +- Comparison must surface mismatched costs, datasets, windows, engines and failed candidates; default ranking uses comparable completed project-gated runs. +- Batch submission requires a resolved frozen dataset hash shared by its candidates. A single run may first prepare a new source request; individual sweep trials must not independently reload provider history. +- Retention is archive-first. Referenced runs/versions/datasets/artifacts cannot disappear through an existing cascade. +- UI/API do not calculate competing equity, fees or fills. Display-only formatting/downsampling never changes financial results. + +## Product increments + +| Slice | User journey | Tasks | Engine prerequisite | +| --- | --- | --- | --- | +| M1 exploratory workbench | Select supported existing strategy -> save/configure -> durable submit -> status/cancel -> results/trades -> reopen | W01–W04 | Existing engines, explicitly limited/legacy/ungated | +| M2 organized research | Create project/hypothesis -> select immutable registered version -> run -> save evidence-qualified finding | R01–R04/R10 | Can ship alongside engine migration | +| M3 reproducible canonical run | Choose version/dataset/cost/risk -> Rust run with TS decisions -> inspect -> reproduce original | F01/F02/F04–F08, D01, S01/S02, R05/R11/R12 | Canonical economics + explicit correctness tests | +| M4 experiment loop | Preview sweep -> run -> compare -> validate out of sample/costs/regimes | R06–R09/S05 | M3 | +| M5 AI loop | AI candidate -> bounded isolated experiments -> evidence -> human review -> paper promotion | A01–A04/S03/S04 | M4 + isolated code + verified paper path | + +Do not delay M1/M2 for the entire Rust migration. Conversely, delivering those screens does not make old financial results trustworthy. M1 release requires C06 runtime isolation; exploratory labels never excuse interference with paper state. + +Dataset selection R11 lists retained manifests without loading bar payloads. A selected existing hash is pinned at submission. A new source request freezes query parameters then prepares asynchronously through the existing runner; only after a fenced atomic dataset binding is it reproducible input. No strategy execution occurs before that binding. Retries reuse the pinned dataset, not a fresh provider query. The UI must distinguish these phases. + +## Example: bounded AI-assisted multi-strategy research + +Illustrative workflow, not a claim of profitable results: + +1. An authorized agent registers the hypothesis “trend and mean-reversion components benefit from different volatility budgets” in a project. It specifies validation criteria before seeing held-out results. +2. It selects immutable SMA and mean-reversion versions (or submits isolated candidate artifacts), two strategy instances per asset, a frozen multi-asset dataset, a fixed seed and long-only account/risk policy. The execution series is 1m; 5m/1h inputs are feature-only. Model/threshold fits use training data only. +3. It previews a bounded grid: 3 fast windows × 2 slow windows × 2 high-volatility multipliers = 12 candidate portfolios. A declared 30-trial research budget admits those 12, with all failures retained. +4. It selects at most two candidates using the recorded validation criterion, then requests 3 cost scenarios each (6 runs) and 4 chronological walk-forward segments each (8 runs). Two final held-out runs bring the total to 28; each admission still checks remaining budget. The held-out data is not exposed to candidate code before its designated phase. +5. It compares aggregate and per-owner equity/P&L, regime sample counts, turnover, cost sensitivity and failed execution diagnostics. A finding cites the exact 28 run IDs/configurations and distinguishes exploratory selection from held-out evidence. Failure to outperform the baseline remains a valid finding. +6. The user opens the same experiment in the web app, inspects trades/positions, reproduces an original run, requests further validation if desired and explicitly approves a version for paper trading only after S04 readiness. The agent cannot activate paper or live trading. + +No extra AI database, simulator or agent framework is needed for this workflow. + +## UI conventions and tests + +Reuse current Card/Dialog/DataTable/layout/chart/metric components and responsive layouts. Add only research/strategy/experiment navigation. Preserve draft input on errors, show loading separate from empty, label incomplete/cancelled/legacy/ungated results, and allow reopening exact saved URLs. Do not replace working components for cosmetic consistency. + +Existing [analytics-ui tests](../../../test/integration/analytics-ui.test.tsx#L1) use server rendering; there is no declared browser harness in [web package](../../../apps/stock/web-app/package.json). W01 adds narrowly scoped interaction tests; W04 adds real navigation E2E, preferably Playwright. Dependency installation is an explicit task step requiring the usual approval, not an assumed existing capability. + +## Review clarifications + +- Metrics are derived by one reviewed reporting path from Rust ledger/session marks; the browser does not recalculate finances. +- R06 provides small SQL summaries now. Full result pagination/storage normalization is deferred P05. +- Project/catalog/dataset screens are not prerequisites for backend experiments or an AI client. Release still requires the applicable browser story and isolation gates. +- Walk-forward v1 uses explicitly reset accounts/state per segment with indicator warmup. Display segment returns and reset semantics; do not label stitched independent capital as one continuous executable portfolio. +- AI narratives cite run/version/metric paths. Traceable evidence is not automatic validation of an arbitrary natural-language conclusion. + +Validation reports (R08) are immutable experiment-owned outputs, not research findings. Their display must work before R03. R09 enables save/link-finding only when R03 evidence APIs are present; the finding references the exact report and contributing runs, without moving financial truth into a second store. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md new file mode 100644 index 00000000..e5c68a5c --- /dev/null +++ b/docs/development/backlog/README.md @@ -0,0 +1,118 @@ +# Canonical development backlog + +**First-wave execution is authorized; consult manifest execution_scope.** Start with [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave prompts](../FIRST-WAVE.md). Other tasks and unresolved policies remain gated. + +## One source of truth + +[manifest.json](manifest.json) owns scheduling metadata: status, priorities, dependencies, ADR approvals, assignments and write locks. Task Markdown owns implementation scope/evidence/acceptance. This index and the [graph](dependencies.mmd) are derived views. Only the planning/integration owner updates scheduling state. + +**43 scheduled + 5 deferred + 4 merged IDs = 52 retained IDs.** Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation. + +States: ready, claimed, in_progress, review, done, blocked, deferred, merged. “Ready” means no code/ADR prerequisite, not execution authority. Implementation dependencies require accepted integration. `release_gates` govern enabling an end-to-end feature, not component coding or integration; conditional gates apply only to the named capability. F05 may integrate before F06, but its replay behavior is not released until F06 proves it. + +Relative size: S narrow correction, M coherent boundary, L sensitive owner-controlled integration; not calendar estimates. Actual file overlap overrides symbolic lock names. No compatible structured issue tracker was found; do not duplicate task state in another system. + +## Complete task index + +### E1 — Immediate correctness and runtime containment + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [C01 Correct native terminal valuation](tasks/C01.md) | P0 / ready | None | — | Rust financial correctness / S | +| [C02 Reject malformed native data and preserve milliseconds](tasks/C02.md) | P1 / ready | None | — | Rust/NAPI boundary / S | +| [C03 Close the existing TypeScript fee-funding hole](tasks/C03.md) | P0 / ready | None | — | Trading infrastructure implementation / M | +| [C04 Make partial runtime initialization recoverable](tasks/C04.md) | P1 / ready | None | — | Trading infrastructure implementation / S | +| [C05 Create economic regression fixtures independent of implementations](tasks/C05.md) | P0 / merged → F01 | None | — | Quantitative correctness/test engineering / M | +| [C06 Contain legacy research/paper interference without a second runtime](tasks/C06.md) | P0 / blocked | C04 | — | Trading infrastructure implementation / S | + +### E2 — Canonical Rust financial engine + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [F01 Define the minimal financial contract and economic fixtures](tasks/F01.md) | P0 / blocked | ADR-002, ADR-003, ADR-004 | — | Rust financial contract owner / M | +| [F02 Implement one owner-aware financial ledger](tasks/F02.md) | P0 / blocked | F01, ADR-002 | — | Rust accounting / L | +| [F03 Add strategy-owned position books and fill allocations](tasks/F03.md) | P0 / merged → F02 | None | — | Rust portfolio accounting / M | +| [F04 Enforce cash reservations and portfolio risk centrally](tasks/F04.md) | P0 / blocked | F02, ADR-002, ADR-003 | — | Rust financial risk / L | +| [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / blocked | F04, ADR-003 | F06 | Rust execution semantics / L | +| [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / blocked | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M | +| [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / blocked | F06, C02, ADR-004 | — | Rust/TypeScript integration / M | +| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / blocked | F06, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M | + +### E3 — Point-in-time datasets and features + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [D01 Introduce availability-aware dataset v2](tasks/D01.md) | P0 / blocked | ADR-003 | — | TypeScript trading infrastructure / M | +| [D02 Connect supported intraday storage to research datasets](tasks/D02.md) | P1 / blocked | D01 | — | TypeScript trading infrastructure / M | +| [D03 Add dataset eligibility and corporate-action safeguards](tasks/D03.md) | P1 / merged → D01 | None | — | TypeScript trading infrastructure / M | +| [D04 Provide prefix-safe shared feature calculation](tasks/D04.md) | P1 / deferred | S01, P01 | — | Quantitative feature engineering / M | + +### E4 — TypeScript strategies and durable paper integration + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [S01 Run deterministic TypeScript decisions on Rust sessions](tasks/S01.md) | P0 / blocked | F07, ADR-004, ADR-005 | — | TypeScript trading infrastructure / M | +| [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / blocked | S01 | — | TypeScript strategy/quant engineering / M | +| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / blocked | S01, C06, ADR-005 | — | Durable execution/Rust integration / L | +| [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / blocked | S02, S03 | — | TypeScript trading infrastructure / M | +| [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / blocked | S02, F08 | R08 | Quant strategy research / M | +| [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / blocked | S03, S04, R05 | — | TypeScript trading infrastructure / M | + +### E5 — Existing web backtest vertical slice + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [W01 Make existing run controls and selection truthful](tasks/W01.md) | P1 / ready | None | — | Full-stack React/API / M | +| [W02 Expose result provenance and legacy correctness limitations](tasks/W02.md) | P1 / blocked | W01 | — | Full-stack research UX / M | +| [W03 Separate save, submit and repeat-safe run creation](tasks/W03.md) | P1 / blocked | O01 | — | Full-stack durable workflow / M | +| [W04 Verify the first research vertical slice in a browser](tasks/W04.md) | P1 / blocked | W01, W02, W03, C06 | — | Full-stack test engineering / M | + +### E6 — Research product, provenance and validation + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [R01 Persist immutable strategy versions and parameter schemas](tasks/R01.md) | P1 / blocked | O01, ADR-006 | — | Full-stack research product / M | +| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / blocked | R01, W03, ADR-006 | W04 | Full-stack research product / M | +| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / blocked | R01, R10, ADR-006 | — | Full-stack research product / M | +| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / blocked | R03, W02, ADR-006 | W04 | Full-stack research product / M | +| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / blocked | F08, S02, R01, R10, D01, W03, C06, ADR-006 | — | Full-stack research product / M | +| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / blocked | R05, ADR-006 | — | Full-stack research product / M | +| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / blocked | R06, ADR-006 | W04 | Full-stack research product / M | +| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / blocked | R06, ADR-006 | — | Quantitative research integrity / M | +| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M | +| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / blocked | R01, ADR-006 | — | Full-stack research product / M | +| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / blocked | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M | +| [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / blocked | R05, W04, ADR-006 | — | Full-stack reproducible research / S | + +### E7 — Measured research throughput + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [P01 Measure existing research paths before extending the benchmark](tasks/P01.md) | P2 / ready | None | — | Performance/infrastructure engineering / M | +| [P02 Remove measured replay queue and hot-loop overhead](tasks/P02.md) | P2 / merged → F06 | None | — | Performance/infrastructure engineering / M | +| [P03 Reuse validated datasets within bounded native workers](tasks/P03.md) | P2 / deferred | F07, P01, ADR-004, ADR-008 | — | Performance/infrastructure engineering / M | +| [P04 Schedule deterministic batches across a bounded worker pool](tasks/P04.md) | P2 / blocked | F07, R06, C06, P01, ADR-008 | — | Performance/infrastructure engineering / M | +| [P05 Separate result summaries from paged detail payloads](tasks/P05.md) | P2 / deferred | R06, P01 | — | Performance/infrastructure engineering / M | +| [P06 Conditionally add a minimal Rust-executed strategy plan](tasks/P06.md) | P2 / deferred | P04, S01, ADR-008 | — | Rust/TS performance compiler boundary / M | + +### E8 — Authorized, isolated AI research + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [A01 Add research-only principals and durable job budgets](tasks/A01.md) | P1 / blocked | R06, O01, ADR-007 | — | Backend security/durable scheduling / M | +| [A02 Isolate untrusted TypeScript strategy builds and decisions](tasks/A02.md) | P1 / blocked | A01, S01, P01, ADR-007 | — | Process isolation/security / L | +| [A03 Implement an evidence-linked AI research workflow client](tasks/A03.md) | P2 / blocked | A02, R08, R03, ADR-007 | — | AI research integration / M | +| [A04 Add human-reviewed promotion to paper deployment](tasks/A04.md) | P2 / blocked | S04, R09, A01, R01, ADR-007, ADR-005 | — | Full-stack paper trading integration / M | + +### E9 — Migration and operational safeguards + +| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | +| --- | --- | --- | --- | --- | +| [O01 Serialize additive schema migrations safely](tasks/O01.md) | P1 / ready | None | — | PostgreSQL/backend infrastructure / S | +| [O02 Expose truthful research and paper readiness diagnostics](tasks/O02.md) | P1 / deferred | S04 | — | Infrastructure/observability / M | + +## Scheduling checks + +Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation. + +First wave: **C01, C03, C04, W01**, each with a copy-ready bounded assignment in [FIRST-WAVE.md](../FIRST-WAVE.md). No task has been implemented by this planning revision. diff --git a/docs/development/backlog/dependencies.mmd b/docs/development/backlog/dependencies.mmd new file mode 100644 index 00000000..dffb7091 --- /dev/null +++ b/docs/development/backlog/dependencies.mmd @@ -0,0 +1,193 @@ +flowchart TD + %% Generated view of manifest.json. Solid edges: implementation; dotted: release only. + subgraph E1["E1: Immediate correctness and runtime containment"] + C01["C01: Correct native terminal valuation"] + C02["C02: Reject malformed native data and preserve milliseconds"] + C03["C03: Close the existing TypeScript fee-funding hole"] + C04["C04: Make partial runtime initialization recoverable"] + C06["C06: Contain legacy research/paper interference without a second runtime"] + end + subgraph E2["E2: Canonical Rust financial engine"] + F01["F01: Define the minimal financial contract and economic fixtures"] + F02["F02: Implement one owner-aware financial ledger"] + F04["F04: Enforce cash reservations and portfolio risk centrally"] + F05["F05: Unify matching and order lifecycle on the ledger"] + F06["F06: Implement deterministic replay once, with linear historical traversal"] + F07["F07: Expose bounded Rust step sessions through existing NAPI workers"] + F08["F08: Publish canonical metrics and versioned result projections"] + end + subgraph E3["E3: Point-in-time datasets and features"] + D01["D01: Introduce availability-aware dataset v2"] + D02["D02: Connect supported intraday storage to research datasets"] + D04["D04: Provide prefix-safe shared feature calculation (conditional)"] + end + subgraph E4["E4: TypeScript strategies and durable paper integration"] + S01["S01: Run deterministic TypeScript decisions on Rust sessions"] + S02["S02: Adapt one SMA strategy for the first canonical path"] + S03["S03: Adapt durable paper transactions to Rust financial reducers"] + S04["S04: Establish a verified paper feed and operator safety gate"] + S05["S05: Add a small composable multi-signal regime example"] + S06["S06: Retire duplicate simulator paths after cutover proof"] + end + subgraph E5["E5: Existing web backtest vertical slice"] + W01["W01: Make existing run controls and selection truthful"] + W02["W02: Expose result provenance and legacy correctness limitations"] + W03["W03: Separate save, submit and repeat-safe run creation"] + W04["W04: Verify the first research vertical slice in a browser"] + end + subgraph E6["E6: Research product, provenance and validation"] + R01["R01: Persist immutable strategy versions and parameter schemas"] + R02["R02: Deliver strategy catalog and version-aware backtest setup"] + R03["R03: Add projects, hypotheses and evidence-linked findings APIs"] + R04["R04: Deliver research workspace and save-findings flow"] + R05["R05: Freeze complete provenance and cut over durable canonical runs"] + R06["R06: Create immutable experiments and bounded sweep expansion"] + R07["R07: Deliver sweep configuration and comparable-result views"] + R08["R08: Add bounded chronological and reset-segment validation"] + R09["R09: Expose validation, cost and regime evidence in the workbench"] + R10["R10: Protect retained research evidence and artifact integrity"] + R11["R11: Select and reuse frozen datasets in the workbench"] + R12["R12: Reproduce an original run separately from rerunning current settings"] + end + subgraph E7["E7: Measured research throughput"] + P01["P01: Measure existing research paths before extending the benchmark"] + P03["P03: Reuse validated datasets within bounded native workers (conditional)"] + P04["P04: Schedule deterministic batches across a bounded worker pool"] + P05["P05: Separate result summaries from paged detail payloads (conditional)"] + P06["P06: Conditionally add a minimal Rust-executed strategy plan (conditional)"] + end + subgraph E8["E8: Authorized, isolated AI research"] + A01["A01: Add research-only principals and durable job budgets"] + A02["A02: Isolate untrusted TypeScript strategy builds and decisions"] + A03["A03: Implement an evidence-linked AI research workflow client"] + A04["A04: Add human-reviewed promotion to paper deployment"] + end + subgraph E9["E9: Migration and operational safeguards"] + O01["O01: Serialize additive schema migrations safely"] + O02["O02: Expose truthful research and paper readiness diagnostics (conditional)"] + end + C04 --> C06 + ADR002 --> F01 + ADR003 --> F01 + ADR004 --> F01 + F01 --> F02 + ADR002 --> F02 + F02 --> F04 + ADR002 --> F04 + ADR003 --> F04 + F04 --> F05 + ADR003 --> F05 + F06 -. release only .-> F05 + F05 --> F06 + D01 --> F06 + P01 --> F06 + ADR003 --> F06 + F06 --> F07 + C02 --> F07 + ADR004 --> F07 + F06 --> F08 + ADR002 --> F08 + ADR003 --> F08 + ADR003 --> D01 + D01 --> D02 + S01 --> D04 + P01 --> D04 + F07 --> S01 + ADR004 --> S01 + ADR005 --> S01 + S01 --> S02 + S01 --> S03 + C06 --> S03 + ADR005 --> S03 + S02 --> S04 + S03 --> S04 + S02 --> S05 + F08 --> S05 + R08 -. release only .-> S05 + S03 --> S06 + S04 --> S06 + R05 --> S06 + W01 --> W02 + O01 --> W03 + W01 --> W04 + W02 --> W04 + W03 --> W04 + C06 --> W04 + O01 --> R01 + ADR006 --> R01 + R01 --> R02 + W03 --> R02 + ADR006 --> R02 + W04 -. release only .-> R02 + R01 --> R03 + R10 --> R03 + ADR006 --> R03 + R03 --> R04 + W02 --> R04 + ADR006 --> R04 + W04 -. release only .-> R04 + F08 --> R05 + S02 --> R05 + R01 --> R05 + R10 --> R05 + D01 --> R05 + W03 --> R05 + C06 --> R05 + ADR006 --> R05 + R05 --> R06 + ADR006 --> R06 + R06 --> R07 + ADR006 --> R07 + W04 -. release only .-> R07 + R06 --> R08 + ADR006 --> R08 + R07 --> R09 + R08 --> R09 + ADR006 --> R09 + S05 -. Regime comparison is enabled .-> R09 + R01 --> R10 + ADR006 --> R10 + D01 --> R11 + O01 --> R11 + ADR003 --> R11 + ADR006 --> R11 + W04 -. release only .-> R11 + R05 --> R12 + W04 --> R12 + ADR006 --> R12 + F07 --> P03 + P01 --> P03 + ADR004 --> P03 + ADR008 --> P03 + F07 --> P04 + R06 --> P04 + C06 --> P04 + P01 --> P04 + ADR008 --> P04 + R06 --> P05 + P01 --> P05 + P04 --> P06 + S01 --> P06 + ADR008 --> P06 + R06 --> A01 + O01 --> A01 + ADR007 --> A01 + A01 --> A02 + S01 --> A02 + P01 --> A02 + ADR007 --> A02 + A02 --> A03 + R08 --> A03 + R03 --> A03 + ADR007 --> A03 + S04 --> A04 + R09 --> A04 + A01 --> A04 + R01 --> A04 + ADR007 --> A04 + ADR005 --> A04 + S04 --> O02 + R03 -. save or link finding only .-> R09 + classDef conditional stroke-dasharray: 5 5,fill:#fff3cd,color:#222 + class D04,P03,P05,P06,O02 conditional + %% Merged traceability only: C05 -> F01; F03 -> F02; D03 -> D01; P02 -> F06. diff --git a/docs/development/backlog/findings.md b/docs/development/backlog/findings.md new file mode 100644 index 00000000..174f9a86 --- /dev/null +++ b/docs/development/backlog/findings.md @@ -0,0 +1,224 @@ +# Revalidated audit findings + +Baseline: `b7aeca4`, inspected 2026-10-22. No standalone structured audit/backlog was found in existing docs; this matrix reconciles the supplied audit concerns against current code. Existing informal docs remain historical context, not a second task tracker. + +**Verified** means the cited implementation establishes the behavior or gap. **Likely** would mean an inference not yet reproduced; none is promoted to a confirmed defect here. **Needs Investigation** marks runtime/coverage questions that source alone cannot certify. No full application test suite or new performance benchmark was run during this planning-only task. Numeric acceptance examples are new test requirements, not fabricated passing tests. + +## FIN-01 — Critical / Verified + +Both execution paths can act on a completed bar and fill against its current close; this is not a defensible default bar-close policy. + +Evidence: [apps/stock/engine/src/backtest/engine.rs:249](../../../apps/stock/engine/src/backtest/engine.rs#L249); [apps/stock/orchestrator/src/services/ExecutionService.ts:224](../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224). + +Disposition: [F01](tasks/F01.md), [F05](tasks/F05.md), [F06](tasks/F06.md), [W02](tasks/W02.md). + +## FIN-02 — Critical / Verified + +Native forced liquidation occurs after the last equity mark; reported final value reads that earlier mark, omitting terminal costs. + +Evidence: [apps/stock/engine/src/backtest/engine.rs:135](../../../apps/stock/engine/src/backtest/engine.rs#L135); [apps/stock/engine/src/backtest/simple_results.rs:308](../../../apps/stock/engine/src/backtest/simple_results.rs#L308). + +Disposition: [C01](tasks/C01.md), [F01](tasks/F01.md), [F02](tasks/F02.md). + +## FIN-03 — Critical / Verified + +Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. + +Evidence: [apps/stock/engine/src/risk/mod.rs:89](../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../apps/stock/orchestrator/src/execution/model.ts#L234). + +Disposition: [C03](tasks/C03.md), [F01](tasks/F01.md), [F02](tasks/F02.md), [F04](tasks/F04.md). + +## FIN-04 — Critical / Verified + +Native fills notify every strategy. TypeScript realized P&L uses aggregate symbol cost basis, not per-strategy cost basis. + +Evidence: [apps/stock/engine/src/backtest/engine.rs:489](../../../apps/stock/engine/src/backtest/engine.rs#L489); [apps/stock/orchestrator/src/execution/model.ts:108](../../../apps/stock/orchestrator/src/execution/model.ts#L108). + +Disposition: [F01](tasks/F01.md), [F02](tasks/F02.md), [S02](tasks/S02.md), [S05](tasks/S05.md). + +## FIN-05 — Critical / Verified + +Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. + +Evidence: [apps/stock/engine/src/api/backtest.rs:63](../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). + +Disposition: [F01](tasks/F01.md), [F02](tasks/F02.md), [F05](tasks/F05.md), [F07](tasks/F07.md), [S01](tasks/S01.md), [S03](tasks/S03.md), [S06](tasks/S06.md), [R05](tasks/R05.md), [P01](tasks/P01.md), [P06](tasks/P06.md). + +## FIN-06 — High / Verified + +Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. + +Evidence: [apps/stock/engine/src/backtest/engine.rs:374](../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../apps/stock/engine/src/backtest/engine.rs#L414). + +Disposition: [F01](tasks/F01.md), [F04](tasks/F04.md), [F05](tasks/F05.md), [S04](tasks/S04.md). + +## FIN-07 — High / Verified + +Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. + +Evidence: [apps/stock/engine/src/backtest/simple_results.rs:374](../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../apps/stock/engine/src/backtest/simple_results.rs#L542). + +Disposition: [F08](tasks/F08.md), [W02](tasks/W02.md), [R07](tasks/R07.md), [R08](tasks/R08.md). + +## DAT-01 — Critical / Verified + +Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. + +Evidence: [libs/core/types/src/historical-data.ts:90](../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../apps/stock/orchestrator/src/services/StorageService.ts#L177). + +Disposition: [F06](tasks/F06.md), [D01](tasks/D01.md), [R08](tasks/R08.md), [R11](tasks/R11.md). + +## DAT-02 — High / Verified + +Native input parsing silently discards malformed rows and truncates timestamps to seconds. + +Evidence: [apps/stock/engine/src/api/backtest.rs:217](../../../apps/stock/engine/src/api/backtest.rs#L217); [apps/stock/engine/src/api/backtest.rs:290](../../../apps/stock/engine/src/api/backtest.rs#L290). + +Disposition: [C02](tasks/C02.md). + +## DAT-03 — High / Verified + +Missing VWAP is replaced with typical price; reported volume and provider-adjusted prices are not a complete corporate-action execution model. + +Evidence: [apps/stock/orchestrator/src/data/historical-dataset.ts:230](../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L230); [libs/core/types/src/historical-data.ts:98](../../../libs/core/types/src/historical-data.ts#L98). + +Disposition: [D01](tasks/D01.md). + +## DAT-04 — High / Verified + +Historical storage selects QuestDB or daily MongoDB; the Mongo path explicitly rejects intraday requests. Ingestion-to-research routing requires an executable provider/interval capability check. + +Evidence: [apps/stock/orchestrator/src/services/StorageService.ts:287](../../../apps/stock/orchestrator/src/services/StorageService.ts#L287); [apps/stock/orchestrator/src/services/StorageService.ts:299](../../../apps/stock/orchestrator/src/services/StorageService.ts#L299). + +Disposition: [D02](tasks/D02.md). + +## RUN-01 — Critical / Verified + +TypeScript research preparation calls the shared mode manager, which shuts down the current mode, so a research job can interfere with paper runtime. + +Evidence: [apps/stock/orchestrator/src/container.ts:101](../../../apps/stock/orchestrator/src/container.ts#L101); [apps/stock/orchestrator/src/core/ModeManager.ts:47](../../../apps/stock/orchestrator/src/core/ModeManager.ts#L47). + +Disposition: [C06](tasks/C06.md). + +## RUN-02 — High / Verified + +Partial initialization can allocate services before isInitialized becomes true; shutdown exits early on that failure path. + +Evidence: [apps/stock/orchestrator/src/core/ModeManager.ts:55](../../../apps/stock/orchestrator/src/core/ModeManager.ts#L55); [apps/stock/orchestrator/src/core/ModeManager.ts:157](../../../apps/stock/orchestrator/src/core/ModeManager.ts#L157). + +Disposition: [C04](tasks/C04.md). + +## KEEP-01 — High / Verified + +Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. + +Evidence: [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151). + +Disposition: [F01](tasks/F01.md), [C06](tasks/C06.md), [F02](tasks/F02.md), [F05](tasks/F05.md), [S01](tasks/S01.md), [S03](tasks/S03.md), [S06](tasks/S06.md), [A04](tasks/A04.md). + +## KEEP-02 — High / Verified + +Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. + +Evidence: [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +Disposition: [F07](tasks/F07.md), [D01](tasks/D01.md), [D04](tasks/D04.md), [W04](tasks/W04.md), [R05](tasks/R05.md), [R06](tasks/R06.md), [R11](tasks/R11.md), [R12](tasks/R12.md), [P01](tasks/P01.md), [P03](tasks/P03.md), [P04](tasks/P04.md), [O02](tasks/O02.md). + +## STR-01 — High / Verified + +Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. + +Evidence: [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). + +Disposition: [F02](tasks/F02.md), [D04](tasks/D04.md), [S01](tasks/S01.md), [S02](tasks/S02.md), [S05](tasks/S05.md), [S06](tasks/S06.md), [R01](tasks/R01.md), [R02](tasks/R02.md), [A02](tasks/A02.md). + +## WEB-01 — High / Verified + +The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. + +Evidence: [apps/stock/web-app/src/app/App.tsx:24](../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). + +Disposition: [W01](tasks/W01.md), [W03](tasks/W03.md), [W04](tasks/W04.md), [R01](tasks/R01.md), [R02](tasks/R02.md), [R03](tasks/R03.md), [R04](tasks/R04.md), [R06](tasks/R06.md), [R07](tasks/R07.md), [R09](tasks/R09.md), [P05](tasks/P05.md), [A01](tasks/A01.md). + +## WEB-02 — High / Verified + +Detail exposes native-unsupported pause/resume controls, omits cancel wiring, and overlapping polling/selection can apply stale responses. + +Evidence: [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:379](../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L379); [apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts:160](../../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts#L160). + +Disposition: [W01](tasks/W01.md), [W04](tasks/W04.md), [O02](tasks/O02.md). + +## WEB-03 — High / Verified + +Definition creation auto-starts by default and catches submission failure; run creation has no client submission key. Re-run uses current definition rather than immutable original input. + +Evidence: [apps/stock/web-api/src/services/backtest-v2.service.ts:105](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L105); [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:173](../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L173). + +Disposition: [W03](tasks/W03.md), [R12](tasks/R12.md). + +## WEB-04 — High / Verified + +Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. + +Evidence: [libs/core/types/src/backtest-run.ts:4](../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../apps/stock/web-api/src/services/backtest-result.ts#L107). + +Disposition: [F08](tasks/F08.md), [W02](tasks/W02.md), [R01](tasks/R01.md), [R03](tasks/R03.md), [R04](tasks/R04.md), [R05](tasks/R05.md), [R06](tasks/R06.md), [R07](tasks/R07.md), [R10](tasks/R10.md), [R11](tasks/R11.md), [R12](tasks/R12.md), [A03](tasks/A03.md). + +## WEB-05 — High / Verified + +SQL deletion cascades from definitions to runs/results; evidence retention must be defined before research findings reference those results. + +Evidence: [database/postgres/init/08-create-runs-table.sql:13](../../../database/postgres/init/08-create-runs-table.sql#L13); [database/postgres/init/06-create-backtest-tables.sql:25](../../../database/postgres/init/06-create-backtest-tables.sql#L25). + +Disposition: [R03](tasks/R03.md), [R10](tasks/R10.md). + +## OPS-01 — High / Verified + +Migration runner uses an explicit safe allowlist; adding SQL alone will not run it. Concurrent migration admission lacks an advisory lock. + +Evidence: [apps/stock/web-api/src/migrations/migration-runner.ts:42](../../../apps/stock/web-api/src/migrations/migration-runner.ts#L42); [apps/stock/web-api/src/migrations/migration-runner.ts:57](../../../apps/stock/web-api/src/migrations/migration-runner.ts#L57). + +Disposition: [O01](tasks/O01.md). + +## PER-01 — Medium / Verified + +EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. + +Evidence: [apps/stock/engine/src/backtest/mod.rs:138](../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../apps/stock/engine/src/api/backtest.rs#L194). + +Disposition: [F06](tasks/F06.md), [F07](tasks/F07.md), [P01](tasks/P01.md), [P03](tasks/P03.md), [P04](tasks/P04.md), [P05](tasks/P05.md), [P06](tasks/P06.md). + +## AI-01 — High / Verified + +Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. + +Evidence: [libs/core/di/src/http/security.ts:4](../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../libs/core/di/src/http/security.ts#L144). + +Disposition: [A01](tasks/A01.md), [A02](tasks/A02.md), [A03](tasks/A03.md), [A04](tasks/A04.md). + +## RES-01 — High / Verified + +Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. + +Evidence: [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168). + +Disposition: [D04](tasks/D04.md), [S05](tasks/S05.md), [R08](tasks/R08.md), [R09](tasks/R09.md), [A03](tasks/A03.md). + +## OPS-02 — High / Needs Investigation + +Paper/live operational readiness is not demonstrated end-to-end. Live is deliberately disabled; preserve that gate until feed, reconciliation and broker-specific recovery are verified. + +Evidence: [apps/stock/orchestrator/src/core/ModeManager.ts:33](../../../apps/stock/orchestrator/src/core/ModeManager.ts#L33); [apps/stock/orchestrator/src/container.ts:152](../../../apps/stock/orchestrator/src/container.ts#L152). + +Disposition: [S04](tasks/S04.md), [A04](tasks/A04.md), [O02](tasks/O02.md). + +## Corrections to over-broad audit conclusions + +- The first web workflow is not missing: real list/detail/routes, transactional dispatch and committed-state websocket updates exist. W01–W04 repair and verify it. +- Durable recovery and frozen data are implemented, not planned placeholders. Preserve them through S03; do not replace them for language uniformity. +- Native callback support is explicitly unavailable; NAPI types alone do not imply TS strategies already run in Rust replay. +- Future/native/experimental strategy files and Python research routines are not project-gated runtime capabilities. Do not enable them simply because names appear in a dropdown. +- Provider-adjusted data is not automatically executable corporate-action accounting. Hashing a dataset does not establish point-in-time correctness. +- No runtime evidence here establishes real broker reliability. Live-disabled guards remain intact. +- Exact hardware throughput, storage hot spots, memory limits and sandbox availability require P01/A02 measurements, not architectural confidence. +- Preservation rules in [cleanup audit](../../cleanup-audit.md) remain: reviewed calculations, restored helpers and useful research prototypes are not disposable dead code. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json new file mode 100644 index 00000000..eac63d70 --- /dev/null +++ b/docs/development/backlog/manifest.json @@ -0,0 +1,1765 @@ +{ + "schema_version": 1, + "plan_revision": "2026-10-22.3", + "repository_base": "b7aeca4", + "plan_status": "first_wave_authorized", + "execution_authorized": true, + "execution_scope": { + "authorized_by": "User: make a commit and start (2026-10-22)", + "tasks": ["C01", "C03", "C04", "W01"], + "permissions": ["planning_snapshot_commit", "isolated_implementation", "local_tests", "local_integration_review"], + "excluded": ["push", "pull_requests", "live_or_paper_operations", "implementation_commits_without_further_approval"], + "pending_policy_decisions": ["ADR-002", "ADR-003", "ADR-007"] + }, + "canonical_metadata": "This manifest alone owns task status, dependency edges, approvals, assignments and write locks. Task Markdown owns scope and acceptance criteria. Index/roadmap are derived views.", + "decisions": [ + { + "id": "ADR-001", + "file": "architecture/decisions/001-ownership.md", + "status": "user_mandated" + }, + { + "id": "ADR-002", + "file": "architecture/decisions/002-financial-policy.md", + "status": "approval_required" + }, + { + "id": "ADR-003", + "file": "architecture/decisions/003-time-and-datasets.md", + "status": "approval_required" + }, + { + "id": "ADR-004", + "file": "architecture/decisions/004-strategy-boundary.md", + "status": "proposed_for_plan_approval" + }, + { + "id": "ADR-005", + "file": "architecture/decisions/005-durable-cutover.md", + "status": "proposed_for_plan_approval" + }, + { + "id": "ADR-006", + "file": "architecture/decisions/006-research-product.md", + "status": "proposed_for_plan_approval" + }, + { + "id": "ADR-007", + "file": "architecture/decisions/007-ai-boundary.md", + "status": "approval_required" + }, + { + "id": "ADR-008", + "file": "architecture/decisions/008-performance.md", + "status": "proposed_with_measurement_gate" + } + ], + "epics": [ + { + "id": "E1", + "title": "Immediate correctness and runtime containment" + }, + { + "id": "E2", + "title": "Canonical Rust financial engine" + }, + { + "id": "E3", + "title": "Point-in-time datasets and features" + }, + { + "id": "E4", + "title": "TypeScript strategies and durable paper integration" + }, + { + "id": "E5", + "title": "Existing web backtest vertical slice" + }, + { + "id": "E6", + "title": "Research product, provenance and validation" + }, + { + "id": "E7", + "title": "Measured research throughput" + }, + { + "id": "E8", + "title": "Authorized, isolated AI research" + }, + { + "id": "E9", + "title": "Migration and operational safeguards" + } + ], + "first_wave": [ + "C01", + "C03", + "C04", + "W01" + ], + "tasks": [ + { + "id": "C01", + "title": "Correct native terminal valuation", + "epic": "E1", + "priority": "P0", + "severity": "Critical", + "status": "ready", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/C01.md", + "findings": [ + "FIN-02" + ], + "complexity": "S", + "specialization": "Rust financial correctness", + "write_locks": [ + "legacy-native-finance" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "C02", + "title": "Reject malformed native data and preserve milliseconds", + "epic": "E1", + "priority": "P1", + "severity": "High", + "status": "ready", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/C02.md", + "findings": [ + "DAT-02" + ], + "complexity": "S", + "specialization": "Rust/NAPI boundary", + "write_locks": [ + "native-public-api" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "C03", + "title": "Close the existing TypeScript fee-funding hole", + "epic": "E1", + "priority": "P0", + "severity": "Critical", + "status": "ready", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/C03.md", + "findings": [ + "FIN-03" + ], + "complexity": "M", + "specialization": "Trading infrastructure implementation", + "write_locks": [ + "ts-execution-model" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "C04", + "title": "Make partial runtime initialization recoverable", + "epic": "E1", + "priority": "P1", + "severity": "High", + "status": "ready", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/C04.md", + "findings": [ + "RUN-02" + ], + "complexity": "S", + "specialization": "Trading infrastructure implementation", + "write_locks": [ + "runtime-composition" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "C05", + "title": "Create economic regression fixtures independent of implementations", + "epic": "E1", + "priority": "P0", + "severity": "Critical", + "status": "merged", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/C05.md", + "findings": [ + "FIN-01", + "FIN-02", + "FIN-03", + "FIN-04", + "FIN-06", + "KEEP-01" + ], + "complexity": "M", + "specialization": "Quantitative correctness/test engineering", + "write_locks": [], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Do not execute: responsibility absorbed into F01", + "merged_into": "F01" + }, + { + "id": "C06", + "title": "Contain legacy research/paper interference without a second runtime", + "epic": "E1", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "C04" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/C06.md", + "findings": [ + "RUN-01", + "KEEP-01" + ], + "complexity": "S", + "specialization": "Trading infrastructure implementation", + "write_locks": [ + "runtime-composition" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "F01", + "title": "Define the minimal financial contract and economic fixtures", + "epic": "E2", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [], + "decision_dependencies": [ + "ADR-002", + "ADR-003", + "ADR-004" + ], + "task_file": "backlog/tasks/F01.md", + "findings": [ + "FIN-05", + "FIN-03", + "FIN-04" + ], + "complexity": "M", + "specialization": "Rust financial contract owner", + "write_locks": [ + "financial-contract" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "F02", + "title": "Implement one owner-aware financial ledger", + "epic": "E2", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "F01" + ], + "decision_dependencies": [ + "ADR-002" + ], + "task_file": "backlog/tasks/F02.md", + "findings": [ + "FIN-02", + "FIN-03", + "FIN-05", + "KEEP-01" + ], + "complexity": "L", + "specialization": "Rust accounting", + "write_locks": [ + "financial-contract", + "rust-ledger" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "F03", + "title": "Add strategy-owned position books and fill allocations", + "epic": "E2", + "priority": "P0", + "severity": "Critical", + "status": "merged", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/F03.md", + "findings": [ + "FIN-04", + "STR-01" + ], + "complexity": "M", + "specialization": "Rust portfolio accounting", + "write_locks": [], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Do not execute: responsibility absorbed into F02", + "merged_into": "F02" + }, + { + "id": "F04", + "title": "Enforce cash reservations and portfolio risk centrally", + "epic": "E2", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "F02" + ], + "decision_dependencies": [ + "ADR-002", + "ADR-003" + ], + "task_file": "backlog/tasks/F04.md", + "findings": [ + "FIN-03", + "FIN-06" + ], + "complexity": "L", + "specialization": "Rust financial risk", + "write_locks": [ + "rust-ledger", + "risk-policy" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "F05", + "title": "Unify matching and order lifecycle on the ledger", + "epic": "E2", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "F04" + ], + "decision_dependencies": [ + "ADR-003" + ], + "task_file": "backlog/tasks/F05.md", + "findings": [ + "FIN-01", + "FIN-05", + "FIN-06", + "KEEP-01" + ], + "complexity": "L", + "specialization": "Rust execution semantics", + "write_locks": [ + "rust-matching", + "financial-contract" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [ + "F06" + ] + }, + { + "id": "F06", + "title": "Implement deterministic replay once, with linear historical traversal", + "epic": "E2", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "F05", + "D01", + "P01" + ], + "decision_dependencies": [ + "ADR-003" + ], + "task_file": "backlog/tasks/F06.md", + "findings": [ + "FIN-01", + "DAT-01", + "PER-01" + ], + "complexity": "M", + "specialization": "Rust deterministic replay", + "write_locks": [ + "rust-replay" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "F07", + "title": "Expose bounded Rust step sessions through existing NAPI workers", + "epic": "E2", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "F06", + "C02" + ], + "decision_dependencies": [ + "ADR-004" + ], + "task_file": "backlog/tasks/F07.md", + "findings": [ + "FIN-05", + "PER-01", + "KEEP-02" + ], + "complexity": "M", + "specialization": "Rust/TypeScript integration", + "write_locks": [ + "native-public-api", + "worker-protocol" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "F08", + "title": "Publish canonical metrics and versioned result projections", + "epic": "E2", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "F06" + ], + "decision_dependencies": [ + "ADR-002", + "ADR-003" + ], + "task_file": "backlog/tasks/F08.md", + "findings": [ + "FIN-07", + "WEB-04" + ], + "complexity": "M", + "specialization": "Quant analytics/Rust integration", + "write_locks": [ + "result-contract" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "D01", + "title": "Introduce availability-aware dataset v2", + "epic": "E3", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [], + "decision_dependencies": [ + "ADR-003" + ], + "task_file": "backlog/tasks/D01.md", + "findings": [ + "DAT-01", + "DAT-03", + "KEEP-02" + ], + "complexity": "M", + "specialization": "TypeScript trading infrastructure", + "write_locks": [ + "dataset-contract" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "D02", + "title": "Connect supported intraday storage to research datasets", + "epic": "E3", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "D01" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/D02.md", + "findings": [ + "DAT-04" + ], + "complexity": "M", + "specialization": "TypeScript trading infrastructure", + "write_locks": [ + "storage-adapters" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "D03", + "title": "Add dataset eligibility and corporate-action safeguards", + "epic": "E3", + "priority": "P1", + "severity": "High", + "status": "merged", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/D03.md", + "findings": [ + "DAT-03", + "DAT-01" + ], + "complexity": "M", + "specialization": "TypeScript trading infrastructure", + "write_locks": [], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Do not execute: responsibility absorbed into D01", + "merged_into": "D01" + }, + { + "id": "D04", + "title": "Provide prefix-safe shared feature calculation", + "epic": "E3", + "priority": "P1", + "severity": "High", + "status": "deferred", + "dependencies": [ + "S01", + "P01" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/D04.md", + "findings": [ + "STR-01", + "RES-01", + "KEEP-02" + ], + "complexity": "M", + "specialization": "Quantitative feature engineering", + "write_locks": [ + "feature-contract" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Only after profiling demonstrates repeated identical feature work; use reviewed incremental calculations directly first.", + "release_gates": [] + }, + { + "id": "S01", + "title": "Run deterministic TypeScript decisions on Rust sessions", + "epic": "E4", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "F07" + ], + "decision_dependencies": [ + "ADR-004", + "ADR-005" + ], + "task_file": "backlog/tasks/S01.md", + "findings": [ + "FIN-05", + "STR-01", + "KEEP-01" + ], + "complexity": "M", + "specialization": "TypeScript trading infrastructure", + "write_locks": [ + "strategy-contract", + "worker-protocol" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "S02", + "title": "Adapt one SMA strategy for the first canonical path", + "epic": "E4", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "S01" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/S02.md", + "findings": [ + "STR-01", + "FIN-04" + ], + "complexity": "M", + "specialization": "TypeScript strategy/quant engineering", + "write_locks": [ + "strategy-builtins" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "S03", + "title": "Adapt durable paper transactions to Rust financial reducers", + "epic": "E4", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "S01", + "C06" + ], + "decision_dependencies": [ + "ADR-005" + ], + "task_file": "backlog/tasks/S03.md", + "findings": [ + "KEEP-01", + "FIN-05" + ], + "complexity": "L", + "specialization": "Durable execution/Rust integration", + "write_locks": [ + "ts-execution-model", + "paper-transaction", + "financial-contract" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "S04", + "title": "Establish a verified paper feed and operator safety gate", + "epic": "E4", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "S02", + "S03" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/S04.md", + "findings": [ + "OPS-02", + "FIN-06" + ], + "complexity": "M", + "specialization": "TypeScript trading infrastructure", + "write_locks": [ + "paper-runtime" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "S05", + "title": "Add a small composable multi-signal regime example", + "epic": "E4", + "priority": "P2", + "severity": "Medium", + "status": "blocked", + "dependencies": [ + "S02", + "F08" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/S05.md", + "findings": [ + "STR-01", + "FIN-04", + "RES-01" + ], + "complexity": "M", + "specialization": "Quant strategy research", + "write_locks": [ + "example-strategy" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [ + "R08" + ] + }, + { + "id": "S06", + "title": "Retire duplicate simulator paths after cutover proof", + "epic": "E4", + "priority": "P2", + "severity": "Medium", + "status": "blocked", + "dependencies": [ + "S03", + "S04", + "R05" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/S06.md", + "findings": [ + "FIN-05", + "STR-01", + "KEEP-01" + ], + "complexity": "M", + "specialization": "TypeScript trading infrastructure", + "write_locks": [ + "runtime-composition", + "ts-execution-model" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "W01", + "title": "Make existing run controls and selection truthful", + "epic": "E5", + "priority": "P1", + "severity": "High", + "status": "ready", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/W01.md", + "findings": [ + "WEB-02", + "WEB-01" + ], + "complexity": "M", + "specialization": "Full-stack React/API", + "write_locks": [ + "web-backtest-detail", + "websocket-hook", + "frontend-test-dependencies" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "W02", + "title": "Expose result provenance and legacy correctness limitations", + "epic": "E5", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "W01" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/W02.md", + "findings": [ + "WEB-04", + "FIN-01", + "FIN-07" + ], + "complexity": "M", + "specialization": "Full-stack research UX", + "write_locks": [ + "web-backtest-detail", + "result-contract" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "W03", + "title": "Separate save, submit and repeat-safe run creation", + "epic": "E5", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "O01" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/W03.md", + "findings": [ + "WEB-03", + "WEB-01" + ], + "complexity": "M", + "specialization": "Full-stack durable workflow", + "write_locks": [ + "web-backtest-detail", + "web-backtest-service", + "sql-migrations" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "W04", + "title": "Verify the first research vertical slice in a browser", + "epic": "E5", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "W01", + "W02", + "W03", + "C06" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/W04.md", + "findings": [ + "WEB-01", + "WEB-02", + "KEEP-02" + ], + "complexity": "M", + "specialization": "Full-stack test engineering", + "write_locks": [ + "browser-harness" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "R01", + "title": "Persist immutable strategy versions and parameter schemas", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "O01" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R01.md", + "findings": [ + "WEB-01", + "WEB-04", + "STR-01" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "sql-migrations", + "strategy-catalog-api" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "R02", + "title": "Deliver strategy catalog and version-aware backtest setup", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R01", + "W03" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R02.md", + "findings": [ + "WEB-01", + "STR-01" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "web-backtest-detail", + "web-strategies" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [ + "W04" + ] + }, + { + "id": "R03", + "title": "Add projects, hypotheses and evidence-linked findings APIs", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R01", + "R10" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R03.md", + "findings": [ + "WEB-01", + "WEB-04", + "WEB-05" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "sql-migrations", + "research-api" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "R04", + "title": "Deliver research workspace and save-findings flow", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R03", + "W02" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R04.md", + "findings": [ + "WEB-01", + "WEB-04" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "web-research", + "web-backtest-detail" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [ + "W04" + ] + }, + { + "id": "R05", + "title": "Freeze complete provenance and cut over durable canonical runs", + "epic": "E6", + "priority": "P0", + "severity": "Critical", + "status": "blocked", + "dependencies": [ + "F08", + "S02", + "R01", + "R10", + "D01", + "W03", + "C06" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R05.md", + "findings": [ + "WEB-04", + "KEEP-02", + "FIN-05" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "result-contract", + "web-backtest-service", + "web-backtest-detail" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "R06", + "title": "Create immutable experiments and bounded sweep expansion", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R05" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R06.md", + "findings": [ + "WEB-01", + "WEB-04", + "KEEP-02" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "sql-migrations", + "experiment-api" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "R07", + "title": "Deliver sweep configuration and comparable-result views", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R06" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R07.md", + "findings": [ + "WEB-01", + "FIN-07", + "WEB-04" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "web-experiments" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [ + "W04" + ] + }, + { + "id": "R08", + "title": "Add bounded chronological and reset-segment validation", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R06" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R08.md", + "findings": [ + "RES-01", + "DAT-01", + "FIN-07" + ], + "complexity": "M", + "specialization": "Quantitative research integrity", + "write_locks": [ + "validation-contract", + "sql-migrations" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "R09", + "title": "Expose validation, cost and regime evidence in the workbench", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R07", + "R08" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R09.md", + "findings": [ + "RES-01", + "WEB-01" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "web-experiments" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [], + "conditional_release_gates": [ + { + "when": "Regime comparison is enabled", + "tasks": [ + "S05" + ] + }, + { + "when": "Saving or linking a research finding is enabled", + "tasks": [ + "R03" + ] + } + ] + }, + { + "id": "R10", + "title": "Protect retained research evidence and artifact integrity", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R01" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R10.md", + "findings": [ + "WEB-05", + "WEB-04" + ], + "complexity": "M", + "specialization": "Full-stack research product", + "write_locks": [ + "sql-migrations", + "web-backtest-service" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "R11", + "title": "Select and reuse frozen datasets in the workbench", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "D01", + "O01" + ], + "decision_dependencies": [ + "ADR-003", + "ADR-006" + ], + "task_file": "backlog/tasks/R11.md", + "findings": [ + "KEEP-02", + "DAT-01", + "WEB-04" + ], + "complexity": "M", + "specialization": "Full-stack market data/research", + "write_locks": [ + "dataset-contract", + "web-backtest-detail", + "web-backtest-service" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [ + "W04" + ] + }, + { + "id": "R12", + "title": "Reproduce an original run separately from rerunning current settings", + "epic": "E6", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R05", + "W04" + ], + "decision_dependencies": [ + "ADR-006" + ], + "task_file": "backlog/tasks/R12.md", + "findings": [ + "WEB-03", + "WEB-04", + "KEEP-02" + ], + "complexity": "S", + "specialization": "Full-stack reproducible research", + "write_locks": [ + "web-backtest-service", + "web-backtest-detail" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "P01", + "title": "Measure existing research paths before extending the benchmark", + "epic": "E7", + "priority": "P2", + "severity": "Medium", + "status": "ready", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/P01.md", + "findings": [ + "PER-01", + "FIN-05", + "KEEP-02" + ], + "complexity": "M", + "specialization": "Performance/infrastructure engineering", + "write_locks": [ + "benchmark-harness" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "P02", + "title": "Remove measured replay queue and hot-loop overhead", + "epic": "E7", + "priority": "P2", + "severity": "Medium", + "status": "merged", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/P02.md", + "findings": [ + "PER-01" + ], + "complexity": "M", + "specialization": "Performance/infrastructure engineering", + "write_locks": [], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Do not execute: responsibility absorbed into F06", + "merged_into": "F06" + }, + { + "id": "P03", + "title": "Reuse validated datasets within bounded native workers", + "epic": "E7", + "priority": "P2", + "severity": "Medium", + "status": "deferred", + "dependencies": [ + "F07", + "P01" + ], + "decision_dependencies": [ + "ADR-004", + "ADR-008" + ], + "task_file": "backlog/tasks/P03.md", + "findings": [ + "PER-01", + "KEEP-02" + ], + "complexity": "M", + "specialization": "Performance/infrastructure engineering", + "write_locks": [ + "worker-protocol", + "native-public-api" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Only after measured repeated dataset admission is a material sweep cost; not a prerequisite for parallel trials.", + "release_gates": [] + }, + { + "id": "P04", + "title": "Schedule deterministic batches across a bounded worker pool", + "epic": "E7", + "priority": "P2", + "severity": "Medium", + "status": "blocked", + "dependencies": [ + "F07", + "R06", + "C06", + "P01" + ], + "decision_dependencies": [ + "ADR-008" + ], + "task_file": "backlog/tasks/P04.md", + "findings": [ + "PER-01", + "KEEP-02" + ], + "complexity": "M", + "specialization": "Performance/infrastructure engineering", + "write_locks": [ + "worker-pool", + "web-backtest-dispatch" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "P05", + "title": "Separate result summaries from paged detail payloads", + "epic": "E7", + "priority": "P2", + "severity": "Medium", + "status": "deferred", + "dependencies": [ + "R06", + "P01" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/P05.md", + "findings": [ + "PER-01", + "WEB-01" + ], + "complexity": "M", + "specialization": "Performance/infrastructure engineering", + "write_locks": [ + "result-contract", + "web-backtest-service", + "web-experiments" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Only after measured trade-detail payload/query/render cost; simple summary projections ship in R06.", + "release_gates": [] + }, + { + "id": "P06", + "title": "Conditionally add a minimal Rust-executed strategy plan", + "epic": "E7", + "priority": "P2", + "severity": "Medium", + "status": "deferred", + "dependencies": [ + "P04", + "S01" + ], + "decision_dependencies": [ + "ADR-008" + ], + "task_file": "backlog/tasks/P06.md", + "findings": [ + "FIN-05", + "PER-01" + ], + "complexity": "M", + "specialization": "Rust/TS performance compiler boundary", + "write_locks": [ + "strategy-contract", + "native-public-api" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Owner go/no-go after representative profiling and explicit prototype budget; no fixed 20%/1.5x magic thresholds.", + "release_gates": [] + }, + { + "id": "A01", + "title": "Add research-only principals and durable job budgets", + "epic": "E8", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "R06", + "O01" + ], + "decision_dependencies": [ + "ADR-007" + ], + "task_file": "backlog/tasks/A01.md", + "findings": [ + "AI-01", + "WEB-01" + ], + "complexity": "M", + "specialization": "Backend security/durable scheduling", + "write_locks": [ + "auth-contract", + "experiment-api" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "A02", + "title": "Isolate untrusted TypeScript strategy builds and decisions", + "epic": "E8", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "A01", + "S01", + "P01" + ], + "decision_dependencies": [ + "ADR-007" + ], + "task_file": "backlog/tasks/A02.md", + "findings": [ + "AI-01", + "STR-01" + ], + "complexity": "L", + "specialization": "Process isolation/security", + "write_locks": [ + "sandbox-contract", + "worker-protocol" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "A03", + "title": "Implement an evidence-linked AI research workflow client", + "epic": "E8", + "priority": "P2", + "severity": "Medium", + "status": "blocked", + "dependencies": [ + "A02", + "R08", + "R03" + ], + "decision_dependencies": [ + "ADR-007" + ], + "task_file": "backlog/tasks/A03.md", + "findings": [ + "AI-01", + "RES-01", + "WEB-04" + ], + "complexity": "M", + "specialization": "AI research integration", + "write_locks": [ + "ai-workflow-client" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "A04", + "title": "Add human-reviewed promotion to paper deployment", + "epic": "E8", + "priority": "P2", + "severity": "Medium", + "status": "blocked", + "dependencies": [ + "S04", + "R09", + "A01", + "R01" + ], + "decision_dependencies": [ + "ADR-007", + "ADR-005" + ], + "task_file": "backlog/tasks/A04.md", + "findings": [ + "OPS-02", + "AI-01", + "KEEP-01" + ], + "complexity": "M", + "specialization": "Full-stack paper trading integration", + "write_locks": [ + "paper-runtime", + "web-strategies", + "sql-migrations" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "O01", + "title": "Serialize additive schema migrations safely", + "epic": "E9", + "priority": "P1", + "severity": "High", + "status": "ready", + "dependencies": [], + "decision_dependencies": [], + "task_file": "backlog/tasks/O01.md", + "findings": [ + "OPS-01" + ], + "complexity": "S", + "specialization": "PostgreSQL/backend infrastructure", + "write_locks": [ + "sql-migrations" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": null, + "release_gates": [] + }, + { + "id": "O02", + "title": "Expose truthful research and paper readiness diagnostics", + "epic": "E9", + "priority": "P1", + "severity": "High", + "status": "deferred", + "dependencies": [ + "S04" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/O02.md", + "findings": [ + "OPS-02", + "WEB-02", + "KEEP-02" + ], + "complexity": "M", + "specialization": "Infrastructure/observability", + "write_locks": [ + "readiness-api" + ], + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Optional cross-service monitoring expansion; required run diagnostics belong to W01/F07 and paper readiness to S04.", + "release_gates": [] + } + ], + "review_note": "Independent skeptical revision: four superseded tasks retain stable IDs; deferred work is not a dependency of scheduled tasks. Release gates are distinct from implementation prerequisites." +} diff --git a/docs/development/backlog/tasks/A01.md b/docs/development/backlog/tasks/A01.md new file mode 100644 index 00000000..5df3bf63 --- /dev/null +++ b/docs/development/backlog/tasks/A01.md @@ -0,0 +1,65 @@ +# A01 — Add research-only principals and durable job budgets + +Parent epic: E8. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Backend security/durable scheduling. + +Scheduling source of truth: [manifest entry A01](../manifest.json). 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 + +- **AI-01 — Verified:** Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. [libs/core/di/src/http/security.ts:4](../../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../../libs/core/di/src/http/security.ts#L144). +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). + +## Intended behavior and implementation scope + +Extend the small existing auth boundary with stable owner/agent identities and research-scoped permissions. Enforce per-agent concurrent-job/trial/time/resource budgets at admission and execution; record actor and audit events. Do not reinstate global historical data truncation limits. + +Measurable benefit: Allows autonomous research without autonomous brokerage control. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- libs/core/di/src/http/security.ts +- apps/stock/web-api/src/routes/ +- apps/stock/web-api/src/services/ (admission) +- apps/stock/orchestrator/src/backtest/BacktestRunner.ts + +Write locks: auth-contract, experiment-api. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R06](R06.md), [O01](O01.md) integrated. + +Architecture decisions: ADR-007. 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 + +- AI research token can register hypotheses and submit authorized experiments but cannot call paper/live administration or mutate financial constraints. +- Budget reservations are transactional and released on failure/cancellation/restart; retries do not double-charge. +- User-configured budgets and rejections are visible; operator's large trusted datasets remain supported. + +## Mandatory tests + +- research_token_live_denied, budget_concurrent_admission, budget_recovery, actor_audit. +- Existing security/browser-session/CSRF tests; do not break current operator workflow. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. + +## Web/API contract and user states + +- API: Research-scoped credential routes/claims; typed403/429 with budget diagnostics on same experiment APIs. +- Backend/data dependencies: Minimal principal/budget/audit persistence; existing local owner maps to one principal. +- Loading/error/empty behavior: API identifies quota wait vs invalid request; UI can show admission error without losing experiment draft. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/A02.md b/docs/development/backlog/tasks/A02.md new file mode 100644 index 00000000..188d6066 --- /dev/null +++ b/docs/development/backlog/tasks/A02.md @@ -0,0 +1,58 @@ +# A02 — Isolate untrusted TypeScript strategy builds and decisions + +Parent epic: E8. Priority/severity: P1 / High. Relative complexity: L. Recommended specialization: Process isolation/security. + +Scheduling source of truth: [manifest entry A02](../manifest.json). 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 + +- **AI-01 — Verified:** Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. [libs/core/di/src/http/security.ts:4](../../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../../libs/core/di/src/http/security.ts#L144). +- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). + +## Intended behavior and implementation scope + +Compile/import AI artifacts only in an OS-restricted process/container without network, secrets, DB, broker access or full future dataset. Engine supervisor sends prefix-only context and receives intents through a small IPC protocol. Apply wall/CPU/memory limits; pin artifact dependencies. node:vm alone is not a security boundary. + +Measurable benefit: Makes arbitrary AI code execution a contained research capability. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/orchestrator/src/backtest/ (isolated strategy host) +- apps/stock/web-api/src/services/ (artifact registration) +- scripts/ (sandbox launch profile) + +Write locks: sandbox-contract, worker-protocol. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [A01](A01.md), [S01](S01.md), [P01](P01.md) integrated. + +Architecture decisions: ADR-007. 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 + +- Malicious imports, filesystem/network/env probing and infinite loops fail safely without affecting the API/paper process. +- Candidate cannot access future bars through files/native handles; only the supervisor owns financial engine and data. +- Trusted reviewed artifact fast path is an explicit human promotion, never self-selected by code. + +## Mandatory tests + +- deny_network_secret_read_child_spawn, infinite_loop_kill, malformed_intent, future_context_exfiltration, worker_cleanup. +- Sandbox availability check fails closed; benchmark IPC overhead separately from trusted NAPI path. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Native runtime/process privileges can invalidate the sandbox; independent security review required. +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. diff --git a/docs/development/backlog/tasks/A03.md b/docs/development/backlog/tasks/A03.md new file mode 100644 index 00000000..ffead119 --- /dev/null +++ b/docs/development/backlog/tasks/A03.md @@ -0,0 +1,63 @@ +# A03 — Implement an evidence-linked AI research workflow client + +Parent epic: E8. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: AI research integration. + +Scheduling source of truth: [manifest entry A03](../manifest.json). 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 + +- **AI-01 — Verified:** Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. [libs/core/di/src/http/security.ts:4](../../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../../libs/core/di/src/http/security.ts#L144). +- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). + +## Intended behavior and implementation scope + +Implement a typed authorized research API client/example using backend R03/R06/R08 contracts, independent of whether project UI is complete. Propose hypothesis, register candidate, preview/submit bounded experiments, inspect all outcomes, request validation and save run-linked findings. No new AI service/framework or mandatory vendor/model SDK. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/web-api/src/routes/ (research API contracts) +- scripts/ (research client example) +- test/integration/ (AI research flow) + +Write locks: ai-workflow-client. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [A02](A02.md), [R08](R08.md), [R03](R03.md) integrated. + +Architecture decisions: ADR-007. 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 + +- Every AI finding links immutable run/artifact IDs and distinguishes proposed hypotheses from validated evidence. +- An execution failure is returned as a diagnostic, not filtered out of candidate history. +- Client cannot promote itself to paper/live or alter operator account risk policy. + +## Mandatory tests + +- ai_hypothesis_to_validated_finding_contract, bounded_search_rejected, failed_trial_reported, evidence_mismatch_rejected. +- Replay the workflow with deterministic fake model suggestions; no paid model call required for CI. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. + +## Web/API contract and user states + +- API: Reuse projects/hypotheses/versions/experiments/artifacts endpoints and diagnostics; publish typed request/response examples. +- Backend/data dependencies: No second task store or AI-only results database. +- Loading/error/empty behavior: Client handles202 polling,429 budgets,409 conflicts and terminal failures; UI shows AI authorship in existing workspace. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/A04.md b/docs/development/backlog/tasks/A04.md new file mode 100644 index 00000000..411f46fc --- /dev/null +++ b/docs/development/backlog/tasks/A04.md @@ -0,0 +1,64 @@ +# A04 — Add human-reviewed promotion to paper deployment + +Parent epic: E8. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Full-stack paper trading integration. + +Scheduling source of truth: [manifest entry A04](../manifest.json). 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 + +- **OPS-02 — Needs Investigation:** Paper/live operational readiness is not demonstrated end-to-end. Live is deliberately disabled; preserve that gate until feed, reconciliation and broker-specific recovery are verified. [apps/stock/orchestrator/src/core/ModeManager.ts:33](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L33); [apps/stock/orchestrator/src/container.ts:152](../../../../apps/stock/orchestrator/src/container.ts#L152). +- **AI-01 — Verified:** Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. [libs/core/di/src/http/security.ts:4](../../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../../libs/core/di/src/http/security.ts#L144). +- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151). + +## Intended behavior and implementation scope + +Human-only paper deployment of a frozen version requires S04 readiness, research-only permission separation and explicit evidence. It must work for human-authored as well as AI-originated strategies; the A03 AI client is not a prerequisite. Reuse version/evidence APIs and add a deployment record only when this flow is implemented. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/web-app/src/features/strategies/ +- apps/stock/web-api/src/routes/ (paper promotion) +- apps/stock/orchestrator/src/paper/PaperTradingManager.ts +- database/postgres/init/ (optional deployment table) + +Write locks: paper-runtime, web-strategies, sql-migrations. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [S04](S04.md), [R09](R09.md), [A01](A01.md), [R01](R01.md) integrated. + +Architecture decisions: ADR-007, ADR-005. 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 + +- Research-only token cannot create/activate a deployment; operator must review OOS/cost evidence and limitations. +- Only paper deployment is offered; live remains explicitly unavailable. +- Promotion never overwrites existing account capital/checkpoints or silently upgrades strategy state. + +## Mandatory tests + +- human_only_promotion, immutable_deployment_version, incompatible_checkpoint_block, no_live_option. +- Browser AI candidate -> evidence review -> paper status workflow. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. + +## Web/API contract and user states + +- API: POST paper-deployments and explicit activate/halt operations for operator only; read-only history for research clients. +- Backend/data dependencies: Optional deployments table with version/account/evidence FKs, existing durable paper state. +- Loading/error/empty behavior: Not-ready reasons, approval pending, active/halted/failed; no cosmetic success before backend confirmation. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/C01.md b/docs/development/backlog/tasks/C01.md new file mode 100644 index 00000000..ac36e7f1 --- /dev/null +++ b/docs/development/backlog/tasks/C01.md @@ -0,0 +1,56 @@ +# C01 — Correct native terminal valuation + +Parent epic: E1. Priority/severity: P0 / Critical. Relative complexity: S. Recommended specialization: Rust financial correctness. + +Scheduling source of truth: [manifest entry C01](../manifest.json). 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 + +- **FIN-02 — Verified:** Native forced liquidation occurs after the last equity mark; reported final value reads that earlier mark, omitting terminal costs. [apps/stock/engine/src/backtest/engine.rs:135](../../../../apps/stock/engine/src/backtest/engine.rs#L135); [apps/stock/engine/src/backtest/simple_results.rs:308](../../../../apps/stock/engine/src/backtest/simple_results.rs#L308). + +## Intended behavior and implementation scope + +Correct the current native forced-liquidation path only: mark the final account after all closing fills and update the existing terminal-time equity sample instead of appending a duplicate timestamp. Preserve current matching, sizing, liquidation and fee policies. Do not implement the new engine here. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/engine/src/backtest/engine.rs +- apps/stock/engine/src/backtest/simple_results.rs +- test/integration/native-terminal-equity.test.ts (new, only if public API can exercise the same fixture) + +Write locks: legacy-native-finance. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- A deterministic test strategy/direct internal fixture buys exactly1 share at4 from cash10, with1% entry/exit fees and zero slippage: final cash/equity/finalValue=9.92 and total fees=0.08. +- Positions eligible for liquidation in these fixtures are flat; every closing fill is included once, including multiple symbols. Preserve the existing micro-position threshold; any retained residual still contributes its marked value to final equity. +- No-position/zero-fee behavior remains correct; there is exactly one final-time equity sample. + +## Mandatory tests + +- Inline Rust fixtures: terminal_fee_equity, terminal_no_positions, terminal_zero_fee, terminal_multiple_symbols, terminal_timestamp_unique. +- cargo test -p engine --lib --offline; build current addon with bun run --cwd apps/stock/engine build:debug; then bun test test/integration/backtest-result-mapping.test.ts test/integration/backtest-ledger.test.ts. +- If a new native-terminal-equity.test.ts is added, run it too. Do not derive expected quantity from production position sizing. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/C02.md b/docs/development/backlog/tasks/C02.md new file mode 100644 index 00000000..6f8f9ba4 --- /dev/null +++ b/docs/development/backlog/tasks/C02.md @@ -0,0 +1,55 @@ +# C02 — Reject malformed native data and preserve milliseconds + +Parent epic: E1. Priority/severity: P1 / High. Relative complexity: S. Recommended specialization: Rust/NAPI boundary. + +Scheduling source of truth: [manifest entry C02](../manifest.json). 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 + +- **DAT-02 — Verified:** Native input parsing silently discards malformed rows and truncates timestamps to seconds. [apps/stock/engine/src/api/backtest.rs:217](../../../../apps/stock/engine/src/api/backtest.rs#L217); [apps/stock/engine/src/api/backtest.rs:290](../../../../apps/stock/engine/src/api/backtest.rs#L290). + +## Intended behavior and implementation scope + +Validate all input rows before admission; return row-indexed errors instead of filter_map dropping rows. Preserve epoch milliseconds, reject non-finite/invalid OHLC and duplicate conflicting identities. + +Measurable benefit: Stops silent dataset corruption. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/engine/src/api/backtest.rs +- test/integration/ingestion-backtest.test.ts + +Write locks: native-public-api. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- One invalid row causes an atomic load failure with its index; valid neighbors are not partially installed. +- Events at 1001ms and 1999ms remain distinct and ordered; unknown data types fail explicitly. + +## Mandatory tests + +- Native bridge tests invalid OHLC/NaN/missing field/unsupported type and sub-second round trip. +- Existing native load fixtures remain accepted. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## 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. diff --git a/docs/development/backlog/tasks/C03.md b/docs/development/backlog/tasks/C03.md new file mode 100644 index 00000000..7286527e --- /dev/null +++ b/docs/development/backlog/tasks/C03.md @@ -0,0 +1,57 @@ +# C03 — Close the existing TypeScript fee-funding hole + +Parent epic: E1. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Trading infrastructure implementation. + +Scheduling source of truth: [manifest entry C03](../manifest.json). 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 + +- **FIN-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234). + +## Intended behavior and implementation scope + +Narrow interim fix: retain the current legacy gross-exposure financing model and its reducing-order exemption. Add projected unpaid commissions to the existing non-reducing capital test, using proposed remaining quantity plus pending remaining quantities and each order's frozen commission policy. At fill, exclude the current order from other reservations and use its stored policy. Paid fees already reduce current equity and must not be counted again. No new cash-reservation table, schema, long-only rule or independent financing subsystem. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/orchestrator/src/execution/model.ts +- apps/stock/orchestrator/src/execution/SimulationExecution.ts +- test/integration/fee-funding.test.ts (new) + +Write locks: ts-execution-model. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Under existing non-reducing policy:10000 cash, buy100@100,1% fee rejects without financial mutation; buy99@100 succeeds leaving1. +- Two zero-liquidity pending buys of50@100 with1% fees cannot both pass: reserved commitments would total10100. Cancellation releases the computed commitment. +- A99-share order filled10 then89 shares pays99 total commission and leaves1; duplicate events charge nothing twice. +- Existing short/reversal and risk-reducing behavior is unchanged. This fix does not claim the legacy financing model is cash-only or that insolvent short covers cannot create debt. + +## Mandatory tests + +- Dedicated test/integration/fee-funding.test.ts: fee_budget_10000, fee_budget_99, pending_fee_commitments, partial_fee_not_double_counted, cancelled_commitment_released, frozen_order_fee_policy. +- 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. +- Integration owner runs the existing disposable PostgreSQL order-execution suite before merge; no development trading DB. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/C04.md b/docs/development/backlog/tasks/C04.md new file mode 100644 index 00000000..e027f839 --- /dev/null +++ b/docs/development/backlog/tasks/C04.md @@ -0,0 +1,55 @@ +# C04 — Make partial runtime initialization recoverable + +Parent epic: E1. Priority/severity: P1 / High. Relative complexity: S. Recommended specialization: Trading infrastructure implementation. + +Scheduling source of truth: [manifest entry C04](../manifest.json). 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 + +- **RUN-02 — Verified:** Partial initialization can allocate services before isInitialized becomes true; shutdown exits early on that failure path. [apps/stock/orchestrator/src/core/ModeManager.ts:55](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L55); [apps/stock/orchestrator/src/core/ModeManager.ts:157](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L157). + +## Intended behavior and implementation scope + +Keep the successful lifecycle ordering. Register cleanup before each stage that may partially acquire resources; on initialization failure stop admission/feed, attempt all applicable cleanups, preserve the original initialization error and clear failed engine/config readiness. Retrying must be safe. Do not redesign runtime composition or add an imaginary native dispose method. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/orchestrator/src/core/ModeManager.ts +- test/integration/mode-lifecycle.test.ts + +Write locks: runtime-composition. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Inject failure in execution initialize, storage initialize, strategy restore and market initialize. Clean up the failing stage as well as previously acquired stages; untouched stages are not invented resources. +- Cleanup failure neither masks the original error nor prevents remaining cleanup; feed stops before strategy/account teardown. +- No successful modeChanged event is published on failure; engine/config access cannot expose failed readiness; a retry succeeds. +- Existing shutdown ordering and live-disabled validation remain unchanged. + +## Mandatory tests + +- bun test test/integration/mode-lifecycle.test.ts with initialization_failure_each_stage, partial_acquisition_cleanup, cleanup_preserves_original_error, failed_init_retry and no_success_event. +- bun run typecheck; bun run test:contracts. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/C05.md b/docs/development/backlog/tasks/C05.md new file mode 100644 index 00000000..f323c2e7 --- /dev/null +++ b/docs/development/backlog/tasks/C05.md @@ -0,0 +1,5 @@ +# C05 — Merged into F01 + +This ID is retained for traceability and must not be claimed or implemented separately. + +Its required behavior, fixtures and tests are owned by [F01](F01.md). See [skeptical review](../../REVIEW.md) for the effort reduction and [manifest](../manifest.json) for canonical scheduling metadata. diff --git a/docs/development/backlog/tasks/C06.md b/docs/development/backlog/tasks/C06.md new file mode 100644 index 00000000..b3cec299 --- /dev/null +++ b/docs/development/backlog/tasks/C06.md @@ -0,0 +1,56 @@ +# C06 — Contain legacy research/paper interference without a second runtime + +Parent epic: E1. Priority/severity: P0 / Critical. Relative complexity: S. Recommended specialization: Trading infrastructure implementation. + +Scheduling source of truth: [manifest entry C06](../manifest.json). 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 + +- **RUN-01 — Verified:** TypeScript research preparation calls the shared mode manager, which shuts down the current mode, so a research job can interfere with paper runtime. [apps/stock/orchestrator/src/container.ts:101](../../../../apps/stock/orchestrator/src/container.ts#L101); [apps/stock/orchestrator/src/core/ModeManager.ts:47](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L47). +- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151). + +## Intended behavior and implementation scope + +Contain the legacy TS shared-mode hazard without building a second run-local TS execution framework. Use explicit composition roles: a shared paper runtime accepts only already-isolated native research; legacy TS research is allowed only in an explicit research-only composition with paper initialization/activation disabled. Reject unsafe combinations before mode mutation. Canonical TS strategies later use the Rust worker/session path. Keep the existing single-run busy guard. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/orchestrator/src/container.ts +- apps/stock/orchestrator/src/backtest/BacktestRunner.ts +- apps/stock/orchestrator/src/backtest/BacktestEngine.ts + +Write locks: runtime-composition. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [C04](C04.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Attempting a legacy TS run in a paper composition fails with a specific unsupported-combination diagnostic before paper shutdown, cash/checkpoint mutation or feed interruption. +- Explicit legacy research-only startup remains usable and cannot activate paper in that same composition. +- Native research alongside paper preserves paper lifecycle/account hashes; repeated cancelled/failed jobs do not alter them. + +## Mandatory tests + +- legacy_paper_combination_rejected_before_prepare, standalone_legacy_research_allowed, research_only_paper_activation_denied, native_paper_isolation. +- Existing backtest-workflow/typescript-backtest/mode-lifecycle suites; no new worker for legacy TS. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/D01.md b/docs/development/backlog/tasks/D01.md new file mode 100644 index 00000000..fa5062b6 --- /dev/null +++ b/docs/development/backlog/tasks/D01.md @@ -0,0 +1,61 @@ +# D01 — Introduce availability-aware dataset v2 + +Parent epic: E3. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: TypeScript trading infrastructure. + +Scheduling source of truth: [manifest entry D01](../manifest.json). 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 + +- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177). +- **DAT-03 — Verified:** Missing VWAP is replaced with typical price; reported volume and provider-adjusted prices are not a complete corporate-action execution model. [apps/stock/orchestrator/src/data/historical-dataset.ts:230](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L230); [libs/core/types/src/historical-data.ts:98](../../../../libs/core/types/src/historical-data.ts#L98). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Add interval start/end, availableAt, venue/calendar revision and source sequence to frozen events; preserve missing VWAP as missing. Keep v1 snapshots immutable. Convert daily session labels only with an explicit versioned calendar; fail closed for unknown venue/time semantics. Include per-series identity/timeframe so a run can select exactly one execution feed per instrument and separate feature-only series. + +Measurable benefit: Defines point-in-time truth before new replay logic. + +Absorb D03 in the same manifest version: record universe/as-of and corporate-action coverage, distinguish signal-adjusted from raw execution prices and retain limitations. Do not build an action feed or a correctness-gate evidence subsystem. Known unsupported action ranges reject executable policy; unknown coverage stays explicitly exploratory, never silently verified. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- libs/core/types/src/historical-data.ts +- apps/stock/orchestrator/src/data/historical-dataset.ts +- apps/stock/orchestrator/src/services/StorageService.ts + +Write locks: dataset-contract. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +Architecture decisions: ADR-003. 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 + +- A new manifest/hash is produced for every conversion; v1 hashes still verify. +- US daily bars become available at actual session end, including DST and half days; invalid/duplicate conflicts reject. +- Warmup and trade ranges are separate, with no invented VWAP or interpolation. + +## Mandatory tests + +- dataset_v1_compatibility, dataset_v2_hash, DST_half_day, missing_vwap, conflicting_duplicate. +- Future-suffix mutation does not change prior observable prefixes. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/D02.md b/docs/development/backlog/tasks/D02.md new file mode 100644 index 00000000..10e1b8df --- /dev/null +++ b/docs/development/backlog/tasks/D02.md @@ -0,0 +1,57 @@ +# D02 — Connect supported intraday storage to research datasets + +Parent epic: E3. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: TypeScript trading infrastructure. + +Scheduling source of truth: [manifest entry D02](../manifest.json). 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 + +- **DAT-04 — Verified:** Historical storage selects QuestDB or daily MongoDB; the Mongo path explicitly rejects intraday requests. Ingestion-to-research routing requires an executable provider/interval capability check. [apps/stock/orchestrator/src/services/StorageService.ts:287](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L287); [apps/stock/orchestrator/src/services/StorageService.ts:299](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L299). + +## Intended behavior and implementation scope + +Trace the actual intraday collection/schema, add the smallest provider adapter or correct routing, and expose an explicit provider/interval coverage capability. Keep a single normalized dataset admission path; do not migrate all storage systems. + +Measurable benefit: Makes supported intraday requests usable and honest. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- apps/stock/orchestrator/src/services/StorageService.ts +- apps/stock/data-ingestion/src/ +- test/integration/ingestion-backtest.test.ts + +Write locks: storage-adapters. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [D01](D01.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- A disposable ingested 5m fixture is retrieved through the research path with unchanged timestamps/OHLC/count. +- Unavailable ranges/providers return typed errors, never daily data or synthetic fallbacks. +- Record the verified ingestion collection/adapter in the task evidence before changing code. + +## Mandatory tests + +- ingest_5m_freeze_replay, unsupported_interval, missing_range, provider_priority. +- Hash the ingested normalized fixture and compare retrieval. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/D03.md b/docs/development/backlog/tasks/D03.md new file mode 100644 index 00000000..66dd9eeb --- /dev/null +++ b/docs/development/backlog/tasks/D03.md @@ -0,0 +1,5 @@ +# D03 — Merged into D01 + +This ID is retained for traceability and must not be claimed or implemented separately. + +Its required behavior, fixtures and tests are owned by [D01](D01.md). See [skeptical review](../../REVIEW.md) for the effort reduction and [manifest](../manifest.json) for canonical scheduling metadata. diff --git a/docs/development/backlog/tasks/D04.md b/docs/development/backlog/tasks/D04.md new file mode 100644 index 00000000..8c1aa483 --- /dev/null +++ b/docs/development/backlog/tasks/D04.md @@ -0,0 +1,62 @@ +# D04 — Provide prefix-safe shared feature calculation + +Parent epic: E3. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quantitative feature engineering. + +Scheduling source of truth: [manifest entry D04](../manifest.json). 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 + +- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). +- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Add a small feature request/result contract keyed by dataset hash, instrument, timeframe, parameters and implementation version. Reuse reviewed calculations; one experiment-local calculation per identical feature request. Prefix-gate precomputed outputs; no distributed feature service or persistent cache framework. Fitted/model features also key by artifact hash, fit-window identity and availability policy; they must not reuse a transform fitted on another partition. + +Measurable benefit: Avoids duplicate work and feature leakage without a framework. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- libs/calculations/ +- apps/stock/engine/src/indicators/ +- apps/stock/orchestrator/src/data/ +- test/integration/strategy-contracts.test.ts + +Write locks: feature-contract. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [S01](S01.md), [P01](P01.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Deferred: Only after profiling demonstrates repeated identical feature work; use reviewed incremental calculations directly first. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Regime and strategy consumers requesting the same SMA/volatility share results within a run. +- Batch and incremental values match reviewed warmup/NaN semantics; a future data mutation cannot affect earlier features. +- Float feature outputs never become authoritative monetary calculations. + +## Mandatory tests + +- batch_incremental_parity, prefix_equivalence, shared_request_counter, warmup_alignment. +- Run calculations migration-preservation and numerical suites. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/F01.md b/docs/development/backlog/tasks/F01.md new file mode 100644 index 00000000..87d0f1e4 --- /dev/null +++ b/docs/development/backlog/tasks/F01.md @@ -0,0 +1,59 @@ +# F01 — Define the minimal financial contract and economic fixtures + +Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Rust financial contract owner. + +Scheduling source of truth: [manifest entry F01](../manifest.json). 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 + +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). +- **FIN-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234). +- **FIN-04 — Verified:** Native fills notify every strategy. TypeScript realized P&L uses aggregate symbol cost basis, not per-strategy cost basis. [apps/stock/engine/src/backtest/engine.rs:489](../../../../apps/stock/engine/src/backtest/engine.rs#L489); [apps/stock/orchestrator/src/execution/model.ts:108](../../../../apps/stock/orchestrator/src/execution/model.ts#L108). + +## Intended behavior and implementation scope + +Define only the contracts consumed by the first financial vertical slice: scalar posting rules, owner IDs, account risk-session boundary, commands/effects, snapshot version and stable decision identity. Use a maintained checked decimal implementation, not bespoke arithmetic. Absorb C05: add small hand-derived JSON/table fixtures beside their consumers, without a reference simulator or an expected-failure test campaign. Freeze the TS/Rust command/context shape before consumers implement it. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/engine/src/financial/ (new small modules) +- apps/stock/engine/src/api/ +- libs/core/types/src/financial-engine.ts (new) +- test/fixtures/economics/ (small new fixture set) + +Write locks: financial-contract. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +Architecture decisions: ADR-002, ADR-003, ADR-004. 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 + +- Financial postings use8 decimal places with explicit round-half-away-from-zero at ties (matching current TS half-up behavior); reject overflow/non-finite/excess-precision external commands. Float observations/features are not converted into money strings on every native crossing. +- Authoritative basis is remaining cost amount, not rounded average price. Fixture buys3 shares for total5; partial/final disposals release exactly5 basis in total. +- Stable protocol snapshot/command serialization and unknown-version rejection pass small Rust/TS contract fixtures; scope is one supported version, not a compatibility-negotiation framework. +- Each regression fixture lists economic assumptions, hand calculation and owning task. Each implementation task adds its own passing regression coverage; do not merge a blanket failing suite. + +## Mandatory tests + +- Rust/TS fixture parse parity, rounding_ties_positive_negative, overflow_rejected, basis_residual_spec, command_id_conflict_spec. +- Use existing binding smoke tests to confirm Bun/addon compatibility; no temporary simulator or new FFI framework. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/F02.md b/docs/development/backlog/tasks/F02.md new file mode 100644 index 00000000..4a77ffc7 --- /dev/null +++ b/docs/development/backlog/tasks/F02.md @@ -0,0 +1,60 @@ +# 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](../manifest.json). 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 + +- **FIN-02 — Verified:** Native forced liquidation occurs after the last equity mark; reported final value reads that earlier mark, omitting terminal costs. [apps/stock/engine/src/backtest/engine.rs:135](../../../../apps/stock/engine/src/backtest/engine.rs#L135); [apps/stock/engine/src/backtest/simple_results.rs:308](../../../../apps/stock/engine/src/backtest/simple_results.rs#L308). +- **FIN-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234). +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). +- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151). + +## 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. + +## 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](F01.md) 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](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/F03.md b/docs/development/backlog/tasks/F03.md new file mode 100644 index 00000000..0dc2f4c5 --- /dev/null +++ b/docs/development/backlog/tasks/F03.md @@ -0,0 +1,5 @@ +# F03 — Merged into F02 + +This ID is retained for traceability and must not be claimed or implemented separately. + +Its required behavior, fixtures and tests are owned by [F02](F02.md). See [skeptical review](../../REVIEW.md) for the effort reduction and [manifest](../manifest.json) for canonical scheduling metadata. diff --git a/docs/development/backlog/tasks/F04.md b/docs/development/backlog/tasks/F04.md new file mode 100644 index 00000000..af7b142a --- /dev/null +++ b/docs/development/backlog/tasks/F04.md @@ -0,0 +1,57 @@ +# F04 — Enforce cash reservations and portfolio risk centrally + +Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Rust financial risk. + +Scheduling source of truth: [manifest entry F04](../manifest.json). 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 + +- **FIN-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234). +- **FIN-06 — Verified:** Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. [apps/stock/engine/src/backtest/engine.rs:374](../../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../../apps/stock/engine/src/backtest/engine.rs#L414). + +## Intended behavior and implementation scope + +Implement canonical cash-long-only funding, pending fee-inclusive reservations, fill-time affordability and existing per-order/symbol/gross limits. Accept explicit account RiskSessionBoundary commands from the F01 contract; do not infer a day from UTC or independently roll for every venue. Marked daily-loss and drawdown checks use canonical marks. Session rollover resets only daily baseline; peak equity and drawdown halt persist until authorized reset. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/engine/src/risk/mod.rs +- apps/stock/engine/src/financial/risk.rs (new) +- apps/stock/engine/src/financial/ledger.rs + +Write locks: rust-ledger, risk-policy. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [F02](F02.md) integrated. + +Architecture decisions: ADR-002, ADR-003. 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 + +- No accepted order/fill creates negative available cash or an unsupported short. +- Pending/partial orders reserve resources once and release on cancellation/rejection/expiry. +- Stale marks block risk increases; marked losses halt increases even without realized trades; reductions remain possible. + +## Mandatory tests + +- competing_reservations, adverse_gap_reject_remainder, stale_other_symbol, marked_loss_halt, explicit_risk_session_boundary. +- drawdown_halt_survives_rollover_restore, unauthorized_reset_denied, alternate_venue_does_not_reset_account_day. +- Property test raw order and target paths cannot bypass the same policy. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/F05.md b/docs/development/backlog/tasks/F05.md new file mode 100644 index 00000000..b17d15e6 --- /dev/null +++ b/docs/development/backlog/tasks/F05.md @@ -0,0 +1,60 @@ +# F05 — Unify matching and order lifecycle on the ledger + +Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Rust execution semantics. + +Scheduling source of truth: [manifest entry F05](../manifest.json). 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 + +- **FIN-01 — Verified:** Both execution paths can act on a completed bar and fill against its current close; this is not a defensible default bar-close policy. [apps/stock/engine/src/backtest/engine.rs:249](../../../../apps/stock/engine/src/backtest/engine.rs#L249); [apps/stock/orchestrator/src/services/ExecutionService.ts:224](../../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224). +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). +- **FIN-06 — Verified:** Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. [apps/stock/engine/src/backtest/engine.rs:374](../../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../../apps/stock/engine/src/backtest/engine.rs#L414). +- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151). + +## Intended behavior and implementation scope + +Implement pure matcher/order-transition functions over explicit execution events; replay scheduling belongs to F06. Market/limit orders use declared spread/slippage and available liquidity, with no future-bar fields. Retain DAY/GTC/IOC/FOK semantics needed by the existing paper path; unsupported stop/OCO types reject. Target mode and explicit-order mode are mutually exclusive for one strategy instance in v1. Repeated absolute targets account for owned holdings and outstanding commitments; replacements cancel only owned orders. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/engine/src/financial/matching.rs (new) +- apps/stock/engine/src/backtest/engine.rs + +Write locks: rust-matching, financial-contract. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [F04](F04.md) integrated. + +Architecture decisions: ADR-003. Agents may not independently amend their policies. + +Feature activation/release gates: [F06](F06.md). These do not block implementing or integrating this component against its own tests. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Given an already-eligible execution event, market/limit price protection, volume sharing, partial fill, rejection/cancellation and expiry are deterministic. +- IOC cancels remainder; FOK either fills fully or does not fill/charge; DAY accepts only in-session; target-generated GTC survives a session boundary. +- Same owner/instrument repeated target after partial fill does not duplicate quantity; mixed target/explicit mode rejects; another owner's order cannot be cancelled. +- Pure eligibility tests reject prior/same observed event keys. Full next-open ordering is an F06 release gate, not a hidden F05 implementation requirement. + +## Mandatory tests + +- matcher_gap_limit, shared_volume_capacity, partial_cancel, IOC_remainder, FOK_atomicity, DAY_expiry, target_GTC_replace. +- unchanged_target_no_duplicate, mixed_intent_mode_rejected, wrong_owner_cancel, ineligible_event_key_rejected. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/F06.md b/docs/development/backlog/tasks/F06.md new file mode 100644 index 00000000..b0b12767 --- /dev/null +++ b/docs/development/backlog/tasks/F06.md @@ -0,0 +1,58 @@ +# F06 — Implement deterministic replay once, with linear historical traversal + +Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Rust deterministic replay. + +Scheduling source of truth: [manifest entry F06](../manifest.json). 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 + +- **FIN-01 — Verified:** Both execution paths can act on a completed bar and fill against its current close; this is not a defensible default bar-close policy. [apps/stock/engine/src/backtest/engine.rs:249](../../../../apps/stock/engine/src/backtest/engine.rs#L249); [apps/stock/orchestrator/src/services/ExecutionService.ts:224](../../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224). +- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177). +- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194). + +## Intended behavior and implementation scope + +Implement the replay cursor once: sorted immutable events with stable availability/phase/instrument/sequence ordering; add a small pending-event queue only where required. Absorb P02's nonquadratic load and disabled-by-default hot-loop trade logging. Generate open-only execution events from one designated execution series; feature-only frames do not add liquidity or undeclared decision triggers. Publish completed observations, evaluate declared decision barriers, then next-interval opens under recorded zero/nonzero latency policy. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/engine/src/backtest/engine.rs +- apps/stock/engine/src/backtest/mod.rs +- apps/stock/engine/src/financial/replay.rs (new) + +Write locks: rust-replay. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [F05](F05.md), [D01](D01.md), [P01](P01.md) integrated. + +Architecture decisions: ADR-003. 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 + +- Permuting file arrival order does not change economic results after canonical event ordering. +- Daily observations remain unavailable before session close; different symbols retain their actual quote timestamps. +- Multi-timeframe context includes only completed available bars and marks missing/stale inputs explicitly. + +## Mandatory tests + +- adjacent_open_zero_latency, positive_latency_skips_open, future_ohlcv_does_not_change_open_fill, daily_close_target_survives_to_open. +- feature_timeframe_does_not_duplicate_liquidity, equal_timestamp_symbol_permutation, warmup_cannot_trade, stale_mark_timestamp_preserved. +- Replay/restore trace equality. Extend P01 with1k/10k/100k release-build load/replay scaling; preserve economics before accepting faster runs. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/F07.md b/docs/development/backlog/tasks/F07.md new file mode 100644 index 00000000..c57e5112 --- /dev/null +++ b/docs/development/backlog/tasks/F07.md @@ -0,0 +1,60 @@ +# F07 — Expose bounded Rust step sessions through existing NAPI workers + +Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Rust/TypeScript integration. + +Scheduling source of truth: [manifest entry F07](../manifest.json). 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 + +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). +- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Expose a small pull session (load/create/advance/submit/finalize/dispose) in the existing worker, backed by the same financial kernel. advance returns a tagged union: progress, decision batch, or complete. For a decision batch, all due strategies receive immutable views from the same ledger revision; collect all decisions before ordered admission. Use one native test strategy/intent trace for conformance, not a port of every Rust built-in. Per-session dataset load once; cross-trial residency is P03. + +## Exclusions + +No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. + +## Likely files and ownership + +- apps/stock/engine/src/api/backtest.rs +- apps/stock/orchestrator/src/backtest/native-worker.ts +- apps/stock/orchestrator/src/backtest/native-worker-protocol.ts +- apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts + +Write locks: native-public-api, worker-protocol. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [F06](F06.md), [C02](C02.md) integrated. + +Architecture decisions: ADR-004. 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 + +- TS caller handles every step variant; it never assumes each advance returns a decision. Progress/cancel boundaries remain bounded. +- All due decisions reference one barrier revision. Reversing callback evaluation order cannot change output when contexts/states are unchanged; final admission uses declared owner priority. +- No partial barrier is committed if a decision throws. Rust returns per-intent accepted/rejected outcomes; business rejection is not a rollback of the observed decision event. +- Native conformance intent trace and TS fixture use identical financial transitions. Native built-in production strategy parity is not required. +- Worker crash/cancel/lease loss cannot publish successful stale results; snapshot/ID/version mismatches reject. + +## Mandatory tests + +- step_tagged_union, immutable_barrier_revision, reverse_callback_order, decision_exception_aborts_barrier, rejected_intent_is_committed_outcome. +- Existing native-worker/runner cancellation and lease tests; extend P01 with step and context-byte timings. + +Apply relevant [quality gates](../../QUALITY-GATES.md). 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. diff --git a/docs/development/backlog/tasks/F08.md b/docs/development/backlog/tasks/F08.md new file mode 100644 index 00000000..f2c11048 --- /dev/null +++ b/docs/development/backlog/tasks/F08.md @@ -0,0 +1,66 @@ +# F08 — Publish canonical metrics and versioned result projections + +Parent epic: E2. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quant analytics/Rust integration. + +Scheduling source of truth: [manifest entry F08](../manifest.json). 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 + +- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). + +- **Verified reusable analytics:** [reviewed return statistics](../../../../libs/calculations/src/analytics/return-statistics.ts#L24) already separate statistical reporting from financial execution. + +## Intended behavior and implementation scope + +Use canonical Rust ledger postings, owned fills, occupied intervals and session-ending marks as the sole financial inputs. Reuse reviewed TypeScript statistical functions in `libs/calculations/src/analytics/` for return ratios and reports; do not port them to Rust merely for language uniformity. Add a small adapter for the engine-declared session calendar rather than blindly regrouping every venue by UTC date. + +Version economics and metrics independently. Define sampling, annualization, benchmark and risk-free conventions in the result policy. Missing benchmark/risk-free inputs must not silently become invented measurements. Undefined or unsupported metrics are null with reasons. Adapt existing result DTOs without rewriting old rows. + +Measurable benefit: comparable, independently checked rankings without a second ledger or a needless analytics rewrite. + +## Exclusions + +No accounting/fill recomputation in TypeScript, statistical library rewrite, forced native port, new service, or silent reinterpretation of historical results. Native analytics remain an option only if measured as a bottleneck. + +## Likely files and ownership + +- apps/stock/engine/src/backtest/simple_results.rs (authoritative projections, not new statistical formulas) +- apps/stock/orchestrator/src/backtest/native-result.ts +- apps/stock/orchestrator/src/backtest/BacktestReport.ts +- libs/calculations/src/analytics/return-statistics.ts +- libs/calculations/src/analytics/equity.ts (review existing UTC grouping; use explicit session marks) +- libs/core/types/src/backtest-run.ts + +Write locks: result-contract. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [F06](F06.md) integrated. + +Architecture decisions: ADR-002, ADR-003. 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 + +- Fees/P&L/equity/trades reconcile to Rust outputs; session returns include the final session and use the declared risk-session/calendar policy. +- Sharpe uses periodic excess-return mean/std; Sortino uses downside deviation relative to the declared target; zero-variance/undefined cases are null with reasons. +- Exposure uses the union of occupied intervals; open positions count; attribution distinguishes fills and round trips. +- Reviewed calculation functions are reused where their conventions match. Any deliberate difference has a versioned policy and independent arithmetic fixture, not an unexplained second formula. + +## Mandatory tests + +- two_session_marks, constant_negative_returns, zero_variance, overlapping_positions, open_position_exposure. +- Existing result mapping and frontend metric unit fixtures; documented independent arithmetic cross-check. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## 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. diff --git a/docs/development/backlog/tasks/O01.md b/docs/development/backlog/tasks/O01.md new file mode 100644 index 00000000..e7698d09 --- /dev/null +++ b/docs/development/backlog/tasks/O01.md @@ -0,0 +1,55 @@ +# O01 — Serialize additive schema migrations safely + +Parent epic: E9. Priority/severity: P1 / High. Relative complexity: S. Recommended specialization: PostgreSQL/backend infrastructure. + +Scheduling source of truth: [manifest entry O01](../manifest.json). 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 + +- **OPS-01 — Verified:** Migration runner uses an explicit safe allowlist; adding SQL alone will not run it. Concurrent migration admission lacks an advisory lock. [apps/stock/web-api/src/migrations/migration-runner.ts:42](../../../../apps/stock/web-api/src/migrations/migration-runner.ts#L42); [apps/stock/web-api/src/migrations/migration-runner.ts:57](../../../../apps/stock/web-api/src/migrations/migration-runner.ts#L57). + +## Intended behavior and implementation scope + +Preserve the explicit reviewed additive allowlist. On one PostgreSQL transaction client, acquire a transaction-scoped advisory lock BEFORE migration table initialization, migration discovery/check, SQL apply and recording. Do not lock via an arbitrary pooled query or add a migration framework. Integrator allocates additive filenames; applied scripts remain immutable. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/web-api/src/migrations/migration-runner.ts +- database/postgres/init/ +- test/postgres/ (migration tests) + +Write locks: sql-migrations. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Two API startups apply each new migration once without duplicate object errors. +- Upgrade from current schema preserves runs, datasets, execution ledger and checkpoints. +- Destructive init scripts cannot enter startup migration discovery. + +## Mandatory tests + +- two_concurrent_startups_same_client_lock, precheck_inside_lock, migration_failure_rollback, destructive_init_excluded. +- bun run test:postgres on disposable fixtures only; existing migrations/data retained. + +Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. diff --git a/docs/development/backlog/tasks/O02.md b/docs/development/backlog/tasks/O02.md new file mode 100644 index 00000000..e65c028f --- /dev/null +++ b/docs/development/backlog/tasks/O02.md @@ -0,0 +1,68 @@ +# O02 — Expose truthful research and paper readiness diagnostics + +Parent epic: E9. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Infrastructure/observability. + +Scheduling source of truth: [manifest entry O02](../manifest.json). 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 + +- **OPS-02 — Needs Investigation:** Paper/live operational readiness is not demonstrated end-to-end. Live is deliberately disabled; preserve that gate until feed, reconciliation and broker-specific recovery are verified. [apps/stock/orchestrator/src/core/ModeManager.ts:33](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L33); [apps/stock/orchestrator/src/container.ts:152](../../../../apps/stock/orchestrator/src/container.ts#L152). +- **WEB-02 — Verified:** Detail exposes native-unsupported pause/resume controls, omits cancel wiring, and overlapping polling/selection can apply stale responses. [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:379](../../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L379); [apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts:160](../../../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts#L160). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Report actual worker/queue/lease, engine version/capability, dataset load failure, paper feed freshness and recovery/halt state. Replace unmeasured zeros/always-healthy assumptions with unknown/unavailable. Attach run/attempt/strategy IDs to diagnostics; avoid a new telemetry stack. + +Measurable benefit: Makes failures diagnosable from the primary product. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/web-api/src/routes/monitoring.routes.ts +- apps/stock/web-api/src/services/ +- apps/stock/orchestrator/src/api/rest/ +- apps/stock/web-app/src/features/monitoring/ + +Write locks: readiness-api. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [S04](S04.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Deferred: Optional cross-service monitoring expansion; required run diagnostics belong to W01/F07 and paper readiness to S04. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Missing orchestrator/native worker/DB or stale feed cannot report ready. +- Run failure includes phase and actionable cause, with secrets excluded. +- Research availability and paper readiness are separate indicators; live-disabled is explicit. + +## Mandatory tests + +- dependency_unavailable_readiness, stale_feed_status, failed_attempt_diagnostics, no_secret_logs. +- API/UI tests show unknown versus measured zero and retryable error. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. + +## Web/API contract and user states + +- API: Extend current health/monitoring and run diagnostics contracts; no separate monitoring API silo. +- Backend/data dependencies: Persisted attempts and real service probes; no additional time-series platform. +- Loading/error/empty behavior: Unknown, degraded, stale and disconnected states; actionable retry; do not display fake healthy cards. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/P01.md b/docs/development/backlog/tasks/P01.md new file mode 100644 index 00000000..8a25a8c2 --- /dev/null +++ b/docs/development/backlog/tasks/P01.md @@ -0,0 +1,58 @@ +# P01 — Measure existing research paths before extending the benchmark + +Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Performance/infrastructure engineering. + +Scheduling source of truth: [manifest entry P01](../manifest.json). 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 + +- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194). +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Extend the current dataset benchmark with one small harness for paths that actually exist: process/addon startup, dataset preparation, native load/run/result parse and repeated parameter trials. No new observability framework or fabricated callback timing. Mark unavailable counters/phases explicitly; F07/S01/P03/P04/A02 extend the same harness as capabilities arrive. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- scripts/benchmark-dataset.ts +- scripts/benchmark-research.ts (new) +- test/fixtures/ (benchmark datasets) + +Write locks: benchmark-harness. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Single/multi-asset native fixtures and parameter trials record source/native binary/runtime/host/seed hashes and raw timings. +- Separate fresh-process/unprepared data from reused input objects; do not call one-shot repeated loads resident warm throughput. +- Report wall time, observed bar/trial rates, result bytes and RSS; DB/queue/allocation counters are unavailable until instrumented, not zero. +- Fixed fixture/economic hashes match repeated runs under the same policy; current known economic defects are limitations, not benchmark truth. + +## Mandatory tests + +- Tiny harness self-test and1k/10k/100k optional scaling; runtime versions/build hash verified. +- No timing-flaky CI gate. Unsupported multi-strategy ownership/callback paths are labelled unavailable until canonical tasks land. + +Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. diff --git a/docs/development/backlog/tasks/P02.md b/docs/development/backlog/tasks/P02.md new file mode 100644 index 00000000..aa2772e5 --- /dev/null +++ b/docs/development/backlog/tasks/P02.md @@ -0,0 +1,5 @@ +# P02 — Merged into F06 + +This ID is retained for traceability and must not be claimed or implemented separately. + +Its required behavior, fixtures and tests are owned by [F06](F06.md). See [skeptical review](../../REVIEW.md) for the effort reduction and [manifest](../manifest.json) for canonical scheduling metadata. diff --git a/docs/development/backlog/tasks/P03.md b/docs/development/backlog/tasks/P03.md new file mode 100644 index 00000000..bee2a454 --- /dev/null +++ b/docs/development/backlog/tasks/P03.md @@ -0,0 +1,60 @@ +# P03 — Reuse validated datasets within bounded native workers + +Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Performance/infrastructure engineering. + +Scheduling source of truth: [manifest entry P03](../manifest.json). 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 + +- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Load/hash/validate one dataset per worker and create isolated trial sessions over it. Measure object/JSON versus typed columnar buffers; adopt typed buffers only with a demonstrated transfer/allocation benefit. Keep ownership/lifetime explicit and invalidate by dataset/feature version. + +Measurable benefit: Reduces repeated preparation before adding a DSL. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/orchestrator/src/backtest/native-worker-protocol.ts +- apps/stock/orchestrator/src/backtest/native-worker.ts +- apps/stock/engine/src/api/backtest.rs + +Write locks: worker-protocol, native-public-api. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [F07](F07.md), [P01](P01.md) integrated. + +Architecture decisions: ADR-004, ADR-008. Agents may not independently amend their policies. + +Deferred: Only after measured repeated dataset admission is a material sweep cost; not a prerequisite for parallel trials. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- N trials sharing a dataset incur one dataset admission per worker, not per trial. +- Disposing a trial clears mutable strategy/account state but retains immutable data; worker disposal releases buffers. +- Output hashes match uncached runs and sequential trials cannot contaminate one another. + +## Mandatory tests + +- resident_dataset_hit_counter, trial_state_reset, incompatible_version_miss, dispose_memory_plateau. +- P01 warmed sweep time/RSS and serialization-byte comparison. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. diff --git a/docs/development/backlog/tasks/P04.md b/docs/development/backlog/tasks/P04.md new file mode 100644 index 00000000..05c7caf8 --- /dev/null +++ b/docs/development/backlog/tasks/P04.md @@ -0,0 +1,56 @@ +# P04 — Schedule deterministic batches across a bounded worker pool + +Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Performance/infrastructure engineering. + +Scheduling source of truth: [manifest entry P04](../manifest.json). 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 + +- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Use existing isolated one-shot workers and durable claims to run independent trials concurrently at a configurable1/2/4 process limit. Resident dataset reuse is optional P03, not a dependency. Each trial gets deterministic seed/identity and separate mutable state; admission/backpressure honors cancellation/leases. No parallel event processing inside one portfolio. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +- apps/stock/orchestrator/src/backtest/BacktestRunner.ts +- apps/stock/web-api/src/services/BacktestDispatcher.ts + +Write locks: worker-pool, web-backtest-dispatch. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [F07](F07.md), [R06](R06.md), [C06](C06.md), [P01](P01.md) integrated. + +Architecture decisions: ADR-008. 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 + +- Concurrency1/2/4 produces identical per-trial economic hashes and completion-independent ranking. +- A worker crash retries only affected durable attempts; batch cancellation drains or kills workers with no stale result commit. +- Pool concurrency is configurable; no assumption that all available CPUs improve throughput. + +## Mandatory tests + +- parallel_hash_parity, worker_crash_retry, cancellation_under_load, lease_fencing_pool. +- P01 trials/s, efficiency T1/(p*Tp), tail latency and RSS at1/2/4 workers. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. diff --git a/docs/development/backlog/tasks/P05.md b/docs/development/backlog/tasks/P05.md new file mode 100644 index 00000000..49828dda --- /dev/null +++ b/docs/development/backlog/tasks/P05.md @@ -0,0 +1,65 @@ +# P05 — Separate result summaries from paged detail payloads + +Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Performance/infrastructure engineering. + +Scheduling source of truth: [manifest entry P05](../manifest.json). 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 + +- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194). +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). + +## Intended behavior and implementation scope + +Deferred until measured detail payload/query/rendering costs justify it. R06 already provides summary projections. This task may add stable paged trade/position detail and display-only downsampling; keep full exports and retained authoritative results. Do not normalize all storage or add an artifact service by default. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/web-api/src/services/backtest-v2.service.ts +- apps/stock/web-api/src/routes/backtests-v2.routes.ts +- apps/stock/web-app/src/features/backtest/ +- apps/stock/web-app/src/features/experiments/ + +Write locks: result-contract, web-backtest-service, web-experiments. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R06](R06.md), [P01](P01.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Deferred: Only after measured trade-detail payload/query/render cost; simple summary projections ship in R06. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Experiment list retrieves summaries without full OHLC/trade blobs. +- Detail pagination/export preserves every trade in stable sequence; changing display density does not alter reported metrics. +- Report API bytes, query latency and rendering time before/after on the large-trade workload. + +## Mandatory tests + +- paged_trade_reassembly_hash, stable_cursor, summary_matches_full_result, complete_export. +- Browser loading/error/empty/pagination test and P01 result-store/load timings. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. + +## Web/API contract and user states + +- API: GET run summary/provenance plus /trades?cursor and display-series projections; full export remains available. +- Backend/data dependencies: Existing results first; add normalized detail storage only after query profiling and separate approval if scope expands. +- Loading/error/empty behavior: Summary available while detail loads; retry individual page; explicit no trades/end of list; no fake zero risk. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/P06.md b/docs/development/backlog/tasks/P06.md new file mode 100644 index 00000000..bc41abf2 --- /dev/null +++ b/docs/development/backlog/tasks/P06.md @@ -0,0 +1,58 @@ +# P06 — Conditionally add a minimal Rust-executed strategy plan + +Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Rust/TS performance compiler boundary. + +Scheduling source of truth: [manifest entry P06](../manifest.json). 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 + +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). +- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194). + +## Intended behavior and implementation scope + +Deferred. First inspect actual warmed trial profiles after the TS path works. Owner may authorize a time-boxed prototype of a tiny typed feature/comparison/target plan only if projected end-to-end benefit and maintenance savings justify it. The same Rust financial kernel is mandatory; do not use arbitrary fixed percentage/speed thresholds as automatic permission. + +## Exclusions + +No speculative distributed infrastructure or weakened correctness gates. + +## Likely files and ownership + +- apps/stock/orchestrator/src/backtest/strategy-plan.ts +- apps/stock/engine/src/strategies/ +- apps/stock/engine/src/financial/ + +Write locks: strategy-contract, native-public-api. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [P04](P04.md), [S01](S01.md) integrated. + +Architecture decisions: ADR-008. Agents may not independently amend their policies. + +Deferred: Owner go/no-go after representative profiling and explicit prototype budget; no fixed 20%/1.5x magic thresholds. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Owner records baseline, suspected bottleneck, bounded prototype budget and required end-to-end improvement BEFORE implementation; absence of that decision means stay deferred. +- Prototype compares identical supported TS/declarative decision and economic traces on representative workloads; report Amdahl limit, wall time, memory and maintenance cost. +- Go/no-go either accepts the small supported subset or stops it; no implicit universal DSL work. + +## Mandatory tests + +- ts_plan_differential, invalid_plan_validation, state_reset, no_risk_bypass. +- P01 full workload speed/memory comparison, not a no-op microbenchmark alone. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Performance measurements can hide semantic changes; require economic hash equivalence. +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. diff --git a/docs/development/backlog/tasks/R01.md b/docs/development/backlog/tasks/R01.md new file mode 100644 index 00000000..bd61a3cf --- /dev/null +++ b/docs/development/backlog/tasks/R01.md @@ -0,0 +1,70 @@ +# R01 — Persist immutable strategy versions and parameter schemas + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R01](../manifest.json). 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 + +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). +- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). + +## Intended behavior and implementation scope + +Add strategies and append-only strategy_versions; seed registered built-ins with source/bundle hash, parameter schema, checkpoint contract and review status. Store executable artifact bytes or an immutable retained artifact reference, dependency lock and source revision. Draft metadata can change; published executable versions cannot. + +Measurable benefit: Pins executable strategy identity before adding experiments. + +Project/hypothesis linkage is optional and must not require R03 tables or placeholder records. Add nullable foreign-key links only when both entity tables exist, in a coordinated additive migration; standalone versions/experiments work first. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- database/postgres/init/ (new migration) +- apps/stock/web-api/src/routes/ (strategy endpoints) +- apps/stock/web-api/src/services/ (strategy service) +- apps/stock/orchestrator/src/strategies/StrategyRegistry.ts +- libs/core/types/src/strategy-version.ts (new) + +Write locks: sql-migrations, strategy-catalog-api. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [O01](O01.md) integrated. + +Architecture decisions: ADR-006. 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 + +- Invalid versioned parameters reject before enqueue; only registered/reviewed supported artifacts run. +- An idempotency key plus content fingerprint makes identical publish retries return the same version; changed content with the same key returns409. An intentional new revision gets a new ID and lineage even if content matches. +- Published source/schema/checkpoint/dependency content is immutable and retained. Review/approval is separately audited metadata, not a mutation of executable content. +- Registration never executes candidate code in the API; arbitrary untrusted execution stays unavailable until A02. + +## Mandatory tests + +- strategy_version_immutability_postgres, schema_validation, artifact_hash_mismatch, clone_lineage. +- Registry aliases and old definition compatibility. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: GET/POST /api/v2/strategies; GET/POST /strategies/:id/versions; GET /strategy-versions/:id; POST clone. Parameters use a versioned JSON schema subset. +- Backend/data dependencies: New strategy/version tables; existing strategy registry; source-artifact storage retained with version. +- Loading/error/empty behavior: API typed validation errors,404 and409; UI arrives in R02. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/R02.md b/docs/development/backlog/tasks/R02.md new file mode 100644 index 00000000..63a8921d --- /dev/null +++ b/docs/development/backlog/tasks/R02.md @@ -0,0 +1,72 @@ +# R02 — Deliver strategy catalog and version-aware backtest setup + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R02](../manifest.json). 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 + +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). +- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). + +## Intended behavior and implementation scope + +Replace only the strategy placeholder with catalog/detail/version views; allow metadata edits, clone, parameter editing and read-only source/version diff. Add version selection and supported capability filtering to existing backtest form. First release authors code in repository or submits an artifact; no browser IDE. + +Measurable benefit: Makes strategy work a coherent product flow. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- apps/stock/web-app/src/app/App.tsx +- apps/stock/web-app/src/features/strategies/ (new) +- apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx +- apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx +- apps/stock/web-app/src/components/ +- apps/stock/web-api/src/services/backtest-v2.service.ts +- libs/core/types/src/backtest-run.ts + +Write locks: web-backtest-detail, web-strategies. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R01](R01.md), [W03](W03.md) integrated. + +Architecture decisions: ADR-006. Agents may not independently amend their policies. + +Feature activation/release gates: [W04](W04.md). These do not block implementing or integrating this component against its own tests. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- User can create/clone metadata, choose immutable version and schema-valid parameters, then open the existing run flow. +- Unavailable native/custom strategy choices are not offered as runnable. +- Version detail links deployment/backtest history when available; absent histories show empty states. +- During legacy migration only registered artifacts matching the current supported build are runnable; version selection is persisted, but legacy runs remain unproject-gated until R05. + +## Mandatory tests + +- catalog_navigation, parameter_form_validation, immutable_version_selection, clone_revision_diff. +- Browser strategy->backtest flow and schema/API contract tests. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: R01 catalog/version endpoints plus version ID in saved backtest template/request snapshot. +- Backend/data dependencies: R01 schema; current engine capability metadata. Unsupported version/runtime combinations fail before submit. +- Loading/error/empty behavior: Skeleton list/detail; no-strategies create CTA; schema error next to parameter; retry fetch; unsaved edit warning. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/R03.md b/docs/development/backlog/tasks/R03.md new file mode 100644 index 00000000..fc385563 --- /dev/null +++ b/docs/development/backlog/tasks/R03.md @@ -0,0 +1,65 @@ +# R03 — Add projects, hypotheses and evidence-linked findings APIs + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R03](../manifest.json). 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 + +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). +- **WEB-05 — Verified:** SQL deletion cascades from definitions to runs/results; evidence retention must be defined before research findings reference those results. [database/postgres/init/08-create-runs-table.sql:13](../../../../database/postgres/init/08-create-runs-table.sql#L13); [database/postgres/init/06-create-backtest-tables.sql:25](../../../../database/postgres/init/06-create-backtest-tables.sql#L25). + +## Intended behavior and implementation scope + +Add minimal project/hypothesis/note/finding metadata with human/AI authorship and immutable evidence references. Findings refer to runId + metricsVersion + metricPath (and optional immutable artifact ID); the API derives displayed measured values from retained results instead of maintaining another metric truth/validation subsystem. Narrative conclusions may be wrong and must remain distinguishable from referenced measurements. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- database/postgres/init/ (new migration) +- apps/stock/web-api/src/routes/ (research endpoints) +- apps/stock/web-api/src/services/ (research service) +- libs/core/types/src/research.ts (new) + +Write locks: sql-migrations, research-api. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R01](R01.md), [R10](R10.md) integrated. + +Architecture decisions: ADR-006. 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 + +- AI-created hypotheses/notes are labelled unvalidated until explicit validation evidence/review exists. +- Evidence references must resolve to retained run/artifact and known metric version/path; dangling references reject. No new simulator or narrative fact-checking subsystem. +- Archiving metadata does not delete cited runs; narrative changes create a revision while underlying results remain immutable. + +## Mandatory tests + +- hypothesis_vs_evidence, evidence_fk_integrity, authorship_audit, cited_metric_matches_run. +- Migration upgrade fixture retains existing runs/results. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: /api/v2/research-projects, /hypotheses, /analysis-artifacts with explicit evidence references and archive actions. +- Backend/data dependencies: New metadata tables; reuse existing run/result IDs and strategy/version IDs. +- Loading/error/empty behavior: Typed404/409/422, empty evidence lists and explicit unvalidated state; R04 supplies UI. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/R04.md b/docs/development/backlog/tasks/R04.md new file mode 100644 index 00000000..1eb7aa99 --- /dev/null +++ b/docs/development/backlog/tasks/R04.md @@ -0,0 +1,68 @@ +# R04 — Deliver research workspace and save-findings flow + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R04](../manifest.json). 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 + +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). + +## Intended behavior and implementation scope + +Add project overview, hypothesis notes, linked strategies/runs and Save finding from result view. Reuse DataTable/Card/Dialog and current navigation. Keep human conclusions separate from AI suggestions and measured evidence. + +Measurable benefit: Provides the primary research workspace before advanced optimization. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- apps/stock/web-app/src/features/research/ (new) +- apps/stock/web-app/src/app/App.tsx +- apps/stock/web-app/src/lib/constants/navigation.ts +- apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx + +Write locks: web-research, web-backtest-detail. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R03](R03.md), [W02](W02.md) integrated. + +Architecture decisions: ADR-006. Agents may not independently amend their policies. + +Feature activation/release gates: [W04](W04.md). These do not block implementing or integrating this component against its own tests. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Project -> strategy -> configure/run -> inspect -> save cited finding -> reopen project is navigable. +- Finding links open exact run/version; incomplete/legacy evidence displays limitations. +- Notes can be saved without claiming strategy validation. + +## Mandatory tests + +- research_project_to_finding_browser, missing_evidence_error, ai_authorship_badge, archived_project_read. +- Loading/error/empty state component tests. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: R03 project/hypothesis/artifact APIs and existing saved runs. +- Backend/data dependencies: R03 entities, existing run provenance, no requirement for full Rust cutover. +- Loading/error/empty behavior: Empty project guidance; saving/retry states preserve draft; stale evidence error; archived read-only state. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/R05.md b/docs/development/backlog/tasks/R05.md new file mode 100644 index 00000000..f7b7f9d8 --- /dev/null +++ b/docs/development/backlog/tasks/R05.md @@ -0,0 +1,67 @@ +# R05 — Freeze complete provenance and cut over durable canonical runs + +Parent epic: E6. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R05](../manifest.json). 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 + +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). + +## Intended behavior and implementation scope + +Freeze strategy/model artifact IDs, parameters, seed, code/lockfile/build hashes and execution policies at submission. For a selected frozen dataset, pin its hash immediately; for a source request, retain the immutable query and atomically attach the first prepared dataset/hash before replay begins. Expose preparing versus reproducibility-finalized state. Wire the canonical Rust session with existing registered TS strategies into the durable runner and versioned result DTO. Exact reproduction API/UI is R12. + +Measurable benefit: Creates reproducible, project-gated runs usable by humans and AI. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- apps/stock/orchestrator/src/backtest/BacktestRunner.ts +- apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts +- apps/stock/web-api/src/services/backtest-v2.service.ts +- libs/core/types/src/backtest-run.ts + +Write locks: result-contract, web-backtest-service, web-backtest-detail. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [F08](F08.md), [S02](S02.md), [R01](R01.md), [R10](R10.md), [D01](D01.md), [W03](W03.md), [C06](C06.md) integrated. + +Architecture decisions: ADR-006. 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 + +- Changing template, strategy source or provider history after dataset freezing cannot alter an admitted run. A source query alone is not labelled a frozen dataset. +- No strategy decision executes before artifact verification and atomic dataset binding; failed preparation remains diagnosed and retry-safe. +- New results declare financialEngine=rust and strategyExecution separately; correctness-gate evidence requires approved engine/data gates, not a UI flag. + +## Mandatory tests + +- mutate_template_after_submit, freeze_before_first_decision, frozen_seed_replay, provider_change_after_dataset_bind. +- Full durable runner restart/lease/cancel suite and result contract compatibility. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: Run/results expose immutable request plus resolved dataset binding, provenance and preparation state. No exact-reproduce endpoint until R12. +- Backend/data dependencies: Existing request_snapshot/dataset_hash/results extended with retained provenance and engine correctness-gate evidence metadata. +- Loading/error/empty behavior: API distinguishes preparing, dataset-pinned, running, failed and completed. W02/R11 render these fields without fabricated provenance. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/R06.md b/docs/development/backlog/tasks/R06.md new file mode 100644 index 00000000..d8e080ff --- /dev/null +++ b/docs/development/backlog/tasks/R06.md @@ -0,0 +1,68 @@ +# R06 — Create immutable experiments and bounded sweep expansion + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R06](../manifest.json). 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 + +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Expand immutable bounded experiment grids into existing durable runs with unique trial keys and one pinned dataset hash. Reuse outbox/lease/attempt machinery. A retry-failed action creates a new fenced attempt for the same immutable failed logical run, only when no terminal result exists; append prior attempt diagnostics before clearing the active error. Do not overwrite completed results or create a duplicate candidate/attempt framework. Provide a minimal SQL summary projection excluding OHLC/trade arrays now; P05 later owns only profiled large-detail optimization. + +Project/hypothesis linkage is optional and must not require R03 tables or placeholder records. Add nullable foreign-key links only when both entity tables exist, in a coordinated additive migration; standalone versions/experiments work first. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- database/postgres/init/ (new migration) +- apps/stock/web-api/src/routes/ (experiment endpoints) +- apps/stock/web-api/src/services/ (experiment expansion) +- apps/stock/orchestrator/src/backtest/run-repository.ts + +Write locks: sql-migrations, experiment-api. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R05](R05.md) integrated. + +Architecture decisions: ADR-006. 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 + +- Repeated expansion has identical ordered candidate fingerprints and creates no duplicate logical runs. +- Failed retry preserves run inputs/trial key and prior error/attempt history; stale attempts cannot commit. Completed/cancelled stored results are not silently overwritten. +- Experiment summary lists all outcomes and metrics/provenance without reading/transmitting full trade/OHLC blobs. +- Batch cancellation stops new admission and requests active child cancellation; all candidates use the same frozen data for comparable windows. + +## Mandatory tests + +- deterministic_grid, duplicate_expand_race, retry_failed_preserves_attempt_history, stale_retry_fenced, completed_result_retry_rejected. +- summary_excludes_detail_payload, partial_batch_failure, cancel_batch, one_dataset_hash_for_all_trials; disposable DB/queue failure tests. + +Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: POST/GET /api/v2/experiments; GET /experiments/:id/trials; POST cancel/retry; preview validates grid and returns count. +- Backend/data dependencies: Experiments table; nullable experiment_id/trial_key on runs; existing result storage. +- Loading/error/empty behavior: API distinguishes empty/unsubmitted, partial, cancelled and terminal states; never averages missing failed trials away. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/R07.md b/docs/development/backlog/tasks/R07.md new file mode 100644 index 00000000..7f29ad2f --- /dev/null +++ b/docs/development/backlog/tasks/R07.md @@ -0,0 +1,66 @@ +# R07 — Deliver sweep configuration and comparable-result views + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R07](../manifest.json). 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 + +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). +- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). + +## Intended behavior and implementation scope + +Deliver experiment preview/progress/comparison directly on R06 APIs. Accept an existing frozen dataset ID and show its manifest; R11's picker is optional convenience, not a prerequisite. A project/workspace link is optional; users need not build project metadata before comparing a sweep. Reuse current charts/metrics and R06 summary projection. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- apps/stock/web-app/src/features/experiments/ (new) +- apps/stock/web-app/src/features/backtest/components/ +- apps/stock/web-app/src/components/ui/DataTable/ + +Write locks: web-experiments. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R06](R06.md) integrated. + +Architecture decisions: ADR-006. Agents may not independently amend their policies. + +Feature activation/release gates: [W04](W04.md). These do not block implementing or integrating this component against its own tests. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- User previews bounded trial count, submits, sees all statuses, cancels and opens exact candidate runs. +- Default comparison requires matching data, execution/metrics policy, costs and evaluation windows; mismatches remain visible, not silently ranked. +- No full detail blobs on summary list; failed/incomplete counts and null metrics are explicit. + +## Mandatory tests + +- sweep_to_compare_browser, mixed_policy_warning, partial_failure_visibility, reopen_experiment. +- Large result table rendering measurement and metric-null tests. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: R06 experiment/trial listing; summary metrics projection from result contracts; pagination where needed. +- Backend/data dependencies: Experiments and canonical provenance; full trade arrays are fetched only on run detail. +- Loading/error/empty behavior: Preview loading; invalid grid errors; empty not-yet-submitted; per-trial failed/cancelled; retryable aggregate errors. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/R08.md b/docs/development/backlog/tasks/R08.md new file mode 100644 index 00000000..3cdcfc05 --- /dev/null +++ b/docs/development/backlog/tasks/R08.md @@ -0,0 +1,70 @@ +# R08 — Add bounded chronological and reset-segment validation + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quantitative research integrity. + +Scheduling source of truth: [manifest entry R08](../manifest.json). 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 + +- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168). +- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177). +- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542). + +## Intended behavior and implementation scope + +First implement bounded chronological parameter selection and nonoverlapping walk-forward recipes for deterministic registered strategies. Explicit warmup and evaluation windows; each validation segment starts from its declared initial capital and empty positions with warmed indicators, not carried money/state. Aggregate segment returns as a labelled reset-segment research series, never claim one continuous tradable equity curve. Cost/parameter sensitivity reuses grid expansion. Reject trainable/overlapping-label models until their fit-artifact and declared horizon/embargo contracts are supplied; do not invent general ML infrastructure for SMA. + +Persist the immutable validation manifest/report as experiment-owned JSON on the R06 experiment (or a focused child row if immutability requires it), keyed by experiment/report version and containing every contributing run ID, selection rule and segment policy. This is not R03 research-findings storage. Reopening an experiment must recover the same report; new inputs require a new experiment/report identity. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- apps/stock/web-api/src/services/ (validation recipes) +- apps/stock/orchestrator/src/backtest/ +- test/integration/ (research validation tests) +- database/postgres/init/ and reviewed migration registry (only if experiment report persistence needs an additive column/table) + +Write locks: validation-contract, sql-migrations. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R06](R06.md) integrated. + +Architecture decisions: ADR-006. 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 + +- Training/validation/test inputs and selection rule are frozen before execution. Test values cannot affect earlier parameter selection or fitted inputs. +- Every segment declares capital/reset/warmup policy; warmup has no orders/fills; OOS intervals do not overlap. +- All tried candidates and holdout accesses remain visible. Independent segment cash accounts are not summed/stitched as a continuous portfolio. +- Immutable experiment-owned reports reopen without any project/hypothesis/findings records or R03 API; conflicting attempts cannot overwrite a completed report. +- For a later declared nonzero label horizon require gap/purge >= horizon; unsupported/missing horizon/trainable fit metadata rejects rather than leaking future data. + +## Mandatory tests + +- chronological_selection, test_suffix_cannot_change_selection, warmup_no_trades, nonoverlapping_windows, reset_segment_accounting. +- experiment_report_without_research_metadata, immutable_report_reopen, conflicting_report_write_rejected. +- reject_uncontracted_trainable_model, horizon_gap_validation, bounded_cost_grid; fixed seeds and retained selected-parameter artifacts. + +Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: Validation recipe and immutable report under the existing experiment API; report includes every contributing run and declared segment/warmup policy. +- Backend/data dependencies: R06 experiments/runs and experiment-owned JSON reports. No R03 analysis_artifacts dependency or separate optimization service. +- Loading/error/empty behavior: Typed invalid-window/insufficient-warmup errors; validation failures are not profitable candidates. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/R09.md b/docs/development/backlog/tasks/R09.md new file mode 100644 index 00000000..d7d879f3 --- /dev/null +++ b/docs/development/backlog/tasks/R09.md @@ -0,0 +1,65 @@ +# R09 — Expose validation, cost and regime evidence in the workbench + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R09](../manifest.json). 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 + +- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168). +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). + +## Intended behavior and implementation scope + +Expose stored chronological/cost validation evidence from R08. Regime panels render only when valid as-of regime annotations exist; otherwise show unavailable, not fake classification. The basic validation UI need not wait for S05; enabling that example's regime comparison requires its artifact contract. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- apps/stock/web-app/src/features/experiments/ +- apps/stock/web-app/src/features/research/ +- apps/stock/web-app/src/features/backtest/components/ + +Write locks: web-experiments. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R07](R07.md), [R08](R08.md) integrated. + +Architecture decisions: ADR-006. Agents may not independently amend their policies. + +Conditional activation: regime comparison requires [S05](S05.md); saving/linking a research finding requires [R03](R03.md). Neither blocks basic validation display. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- User can validate and inspect each OOS segment with reset/warmup/cost assumptions visible. +- Regime data missing => explicit unavailable panel; present => sample counts/unclassified bucket and window coverage displayed. +- Validation display works without R03. Enable save/link-finding only when R03 exists; link the exact experiment/report identity and contributing run/metric references through its existing evidence API. Otherwise show the action unavailable. +- No client-side accounting or continuous-equity claim for reset segments. + +## Mandatory tests + +- walk_forward_browser, train_test_badges, insufficient_sample_warning, regime_slice_reconciliation. +- Loading/empty/failure states for incomplete validation; validation_without_findings_api; save_finding_requires_R03. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: R08 experiment-owned immutable recipes/reports. R03 evidence-linked findings only for the conditionally enabled save action. +- Backend/data dependencies: Canonical returns, as-of regime annotations and sample counts; no client-side financial recomputation. +- Loading/error/empty behavior: Loading each segment; unclassified regime bucket; invalid partition feedback; explicit partial validation. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/R10.md b/docs/development/backlog/tasks/R10.md new file mode 100644 index 00000000..56e51b68 --- /dev/null +++ b/docs/development/backlog/tasks/R10.md @@ -0,0 +1,65 @@ +# R10 — Protect retained research evidence and artifact integrity + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. + +Scheduling source of truth: [manifest entry R10](../manifest.json). 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 + +- **WEB-05 — Verified:** SQL deletion cascades from definitions to runs/results; evidence retention must be defined before research findings reference those results. [database/postgres/init/08-create-runs-table.sql:13](../../../../database/postgres/init/08-create-runs-table.sql#L13); [database/postgres/init/06-create-backtest-tables.sql:25](../../../../database/postgres/init/06-create-backtest-tables.sql#L25). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). + +## Intended behavior and implementation scope + +Archive existing templates/runs rather than cascading deletion when they retain run history; protect immutable strategy versions, datasets and artifact references established by R01. Add checksum verification on retrieval. R03 subsequently adds finding-reference constraints using the same retention rule. No automatic purge; explicit operator purge later needs a reference check and confirmation. + +Measurable benefit: Prevents accidental loss of reproducibility. + +## Exclusions + +No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. + +## Likely files and ownership + +- database/postgres/init/ (new migration) +- 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/services/ (artifact references) + +Write locks: sql-migrations, web-backtest-service. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R01](R01.md) integrated. + +Architecture decisions: ADR-006. 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 + +- Deleting a definition with retained runs cannot cascade-delete those runs/results. +- Unreferenced legacy deletion behavior is explicitly tested/documented; archived objects remain reproducible. +- Missing/corrupt artifact produces an actionable integrity error; no fallback to current source. + +## Mandatory tests + +- retained_run_delete_restricted_postgres, archive_preserves_replay, artifact_checksum, legacy_delete_compatibility. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Schema/API backward compatibility, historical provenance and UI state regression. +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. + +## Web/API contract and user states + +- API: Archive actions and409 reference details on destructive API attempts; retained read APIs stay stable. +- Backend/data dependencies: Foreign keys/restrictions on existing run/result relationships and new artifact references. +- Loading/error/empty behavior: Archive confirmation; referenced-delete explanation; read-only archived details; missing-artifact error. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/R11.md b/docs/development/backlog/tasks/R11.md new file mode 100644 index 00000000..a0c552cb --- /dev/null +++ b/docs/development/backlog/tasks/R11.md @@ -0,0 +1,70 @@ +# R11 — Select and reuse frozen datasets in the workbench + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack market data/research. + +Scheduling source of truth: [manifest entry R11](../manifest.json). 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 + +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). +- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). + +## Intended behavior and implementation scope + +Expose metadata-only listing/detail for retained backtest_datasets and add selection by hash to the existing configuration form. Offer either a known frozen dataset or an explicit source request whose data will be prepared asynchronously by the existing runner. Show the eventual pinned hash and coverage; no separate dataset job service. + +Measurable benefit: Delivers dataset choice and reuse as a real web workflow. + +## Exclusions + +No new storage service, arbitrary truncation, full corporate-action feed, or synchronous API-side historical loading. + +## Likely files and ownership + +- apps/stock/web-api/src/routes/ (dataset endpoints) +- apps/stock/web-api/src/services/ (dataset metadata) +- apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx +- apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx +- apps/stock/orchestrator/src/backtest/BacktestRunner.ts + +Write locks: dataset-contract, web-backtest-detail, web-backtest-service. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [D01](D01.md), [O01](O01.md) integrated. + +Architecture decisions: ADR-003, ADR-006. Agents may not independently amend their policies. + +Feature activation/release gates: [W04](W04.md). These do not block implementing or integrating this component against its own tests. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- User selects a compatible dataset by hash or requests a new source/date/interval range; mismatch rejects before simulation. +- Source-request submission is labelled unpinned/preparing, not reproducible data; the first prepared snapshot is attached atomically before execution and reused on retry. +- Listing does not return full bar arrays; missing/corrupt/unknown-coverage datasets show actionable status. + +## Mandatory tests + +- dataset_list_metadata_only, select_hash_compatibility, source_request_freeze_status, retry_reuses_bound_hash. +- Browser select existing dataset -> run -> inspect pinned hash; invalid coverage/timeframe feedback. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Confusing source-query identity with frozen content identity; maintain legacy v1 snapshots and explicit preparation state. +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. + +## Web/API contract and user states + +- API: GET dataset metadata/manifest and existing hash-or-source configuration; no new dataset job service. +- Backend/data dependencies: D01 and existing retained snapshots. Implementation does not require all W04 browser release work. +- Loading/error/empty behavior: Picker empty/loading/retry/incompatible states; source request remains unpinned until atomic preparation. +- Release: This flow must pass the shared W04 browser harness before user-facing release; do not build another harness. + +## 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. diff --git a/docs/development/backlog/tasks/R12.md b/docs/development/backlog/tasks/R12.md new file mode 100644 index 00000000..3b24c30c --- /dev/null +++ b/docs/development/backlog/tasks/R12.md @@ -0,0 +1,67 @@ +# R12 — Reproduce an original run separately from rerunning current settings + +Parent epic: E6. Priority/severity: P1 / High. Relative complexity: S. Recommended specialization: Full-stack reproducible research. + +Scheduling source of truth: [manifest entry R12](../manifest.json). 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 + +- **WEB-03 — Verified:** Definition creation auto-starts by default and catches submission failure; run creation has no client submission key. Re-run uses current definition rather than immutable original input. [apps/stock/web-api/src/services/backtest-v2.service.ts:105](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L105); [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:173](../../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L173). +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Add reproduce-original endpoint/action that copies the retained versioned input bundle including dataset/artifact/engine policies into a new durable run. Keep rerun-current a separate labelled action. Verify retained artifacts and compatible engine availability before admission; no fallback to current source or provider history. + +Measurable benefit: Makes exact experiment repetition a user-visible, verifiable capability. + +## Exclusions + +No downloading/executing arbitrary historic binaries, silent economics downgrade or overwriting original results. + +## Likely files and ownership + +- apps/stock/web-api/src/routes/backtests-v2.routes.ts +- apps/stock/web-api/src/services/backtest-v2.service.ts +- apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +- apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx + +Write locks: web-backtest-service, web-backtest-detail. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [R05](R05.md), [W04](W04.md) integrated. + +Architecture decisions: ADR-006. 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 + +- Original reproduction after template/provider/strategy changes yields the same economic hash on the same supported build/policy. +- A missing original artifact or unsupported old engine produces an explicit error; old result remains viewable. +- UI previews exact original inputs and links source/reproduction runs without mutating either. + +## Mandatory tests + +- reproduce_after_template_provider_change, missing_original_artifact, unsupported_engine_version, economic_hash_parity. +- Browser original-vs-current action and duplicate-submit idempotency. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Legacy provenance may be insufficient; fail explicitly instead of pretending exact reproducibility. +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. + +## Web/API contract and user states + +- API: POST /api/v2/runs/:id/reproduce with idempotency key; response links originalRunId and new run. Rerun-current uses ordinary submit. +- Backend/data dependencies: R05 retained input bundle and R10 artifact integrity; require available approved engine build. +- Loading/error/empty behavior: Preview/loading; missing artifact or version error; accepted pending run; hash match/mismatch after completion. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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. diff --git a/docs/development/backlog/tasks/S01.md b/docs/development/backlog/tasks/S01.md new file mode 100644 index 00000000..2d39cc76 --- /dev/null +++ b/docs/development/backlog/tasks/S01.md @@ -0,0 +1,59 @@ +# S01 — Run deterministic TypeScript decisions on Rust sessions + +Parent epic: E4. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: TypeScript trading infrastructure. + +Scheduling source of truth: [manifest entry S01](../manifest.json). 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 + +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). +- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). +- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151). + +## Intended behavior and implementation scope + +Implement deterministic-by-contract TS decisions with prefix-only observations plus existing reviewed incremental calculations; shared feature caching is not a prerequisite. Use the F07 tagged step/barrier API, owner-stamped IDs, explicit decision cadence and seeded randomness. Stage next strategy states and RNG cursors until the barrier is submitted. Decision exceptions discard staged states and abort the attempt; rejected financial intents still commit the observation/state transition and return feedback. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- apps/stock/orchestrator/src/strategies/ +- apps/stock/orchestrator/src/backtest/native-worker.ts +- apps/stock/orchestrator/src/backtest/strategy-plan.ts +- libs/core/types/src/ + +Write locks: strategy-contract, worker-protocol. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md. + +## Dependencies and blockers + +Implementation requires [F07](F07.md) integrated. + +Architecture decisions: ADR-004, ADR-005. 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 + +- On the pinned supported runtime/build, controlled clock/random inputs and identical state yield identical fixture decision traces and economic hashes. +- Each strategy sees its own state/positions and the same barrier portfolio snapshot, not a state mutated by another callback's early admission. +- Retry restores strategy state, RNG position and decision sequence; quantity rejection does not pretend the observation never occurred. +- Contract/type checks prohibit broker/account mutation services; trusted callbacks are not a security sandbox. No claim that repeated tests prove arbitrary TS deterministic. + +## Mandatory tests + +- same_seed_trace, all_callbacks_same_barrier_view, exception_restores_state_rng, rejected_order_feedback, repeated_target_no_duplicate. +- Compile-time context tests and preserved strategy-recovery scenarios; P01 adds actual TS decision costs. + +Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/S02.md b/docs/development/backlog/tasks/S02.md new file mode 100644 index 00000000..8b17a2a9 --- /dev/null +++ b/docs/development/backlog/tasks/S02.md @@ -0,0 +1,57 @@ +# S02 — Adapt one SMA strategy for the first canonical path + +Parent epic: E4. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: TypeScript strategy/quant engineering. + +Scheduling source of truth: [manifest entry S02](../manifest.json). 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 + +- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). +- **FIN-04 — Verified:** Native fills notify every strategy. TypeScript realized P&L uses aggregate symbol cost basis, not per-strategy cost basis. [apps/stock/engine/src/backtest/engine.rs:489](../../../../apps/stock/engine/src/backtest/engine.rs#L489); [apps/stock/orchestrator/src/execution/model.ts:108](../../../../apps/stock/orchestrator/src/execution/model.ts#L108). + +## Intended behavior and implementation scope + +Adapt one existing SMA strategy first into the approved TS decision API using the current registry alias. Remove direct ModeManager/ExecutionService access for this version; parameters and owner budget are explicit. Keep other strategies/version readers intact and visibly legacy/unsupported on the canonical path until adapted. A native conformance strategy is test-only, not a competing production implementation. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- apps/stock/orchestrator/src/strategies/StrategyRegistry.ts +- apps/stock/orchestrator/src/strategies/BaseStrategy.ts +- apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts +- apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts + +Write locks: strategy-builtins. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [S01](S01.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- The versioned SMA strategy runs via the Rust session with no service injection and isolated checkpoint state. +- Entry/exit and owner sizing are explicit; prior registry alias still resolves to a deliberate version/capability. +- A new canonical run can ship after this one strategy passes; migrating every native/TS built-in is not a release gate. + +## Mandatory tests + +- sma_registry_alias, owner_budget_sizing, sma_checkpoint_restore, sma_next_open_trace. +- Legacy strategy/result compatibility remains; no wholesale BaseStrategy deletion. + +Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/S03.md b/docs/development/backlog/tasks/S03.md new file mode 100644 index 00000000..d597f8f1 --- /dev/null +++ b/docs/development/backlog/tasks/S03.md @@ -0,0 +1,59 @@ +# S03 — Adapt durable paper transactions to Rust financial reducers + +Parent epic: E4. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Durable execution/Rust integration. + +Scheduling source of truth: [manifest entry S03](../manifest.json). 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 + +- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151). +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). + +## Intended behavior and implementation scope + +Preserve the existing PostgreSQL row lock, checkpoint+intent commit and per-effect journal. Rehydrate a private Rust staged state, call the same in-place financial kernel used by research, persist returned snapshot/effects atomically, publish after commit. Do not serialize/rebuild resident research state per event merely to satisfy paper staging. Metrics/UI are not transaction prerequisites. Before paper cutover, retain supported current order/TIF and recovery semantics or explicitly refuse incompatible outstanding state. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts +- apps/stock/orchestrator/src/execution/SimulationExecution.ts +- apps/stock/orchestrator/src/execution/StrategyRecovery.ts +- apps/stock/orchestrator/src/services/ExecutionService.ts +- apps/stock/engine/src/api/ + +Write locks: ts-execution-model, paper-transaction, financial-contract. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [S01](S01.md), [C06](C06.md) integrated. + +Architecture decisions: ADR-005. 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 + +- Rollback discards staged native changes; crash before/after commit/publish has no duplicate fee/order or lost checkpoint. +- Restore includes owner cost residuals, open-order policies/reservations, event cursor, strategy/RNG state and IDs. +- Existing PostgreSQL failure cases and legacy supported DAY/GTC/IOC/FOK behavior pass the canonical path; incompatible old snapshot versions fail with a migration instruction. +- Research and paper reducers match economic postings for the same event/intent trace; different live data/timing is not claimed to produce identical trades. + +## Mandatory tests + +- Port all existing PostgreSQL order-execution and strategy-recovery failure cases. +- fault_before_commit, fault_after_commit_before_publish, multi_owner_lock, same_id_conflict, snapshot_restore_parity. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/S04.md b/docs/development/backlog/tasks/S04.md new file mode 100644 index 00000000..c3498e06 --- /dev/null +++ b/docs/development/backlog/tasks/S04.md @@ -0,0 +1,58 @@ +# S04 — Establish a verified paper feed and operator safety gate + +Parent epic: E4. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: TypeScript trading infrastructure. + +Scheduling source of truth: [manifest entry S04](../manifest.json). 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 + +- **OPS-02 — Needs Investigation:** Paper/live operational readiness is not demonstrated end-to-end. Live is deliberately disabled; preserve that gate until feed, reconciliation and broker-specific recovery are verified. [apps/stock/orchestrator/src/core/ModeManager.ts:33](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L33); [apps/stock/orchestrator/src/container.ts:152](../../../../apps/stock/orchestrator/src/container.ts#L152). +- **FIN-06 — Verified:** Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. [apps/stock/engine/src/backtest/engine.rs:374](../../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../../apps/stock/engine/src/backtest/engine.rs#L414). + +## Intended behavior and implementation scope + +Verify the real paper feed path, recovery and stale-feed/kill controls on the canonical engine. Own the minimal paper-readiness endpoint/status needed to activate safely; do not wait for optional O02 cross-service dashboards. Reuse existing monitoring routes/components for actual state, unknown rather than fake zeros. Live remains disabled. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- apps/stock/orchestrator/src/paper/PaperTradingManager.ts +- apps/stock/orchestrator/src/services/MarketDataService.ts +- apps/stock/orchestrator/src/services/ExecutionService.ts +- apps/stock/orchestrator/src/api/rest/ +- apps/stock/data-ingestion/src/ + +Write locks: paper-runtime. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [S02](S02.md), [S03](S03.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Controlled feed observation -> shared TS strategy -> Rust fill -> SQL commit -> restart reconciles. +- Readiness is false for stale/disconnected feed, incomplete recovery, unsupported account state or persisted halt; no default capital reset. +- Human operator halt persists; activation is acknowledged only after readiness. Optional general monitoring is not necessary for this gate. + +## Mandatory tests + +- paper_feed_to_fill_restart, stale_feed_halt, persisted_kill_switch, configured_capital. +- Live route/adapter disabled tests and readiness tests. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/S05.md b/docs/development/backlog/tasks/S05.md new file mode 100644 index 00000000..ed8bb843 --- /dev/null +++ b/docs/development/backlog/tasks/S05.md @@ -0,0 +1,58 @@ +# S05 — Add a small composable multi-signal regime example + +Parent epic: E4. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Quant strategy research. + +Scheduling source of truth: [manifest entry S05](../manifest.json). 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 + +- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). +- **FIN-04 — Verified:** Native fills notify every strategy. TypeScript realized P&L uses aggregate symbol cost basis, not per-strategy cost basis. [apps/stock/engine/src/backtest/engine.rs:489](../../../../apps/stock/engine/src/backtest/engine.rs#L489); [apps/stock/orchestrator/src/execution/model.ts:108](../../../../apps/stock/orchestrator/src/execution/model.ts#L108). +- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168). + +## Intended behavior and implementation scope + +Adapt the existing mean-reversion idea as a second TS strategy/example and compose trend/momentum scores plus a simple fixed/training-only volatility regime using reviewed calculations. Ordinary functions, no universal signal/regime framework. Code/decision tests can land before R08; conclusions about performance require R08 validation. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- apps/stock/orchestrator/src/strategies/builtin/ +- apps/stock/orchestrator/src/strategies/StrategyRegistry.ts +- libs/calculations/ + +Write locks: example-strategy. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [S02](S02.md), [F08](F08.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Feature activation/release gates: [R08](R08.md). These do not block implementing or integrating this component against its own tests. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Two strategy instances sharing an asset maintain independent state/basis and route fills correctly. +- Exit is not blocked by entry-only volume filters; thresholds and owner budgets are explicit. +- Regime/no-regime ablation inputs and cost-sensitivity recipe are reproducible; no alpha claim before validation release gate. + +## Mandatory tests + +- signal_composition_units, regime_boundary_availability, multi_strategy_ownership, no_regime_ablation_reproducibility. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/S06.md b/docs/development/backlog/tasks/S06.md new file mode 100644 index 00000000..ed30ed2b --- /dev/null +++ b/docs/development/backlog/tasks/S06.md @@ -0,0 +1,61 @@ +# S06 — Retire duplicate simulator paths after cutover proof + +Parent epic: E4. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: TypeScript trading infrastructure. + +Scheduling source of truth: [manifest entry S06](../manifest.json). 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 + +- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114). +- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315). +- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151). + +## Intended behavior and implementation scope + +Delete only unreachable competing accounting/fill implementations after canonical research and paper pass the release gate. Keep old result readers, artifact history, calculation library and research prototypes. Remove the unsupported native callback stub and unused synthetic depth path only after caller inventory. + +Measurable benefit: Reduces long-term maintenance only after behavior is preserved. + +## Exclusions + +No deletion of reviewed calculations, research prototypes, old result compatibility or unrelated dead-code campaign. + +## Likely files and ownership + +- apps/stock/orchestrator/src/backtest/BacktestEngine.ts +- apps/stock/orchestrator/src/backtest/MarketSimulator.ts +- apps/stock/orchestrator/src/execution/SimulationExecution.ts +- apps/stock/orchestrator/src/execution/model.ts +- apps/stock/engine/src/api/backtest.rs + +Write locks: runtime-composition, ts-execution-model. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [S03](S03.md), [S04](S04.md), [R05](R05.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- All supported production research/paper entry points call one Rust financial implementation. +- No competing TS applyFill or independent simulation matching remains on active paths. +- Preservation inventory passes; archived experimental algorithms are not deleted for lacking imports. + +## Mandatory tests + +- Dependency/call-site inventory plus full integration/native/PostgreSQL suites. +- Replay pre-cutover golden fixtures using explicit compatibility expectations; old result reading still works. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. diff --git a/docs/development/backlog/tasks/W01.md b/docs/development/backlog/tasks/W01.md new file mode 100644 index 00000000..f6b2cbef --- /dev/null +++ b/docs/development/backlog/tasks/W01.md @@ -0,0 +1,70 @@ +# W01 — Make existing run controls and selection truthful + +Parent epic: E5. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack React/API. + +Scheduling source of truth: [manifest entry W01](../manifest.json). 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 + +- **WEB-02 — Verified:** Detail exposes native-unsupported pause/resume controls, omits cancel wiring, and overlapping polling/selection can apply stale responses. [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:379](../../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L379); [apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts:160](../../../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts#L160). +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). + +## Intended behavior and implementation scope + +Repair the existing UI flow only: wire cancel, show cancel-requested until persisted terminal state, use one nonoverlapping polling authority, and guard requests by selection generation/abort. Websocket messages invalidate/refetch persisted state, not a competing state store. Repair the current reconnect guard/cleanup as needed. Expose cancel as the supported shared execution control; leave legacy pause/resume/speed endpoints intact but do not advertise them without per-run support. No capability registry, SQL migration or new backend job protocol. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- 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 a focused DOM test dependency is necessary) + +Write locks: web-backtest-detail, websocket-hook, frontend-test-dependencies. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md. + +## Dependencies and blockers + +No code prerequisite. Global execution approval and write-lock acquisition still required. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Late getRun(A) AND getResults(A) cannot replace selected B, including completion/error callbacks. +- At most one poll is outstanding per mounted selection; switching/unmount invalidates previous requests and cleans timers/subscriptions. +- Pending cancellation can persist as cancelled immediately; active cancellation remains requested until stored acknowledgement. Failed/cancelled never display successful completion. +- Current native-unsupported server pause/resume/speed controls are absent/disabled; chart playback controls are unaffected. +- Reconnect or polling fallback recovers actual status; completed zero-trade data is distinct from missing results. + +## Mandatory tests + +- New backtest-run-controls.test.tsx: stale_status_response, stale_results_response, one_poll_in_flight, no_publish_after_unmount, pending_vs_active_cancel, unsupported_controls, reconnect_or_poll_recovery. +- 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. +- Reuse Bun and existing React tests. One minimal DOM test adapter is allowed if needed; W04 owns real browser E2E, not a second harness here. + +Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. + +## Web/API contract and user states + +- API: Existing v2 getRun/getResults/cancel and websocket invalidation only. No new capability schema or financial fields. +- Backend/data dependencies: Existing persisted cancellation/status contract; backend source is read-only for this task. +- Loading/error/empty behavior: Preserve selected B during stale A responses; retry errors; requested versus acknowledged cancellation; zero trades versus unavailable result. +- Parallelism: Independent of first-wave native finance, TS finance and ModeManager files. Owns frontend test-dependency changes if needed. + +## 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. diff --git a/docs/development/backlog/tasks/W02.md b/docs/development/backlog/tasks/W02.md new file mode 100644 index 00000000..1466b2f5 --- /dev/null +++ b/docs/development/backlog/tasks/W02.md @@ -0,0 +1,66 @@ +# W02 — Expose result provenance and legacy correctness limitations + +Parent epic: E5. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research UX. + +Scheduling source of truth: [manifest entry W02](../manifest.json). 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 + +- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107). +- **FIN-01 — Verified:** Both execution paths can act on a completed bar and fill against its current close; this is not a defensible default bar-close policy. [apps/stock/engine/src/backtest/engine.rs:249](../../../../apps/stock/engine/src/backtest/engine.rs#L249); [apps/stock/orchestrator/src/services/ExecutionService.ts:224](../../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224). +- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542). + +## Intended behavior and implementation scope + +Add read-only provenance/limitations DTO and panel using data actually stored. Distinguish missing metadata, legacy semantics and project-gated engine versions; label same-bar/funding/attribution limitations. Do not infer a historical code hash or certify results from engine name alone. + +Measurable benefit: Delivers useful UI now without presenting invalid results as validated. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +- apps/stock/web-app/src/features/backtest/components/BacktestMetrics.tsx +- apps/stock/web-api/src/services/backtest-result.ts +- libs/core/types/src/backtest-run.ts + +Write locks: web-backtest-detail, result-contract. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [W01](W01.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Every existing run reopens with exact stored configuration where present and explicit unknown fields otherwise. +- Legacy/native/TS result limitations are visible next to performance; unproject-gated results cannot be treated as validated promotion evidence. +- No zero-valued placeholder is presented as a measured risk metric. + +## Mandatory tests + +- legacy_missing_provenance, frozen_config_not_mutable_definition, limitation_badge, null_metrics. +- Existing backtest-result-mapping and analytics-ui tests. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. + +## Web/API contract and user states + +- API: Extend GET /api/v2/runs/:id/results with provenance availability, economics version and limitations; backward-compatible optional fields. +- Backend/data dependencies: Existing result configuration/dataset; future R05 extends the same contract. +- Loading/error/empty behavior: Separate loading, no-result-yet, failed run, and legacy metadata unavailable; never fabricate defaults as provenance. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/W03.md b/docs/development/backlog/tasks/W03.md new file mode 100644 index 00000000..3f3bd445 --- /dev/null +++ b/docs/development/backlog/tasks/W03.md @@ -0,0 +1,66 @@ +# W03 — Separate save, submit and repeat-safe run creation + +Parent epic: E5. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack durable workflow. + +Scheduling source of truth: [manifest entry W03](../manifest.json). 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 + +- **WEB-03 — Verified:** Definition creation auto-starts by default and catches submission failure; run creation has no client submission key. Re-run uses current definition rather than immutable original input. [apps/stock/web-api/src/services/backtest-v2.service.ts:105](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L105); [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:173](../../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L173). +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). + +## Intended behavior and implementation scope + +Make the web save action explicitly non-running; add an explicit Save and run operation with visible submit failures. Add a principal-scoped submission key plus payload hash so transport retries return the same run. Preserve transactional request snapshot/outbox creation and legacy compatibility explicitly. + +Measurable benefit: Removes accidental/duplicate runs and hidden submission errors. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- apps/stock/web-api/src/services/backtest-v2.service.ts +- apps/stock/web-api/src/routes/backtests-v2.routes.ts +- apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx +- apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +- database/postgres/init/ (new additive migration) + +Write locks: web-backtest-detail, web-backtest-service, sql-migrations. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [O01](O01.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Repeated same-key/same-payload submit yields one run and outbox entry; changed payload under same key returns409. +- Saving a definition creates no hidden job; submission failure remains visible and retryable. +- Concurrent submissions preserve run numbering; non-browser clients use the same endpoint semantics. + +## Mandatory tests + +- idempotent_submission_postgres_race, submission_key_conflict, save_only, save_and_run_failure. +- Existing durable-backtest and workflow suites. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. + +## Web/API contract and user states + +- API: POST definition with explicit autoStart:false; POST runs with Idempotency-Key, request fingerprint,202/Location;409 conflict. +- Backend/data dependencies: Existing definitions/runs/dispatch plus one submission uniqueness constraint. +- Loading/error/empty behavior: Submitting disables duplicate clicks; persisted definition survives submit failure; retry reuses the same key; empty strategy list explains unavailable capability. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. +## 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. diff --git a/docs/development/backlog/tasks/W04.md b/docs/development/backlog/tasks/W04.md new file mode 100644 index 00000000..627bb0c9 --- /dev/null +++ b/docs/development/backlog/tasks/W04.md @@ -0,0 +1,67 @@ +# W04 — Verify the first research vertical slice in a browser + +Parent epic: E5. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack test engineering. + +Scheduling source of truth: [manifest entry W04](../manifest.json). 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 + +- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). +- **WEB-02 — Verified:** Detail exposes native-unsupported pause/resume controls, omits cancel wiring, and overlapping polling/selection can apply stale responses. [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:379](../../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L379); [apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts:160](../../../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts#L160). +- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190). + +## Intended behavior and implementation scope + +Add a narrowly scoped browser runner if the repository lacks one; prefer Playwright for real navigation and use existing Bun/server-render tests for small components. Exercise actual API/dispatcher/disposable DB and a deterministic fixture worker, plus one native smoke run. + +Measurable benefit: Protects the primary product path while internals migrate. + +## Exclusions + +No unrelated refactor, new service or broker activation. + +## Likely files and ownership + +- test/e2e/ (extend) +- apps/stock/web-app/package.json +- scripts/test-postgres.ts +- apps/stock/web-app/src/features/backtest/ + +Write locks: browser-harness. One agent owns this change. Lock names do not override actual overlapping files. + +## Dependencies and blockers + +Implementation requires [W01](W01.md), [W02](W02.md), [W03](W03.md), [C06](C06.md) integrated. + +No additional economic-policy approval is needed for this narrowly scoped task. + +Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries. + +## Acceptance criteria + +- Select supported strategy -> save/configure -> submit -> pending/running -> completed -> trades -> reload URL works. +- Cancellation, worker failure, empty results, inaccessible run and network reconnect have user-visible outcomes. +- Initial slice is explicitly exploratory until F08/S02/R05 correctness-gate evidence; no mock fixture is claimed as financial correctness proof. + +## Mandatory tests + +- browser_saved_run_lifecycle, browser_cancel_failure, browser_reopen_and_switch, native_smoke. +- Disposable PostgreSQL/Redis suite; browser install is an explicit dependency, not assumed present. + +Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. + +## Regression risks and rollback + +Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests. +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. + +## Web/API contract and user states + +- API: Exercise existing v2 APIs and websocket projection; no new business endpoints. +- Backend/data dependencies: Isolated test DB/queue and fixture dataset; never local paper accounts. +- Loading/error/empty behavior: Assert loading/empty/error/retry/cancelled states in rendered UI. +- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. + +## 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.