# 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/contracts/builtin-strategy.ts` and `strategies/canonical-sma.ts`: one strategy/schema owner. - `apps/stock/orchestrator/src/contracts/strategy-replay.ts` and the existing native worker protocol/child/supervisor: a disjoint worker owner consumes the pinned selection schema. - Dedicated strategy and worker integration tests/fixtures follow those owners. Root owns planning/integration; review is independent. Preserve the legacy registry, BaseStrategy and built-ins unchanged; reuse their alias mapping. No generic registry rewrite. Actual overlapping files override symbolic locks. ## 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. ## S01 integration handoff — 2026-10-23 Consume `contracts/canonical-strategy.ts` and `backtest/strategy-runtime.ts`: typed synchronous programs return JSON next state and financial intent; the host owns per-instance seeds/cursors and Rust owns admission/accounting. Reuse reviewed calculation semantics. Preserve the current legacy factory contract; add only the small trusted built-in resolver/composition needed to select the canonical SMA version deliberately. Wire that reviewed built-in through the existing native worker with explicit strategy/version/parameters and retained dataset/config inputs. Never serialize callback functions/source or accept arbitrary module paths. Keep legacy and conformance requests intact; unknown canonical strategies/versions reject explicitly. R05 still owns durable default and public-result migration. No browser/default activation or paper migration is implied here. S01 retries whole attempts from frozen inputs and original state/seeds. Its snapshots are diagnostic, not native resume tokens. `sma_checkpoint_restore` should verify indicator state serialization/recomputation and full retry equivalence without introducing TS-only mid-run financial resume. Admission feedback is not a complete fill-event feed; positions/open orders remain authoritative native views. ## Execution contract — 2026-10-23 S01 is accepted as `2bcadbd`. The trusted selection is `{ownerId, strategyId, strategyVersion, seed, instrumentId, seriesId, ownerBudget, parameters: {fastPeriod, slowPeriod}}`. Existing SMA aliases normalize to `sma_crossover`; the explicit new version is `sma-crossover-long-only/v1`. Reject legacy quantity/fraction/holding-period parameters and unknown fields on this version. It deliberately differs from legacy short entries and account-wide sizing. One instance consumes one declared instrument/series included in its native cadence. Use the reviewed `movingAverageCrossover` with a bounded `slowPeriod + 1` close window, including warmup and its existing equality rules. Process availability-order observations only if their `(event_time, source_sequence)` advances; delayed older observations do not rewrite history. A real golden cross establishes a whole-share target `floor(ownerBudget / close)` using exact decimal inputs; no minimum-one purchase. Hold that target through the bullish phase, including ties; a death cross establishes zero. Repeat the same target on fresh selected input so native target reconciliation preserves or retries commitments. Missing, stale or no-new selected input emits sparse empty targets, preserving existing GTC intent. Match the last accepted observation to the native Fresh input before emitting a target. Budget is desired gross notional, not a new hard risk allocation; Rust alone handles fees, gaps, funding and risk. Keep finite plain JSON indicator state; validate reconstruction without exposing initial-state injection over IPC. Whole-attempt retries start from original inputs. No rolling-sum arithmetic rewrite or feature-cache framework. Add strict `runStrategyReplay` version1 requests with existing dataset/config/eventBudget/resultFormat and trusted selections only. Return a versioned `strategyReplayResult` envelope containing normalized selections actually executed and the unchanged native result. The parent captures detached normalized inputs before fork and binds selections, native identity, policy and format on return. No callbacks, source, arbitrary paths, checkpoint transport or second worker infrastructure. Existing legacy/conformance requests remain supported. Required additions: warmup/tie/delayed-bar/freshness cases; exact budget and native fee/gap rejection; separate owners; whole retry and JSON reconstruction; real worker/direct equality in all formats; malformed/tampered responses, crashes and cancellation (including result-before-close); legacy worker regressions. Full repository and disposable recovery gates follow integration. Measure representative release SMA replay without calling it pure callback cost or claiming a performance improvement. ## Validated handoff — 2026-10-23 The new schema and `createBuiltinStrategy`/`validateBuiltinStrategyBindings` implement the pinned contract; the legacy registry and built-ins are unchanged. `runStrategyReplay` requests carry only trusted selections. `parseStrategyReplayResult` validates the versioned envelope and all native result formats. New tests and existing gates pass; exact source hashes, commands and measurements are in the manifest's fifteenth-wave validation and roadmap handoff. Implementation remains uncommitted pending acceptance. Worker provenance identifies the reviewed built-in/version/configuration. R01/R05 still own immutable code-artifact retention, durable/public results and default activation. Whole-attempt retry remains the recovery model. [P08](P08.md) records the measured state/decision overhead; optimization and financial-policy changes are outside S02.