# 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 — Verified:** `MarketDataService.initialize()` creates a Socket.IO client, but `data-ingestion/src/routes/create-routes.ts` mounts no stream producer. The unmounted live route queues an absent handler. Connection logging is not feed readiness. - **FIN-06 — Addressed by F04/F05/S03:** Canonical Rust already enforces quantity/cash/risk and quote capacity. S04 must connect that tested engine to explicit market-data timing and retain its durable recovery, rather than fix or duplicate financial arithmetic. See `execution/CanonicalPaperExecution.ts` and `PostgresCanonicalExecutionRepository.ts`. - **OPS-02 composition evidence — Verified:** Existing composition constructs legacy execution/mode/order gateways; canonical activation requires an isolated graph and a persisted operator/feed gate, not just another boolean in a route. ## 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. S03 supplies transaction custody and trusted command ingestion, not feed scheduling. Define the host's observation-series/cadence manifest before accepting auxiliary feature timeframes; retain the separate native execution-series configuration. Schedule ordinary completed observations and exact consumed-quote decisions without timestamp restamping. A durably admitted invalid input remains pending and drain rejects it: readiness must fail closed until recovery succeeds, without silently skipping data or resetting capital. ## Exclusions No unrelated refactor, new service or broker activation. ## Likely files and ownership - apps/stock/orchestrator/src/paper/{feed,CanonicalPaperRuntime}.ts - apps/stock/orchestrator/src/execution/{canonical-paper,CanonicalPaperExecution,PostgresCanonicalExecutionRepository}.ts - apps/stock/orchestrator/src/{contracts/paper-runtime,api/rest/paper,container,simple-container,index,routes/create-routes,types}.ts - apps/stock/config/src/schemas/stock-app.schema.ts - test/{integration,postgres,fixtures}/paper-*.ts Write locks: paper-runtime. Root owns shared contracts/composition/API; disjoint feed and custody slices have one owner each. 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. ## Execution contract — 2026-10-23 Base `c01e96e` contains accepted S03. This wave implements an opt-in canonical composition; no default cutover or trading activation. Inspection found no usable quote producer behind the legacy Socket.IO client: ingestion does not serve that protocol, the live route is not mounted, and its queued handler is absent. Do not manufacture provider readiness. The implemented ingress is an authenticated normalized HTTP frame boundary; a real provider adapter and verified operational calendar remain prerequisites for running it. - Rust alone owns matching, financial state and risk. Host control state shares the existing SQL account row lock; no additional service/table. Immutable policy binds target-mode built-ins, explicit raw-price quote series, auxiliary completed-bar manifests/cadence, versioned UTC sessions and account risk boundaries. - Each process generation fences prior hosts. Startup/reconnect disconnects or revokes activation. Initial and persisted human halt stop decisions, submissions and fills without finish/cancel/liquidation/reset. Every drain step rechecks controls under the account lock; old shutdown cannot stop a replacement. - Feed frames carry original physical quote timestamps/sequences and explicit atomic release time. All quotes execute in native key order before the final synchronized decision; new intents cannot fill on those quotes. Completed bars are supplied, never synthesized. Session-open anchored bars may clip at declared session close. Auxiliary observations do not mark prices or create liquidity. - Frame admission persists original receipt/disposition and every input atomically. Exact retries never change health-only/admitted meaning. Physical quote/bar receipts prevent conflicting or recycled observations, including inactive probes. New active frames cannot plan against pending recovery; producer retries after prior request drains. - Fresh transport and every configured asset must be ready. Check the old deadline before refreshing health. Missing/stale/future/regressing/out-of-session data fail closed; no time repairs. A late fresh frame cannot silently resume execution. Native daily/drawdown risk remains authoritative and separate from the host pause. - Previously admitted crash-recovery inputs retain their original times. Activation defaults to `recoverPending:false`; explicit `true` is required for pending historical work. Acknowledgement follows successful recovery and final fresh readiness. Invalid durable work remains pending with diagnostics; never skip/restamp/reset it. - With HTTP authentication enabled, human operator credentials alone activate/halt; verified service credentials may submit feed frames. Existing explicit loopback development auth bypass maps to operator and remains supported; readiness in bypass mode is not authenticated-feed certification. Legacy order/position gateways and WebSocket controls are unavailable in canonical composition. Research uses its existing isolated worker. `/health` is liveness; `/api/paper/readiness` reports actual readiness or explicit unknown state. Live remains disabled. Mandatory added scenarios: actual HTTP → built-in SMA → later quote fill → SQL → restart; service activation denial; initial/persisted halt; locked halt race; stale generation/shutdown; idle-before-refresh; stale second asset; pending recovery status; old quote after fresh probe; immutable retry dispositions; explicit historical recovery; cross-session controls; physical observation conflicts; configured capital; canonical/research isolation. No performance work or benchmark is included. ## Validated handoff — 2026-10-23 Implementation and independent G1/G2/API isolation review accepted; manifest remains `review` until owner acceptance/commit. Full repository and PostgreSQL gates pass; the release-addon suite covers real SMA HTTP-to-fill restart, isolated research, all control regressions and native binding checks. See [wave17 validation](../manifest.json) and [roadmap](../../ROADMAP.md#seventeenth-wave-execution--2026-10-23) for exact commands, counts, hashes and limits. Canonical configuration is opt-in at `services.orchestrator.canonicalPaper`, validated before opening connections. `/api/paper/readiness` exposes state; operator `/activate` and `/halt` are separate from trusted producer `/feed/connect`, `/feed/frames`, `/feed/disconnect`. No provider connectivity is claimed and no account was operationally activated. All configured assets currently require covered sessions and fresh quotes; arbitrary callbacks, broker execution and automatic calendar/provider discovery remain outside this slice.