# 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. Root coordinates shared contracts; backend and packaging agents reserve disjoint actual files. 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 - Version parameters reject through the catalog validation API using the retained schema and exact registered built-in validators. R01 exposes no enqueue path: every catalog version is explicitly non-runnable until R05 (trusted built-ins) or A02 (arbitrary candidates). Existing legacy requests carrying catalog version IDs reject rather than silently execute current name-based code. - 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. ## Execution contract — 2026-10-23 - Three additive tables only: editable/archiveable strategies, immutable strategy_versions with retained package JSONB and numbered lineage, append-only operator review events. No R03 placeholders, artifact store or delete cascade. SQL rejects version/review UPDATE/DELETE. - Package v1 retains self-contained bundled JavaScript, exact Bun lock bytes, SHA256 hashes, source revision/dirty state, compiler identity, parameter schema and API/checkpoint identity. The bundle is authoritative executable content; source metadata does not imply original TS retention or full experiment reproducibility. - Canonical SMA/MR schemas and aliases move to the existing pure stock-config subpath with compatibility reexports. JSON form schema is a small scalar subset; exact Zod cross-field validation remains authoritative. No uploaded validator or code executes in API. - Offline packaging builds the two reviewed repository programs with workspace source resolution and no external runtime imports. A separate explicit local seed command registers these built-ins; HTTP publication always creates candidate origin. New/cloned versions start unreviewed. Operator approval/revocation appends audited events, never modifies executable content or enables execution. - Publish and clone use actor/key receipts plus canonical content fingerprints. Read receipt before mutable parent state, lock parent for ordinal/archive decisions, recheck receipt, insert atomically; changed payload with same key conflicts. New key yields intentional new identity even for identical bytes. Clone retains parent lineage and clears registration/review. - Catalog mutations require credential-backed operator/service identity; reviews require operator. The development bypass is not authorship proof. Existing routes preserve their prior authentication behavior. - Metadata list/detail omits artifact/lock content; explicit artifact retrieval retains exact bytes. Version validation returns normalized parameters and `runnable:false`. No UI (R02), retained-artifact execution (R05), untrusted execution (A02), strategy financial changes or performance work. ## Validated handoff — 2026-10-23 Catalog APIs, additive migration 16, pure version/parameter contracts, offline built-in packaging and explicit local seeding are integrated and independently reviewed. Metadata is editable/archiveable; versions/reviews are immutable. Publish/clone receipts, stable built-in families, parent lineage, role checks and exact artifact checksums have real PostgreSQL coverage. New/cloned/rebuilt versions start unreviewed, and all versions remain non-runnable. Local commands (not run against development data in this wave): - `bun run scripts/package-builtin-strategies.ts --out /tmp/builtin-strategies.json` packages both trusted repository programs without database access. - After normal migration startup has applied 16, set `STRATEGY_CATALOG_DATABASE_URL` explicitly and run `bun run scripts/seed-builtin-strategies.ts --seed`. It compiles the local built-ins itself, reuses their catalog families, retains package/lock bytes and leaves new versions pending review. It accepts no arbitrary artifact input and performs no schema migration or strategy execution. HTTP metadata: `/api/v2/strategies`, `/strategies/:id/versions`, `/strategy-versions/:id`; full bytes use `/:id/artifact`; clone/review/parameter validation use `/:id/clone`, `/:id/reviews`, `/:id/validate`. Publication/clone require `Idempotency-Key`. Catalog mutations require actual operator/service credentials, even when other development routes permit loopback bypass; only operator may review. API-supplied names/flags cannot self-register trusted code. Validation: 93 tooling, 509 integration, 150 Rust (four manual ignored), 122 PostgreSQL/Redis and six browser workflows passed, plus source/contracts/build/lint/strict changed-test types. Final release native regressions passed 65 tests. Exact sequencing, hashes, commands and raw logs are canonical in `manifest.json` → `twentieth_wave_validation`. R10 and R02 follow; no current engine switch, candidate execution, trading activation or performance work.