# 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 [canonical paper](../../test/postgres/canonical-paper.test.ts), [canonical paper crash](../../test/postgres/canonical-paper-crash.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 or browser E2E. Run `bun run test:e2e` separately for the web workbench. Native command is `cargo test -p engine --lib --offline`; missing dependencies are a reported blocker, not a pass. The browser gate requires a built checkout, explicit `PIPELINE_TEST_DATABASE_URL` pointing to a disposable `stock_bot_safety*` database, dedicated Redis DB15 in `BACKTEST_TEST_REDIS_URL`, and Chromium. Install the pinned browser explicitly with `bun run test:e2e:install` if missing; do not install browsers implicitly during checks. The command rebuilds the frontend for same-origin production use. It exercises authenticated HTTP/WebSocket routes, durable dispatch and SQL persistence with deterministic UI fixtures plus an actual native smoke run. Fixture results are not financial-correctness evidence. Never use a development trading database or queue. 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.