renames docs
This commit is contained in:
parent
4cd6038063
commit
13eb8352f3
25 changed files with 0 additions and 0 deletions
38
design/development/architecture/benchmarks.md
Normal file
38
design/development/architecture/benchmarks.md
Normal file
|
|
@ -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.
|
||||
25
design/development/architecture/decisions/001-ownership.md
Normal file
25
design/development/architecture/decisions/001-ownership.md
Normal file
|
|
@ -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
|
||||
|
||||
Historical TypeScript `applyFill` (`orchestrator/src/execution/model.ts`, retired in pre-M0 cleanup) and Rust [process_fill](../../../../apps/stock/engine/src/backtest/engine.rs#L426) were 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.
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
# ADR-002 — Money, cost basis, ownership and funding
|
||||
|
||||
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). This revision replaces the unimplemented half-even/rounded-average proposal; approval does not itself alter legacy code or accounts.
|
||||
|
||||
## 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
|
||||
|
||||
Historical TS amount/cost basis and aggregate owner attribution (`orchestrator/src/execution/model.ts`, retired in pre-M0 cleanup), [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.
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
# ADR-003 — Information availability and execution timing
|
||||
|
||||
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). Versioned implementation remains task-gated; legacy snapshots/results are preserved.
|
||||
|
||||
## 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), historical bar-close bid/ask (`orchestrator/src/services/ExecutionService.ts`, retired in pre-M0 cleanup), [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.
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
# ADR-004 — One pull-session boundary, not two strategy frameworks
|
||||
|
||||
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). Session execution is implemented by F07/S01, not by approving this contract direction.
|
||||
|
||||
## 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.
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
# ADR-005 — Shared kernel, distinct persistence boundaries
|
||||
|
||||
Status: **approved by owner continuation, 2026-10-23**. After the handoff named S01 and linked this pending decision, the owner instructed “commit all of it and continue.” This approves the documented direction for the next task; paper migration/default activation remain separately gated. 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 durable step recovery, account locks, and duplicate/conflict handling in [canonical paper execution custody](../../../../apps/stock/orchestrator/src/execution/canonical-paper.ts), along with 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.
|
||||
|
||||
## S01 retry scope
|
||||
|
||||
The existing durable research runner retries whole attempts. S01 follows that boundary: create a fresh native session from frozen data/configuration, clone original strategy states and restore original per-owner seeds, then recompute observations, decisions and RNG cursors. Per-barrier TypeScript diagnostic snapshots are not independently resumable financial checkpoints. Do not add a native checkpoint wire or accept a TS-only mid-run resume merely for S01. Existing Rust checkpoint reconstruction and paper SQL checkpoints remain preserved; S03 owns their durable integration.
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
# ADR-006 — Web-first research product and minimal persistence
|
||||
|
||||
Status: **approved by owner continuation on 2026-10-23**, after the S05 handoff explicitly linked this decision for the next research-product work. Web as primary product is user-mandated. Approval covers direction; engine cutover and trading activation remain separate release gates.
|
||||
|
||||
## 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.
|
||||
27
design/development/architecture/decisions/007-ai-boundary.md
Normal file
27
design/development/architecture/decisions/007-ai-boundary.md
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
# ADR-007 — AI authorization, code isolation and promotion
|
||||
|
||||
Status: **implementation authorized by owner, 2026-10-24**, through the instruction to complete all remaining scheduled tasks. Research-only quotas, OS isolation and no autonomous live access remain mandatory. Actual paper activation still requires a deliberate human action; no trading is activated by development or task closure.
|
||||
|
||||
## 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.
|
||||
|
||||
Implementation clarification (A02/A04): the trusted **research** path is limited to server-registered built-ins. Catalog approval never changes a candidate's isolated research execution. A separate immutable human paper-promotion receipt may authorize the exact candidate factory in the paper host after held-out/cost evidence and financial-build parity checks. That action is a deliberate trust decision; paper starts unbound/halted, and live remains unavailable.
|
||||
|
||||
The first isolation profile is a local Linux x86_64 Docker scratch image containing the installed Bun runtime, trusted protocol host and independent Rust PID1 guardian. It has no host/data mounts or network, uses cgroup limits and a restricted unprivileged child, and dies on supervisor disconnect or a monotonic deadline. Version the image, host, guardian, runtime and policy in retained requests. A standalone restricted transpiler accepts self-contained TypeScript; no dependency installation, remote build service, JavaScript VM security claim or second simulator is introduced.
|
||||
|
||||
## Evidence
|
||||
|
||||
[Current role model](../../../../libs/core/di/src/http/security.ts#L4) is a small operator boundary, not research isolation. Historical `StrategyRegistry.ts` (retired in pre-M0 cleanup) exposed 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.
|
||||
24
design/development/architecture/decisions/008-performance.md
Normal file
24
design/development/architecture/decisions/008-performance.md
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# ADR-008 — Performance work earns its complexity
|
||||
|
||||
Status: performance work explicitly resumed by the owner, 2026-10-28. Evaluate all remaining conditional tasks using the smallest supported change; record no-go decisions for extensions without demonstrated value. P06 still needs a bounded, measured justification before a prototype.
|
||||
|
||||
## 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.
|
||||
|
||||
## October 28 review outcome
|
||||
|
||||
P08 implements one measured local TypeScript state-handling optimization, preserving exact Rust economic hashes. D04/P03/P05/P06 remain deferred; CL21 also remains unnecessary without a concrete replay edit. No new blanket performance pause is imposed; see [benchmarks.md](../benchmarks.md) for measured figures.
|
||||
154
design/development/architecture/overview.md
Normal file
154
design/development/architecture/overview.md
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
# Architecture baseline and target
|
||||
|
||||
> **Historical planning baseline.** The observations and example interfaces below describe
|
||||
> the pre-migration state and proposed design, not today's runtime. For the implemented
|
||||
> connections and current strategy API, start with the [project guide](../../guide/README.md).
|
||||
|
||||
Planning baseline: commit `b7aeca4`, inspected 2026-10-22. This is a historical baseline, not today's runtime contract; see [architecture decisions](./decisions) and [PLATFORM-PLAN.md](../../PLATFORM-PLAN.md) for current boundaries and locked decisions.
|
||||
|
||||
## 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), legacy `StrategyRecovery.ts` (retired in pre-M0 cleanup), [container composition](../../../apps/stock/orchestrator/src/container.ts).
|
||||
|
||||
## 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<FeatureSnapshot>; // only available prefix; includes regime inputs
|
||||
positions: Readonly<OwnedPositions>;
|
||||
portfolio: Readonly<AccountView>;
|
||||
risk: Readonly<EffectiveRiskView>; // context, not a mutable policy object
|
||||
random(): number; // run/strategy seeded stream
|
||||
}
|
||||
interface Strategy<State, Params> {
|
||||
decisionCadence: { executionSeriesId: string; event: "barClose" };
|
||||
initialState(params: Params): State;
|
||||
onDecision(ctx: DecisionContext, state: Readonly<State>, 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.
|
||||
125
design/development/architecture/research-product.md
Normal file
125
design/development/architecture/research-product.md
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
# Integrated research product contracts
|
||||
|
||||
Status: approved under ADR-006 on 2026-10-23. 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.
|
||||
- Canonical single and batch submissions require a resolved retained dataset hash. Prepare sources before admission; 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.
|
||||
|
||||
Canonical source preparation is explicit and precedes run admission. Preview returns materialized source bytes and their normalized identity; retention captures those exact bytes through the existing immutable store. A subsequent source read may differ and must be requested explicitly. Canonical admission validates the retained content and atomically freezes its hash with the executable and policies; the worker verifies the binding before decisions. Retention retries reuse the captured input, and run retries reuse the retained dataset. This 2026-10-24 refinement supersedes the original asynchronous source-preparation-inside-run proposal, avoiding another run lifecycle without weakening frozen-input guarantees. Legacy v1 source preparation/readers retain their existing behavior.
|
||||
|
||||
## 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. W04 now supplies the shared [Playwright workflow harness](../../../test/e2e/workbench.test.ts), real authenticated Hono routes, disposable SQL/Redis, durable dispatch and native smoke coverage. Extend it for research-product flows instead of creating a second harness.
|
||||
|
||||
R11 exposes retained v1 metadata and exact hash selection in both backtest forms. Catalog coverage is unknown and full content integrity is not verified by metadata inspection; the runner validates retained bytes before binding/execution. That R11 milestone was legacy/v1 only. R05 subsequently added a separate fully validated v2 canonical picker and retained-input runner. Legacy source requests retain their original asynchronous behavior and economics qualifications; new canonical source preparation follows the before-admission sequence above.
|
||||
|
||||
## 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.
|
||||
|
||||
|
||||
R01 now retains immutable bundled JavaScript and exact dependency locks with source/build metadata. Three tables support editable strategy metadata, immutable versions and append-only reviews. The offline seed command registers only locally packaged built-ins; HTTP uploads/clones remain candidates. Catalog parameter validation never evaluates code, and all versions remain explicitly non-runnable. R02 may deliver catalog/forms before R05, but version-based execution requires R05; arbitrary candidates additionally require A02. Review approval is evidence, not activation. Original TS source and complete run reproducibility remain outside this catalog-only claim.
|
||||
|
||||
|
||||
## A04 execution: human-reviewed paper promotion
|
||||
|
||||
The `/paper` workflow retains an immutable deployment before any account is bound. Select a sealed chronological or walk-forward **test** run and a fully completed standalone cost study from the same source dataset, strategy version, parameters, risk policy and research build. Review the exact retained code, including AI-originated code, and approve its catalog version separately. Supply a new account/session identity and explicit future feed, intraday observation cadence, risk clock and venue sessions; the platform does not infer them. Financial settings come from the selected saved cost scenario. Preview shows the exact evidence, paper-host identity and limitations; **Create halted deployment** records the promotion without activating trading. An uncertain response freezes the draft: use **Retry same promotion receipt**, which retains the original input and key.
|
||||
|
||||
To use an explicit paper host, build the orchestrator with `bun run --cwd apps/stock/orchestrator build` and apply the registered database migrations. Configure `services.orchestrator.defaultMode: paper`, durable PostgreSQL, and `services.orchestrator.paperDeploymentHost: { enabled: true }`; do not also configure `canonicalPaper`. An optional `deploymentId` binds that immutable deployment at startup but never activates it. Keep research workers in their separate research role. This configuration is opt-in; promotion does not change application defaults.
|
||||
|
||||
The web API requires an explicitly configured `ORCHESTRATOR_URL`. Both services must enable authentication, share the configured administrator credential (`STOCK_BOT_ADMIN_TOKEN`), and explicitly allow the browser origin through `STOCK_BOT_ALLOWED_ORIGINS`; the orchestrator verifies forwarded operator sessions. The original operator credential and Origin are checked at both ends. Development auth bypass, research-agent credentials and service tokens cannot authorize promotion, binding or activation. A missing host or mismatched origin is an unavailable/error state, never a fallback to service privilege.
|
||||
|
||||
Open the saved deployment, **Bind halted host**, connect the trusted feed, inspect readiness/recovery diagnostics, then explicitly **Activate paper**. Recovery of pending work requires the displayed acknowledgment. Restart preserves the same account cash, positions, owner checkpoints and execution journal; it does not recopy historical capital or strategy state. Use **Halt paper** before intervention. Later review revocation blocks new binding/activation but does not halt a running session automatically. Historical evidence and halt remain accessible.
|
||||
|
||||
Paper-host, native engine, dependency and runtime artifacts must remain immutable while running. Drift fails closed and requires restart; changed build/evidence requires a newly reviewed deployment and a new account, not an in-place account reset. Research and paper must share the native financial build, while their worker/host bundles have separate identities. Human promotion explicitly permits these exact bytes to run as trusted paper-host code; the research candidate sandbox does not extend to paper. Paper starts from factory state, uses quotes/displayed size rather than historical Open/volume fills, currently accepts one intraday strategy/asset, and has no live broker. Holdouts and cost sensitivity are retained evidence, not a performance guarantee.
|
||||
Loading…
Add table
Add a link
Reference in a new issue