# R03 — Add projects, hypotheses and evidence-linked findings APIs Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. Scheduling source of truth: [manifest entry R03](../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). - **WEB-05 — Verified:** SQL deletion cascades from definitions to runs/results; evidence retention must be defined before research findings reference those results. [database/postgres/init/08-create-runs-table.sql:13](../../../../database/postgres/init/08-create-runs-table.sql#L13); [database/postgres/init/06-create-backtest-tables.sql:25](../../../../database/postgres/init/06-create-backtest-tables.sql#L25). ## Intended behavior and implementation scope Add minimal project/hypothesis/note/finding metadata with human/AI authorship and immutable evidence references. Findings refer to runId + metricsVersion + metricPath (and optional immutable artifact ID); the API derives displayed measured values from retained results instead of maintaining another metric truth/validation subsystem. Narrative conclusions may be wrong and must remain distinguishable from referenced measurements. ## 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/ (research endpoints) - apps/stock/web-api/src/services/ (research service) - libs/core/types/src/research.ts (new) Write locks: sql-migrations, research-api. One agent owns this change. Lock names do not override actual overlapping files. ## Dependencies and blockers Implementation requires [R01](R01.md), [R10](R10.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 - AI-created hypotheses/notes are labelled unvalidated until explicit validation evidence/review exists. - Evidence references must resolve to retained run/artifact and known metric version/path; dangling references reject. No new simulator or narrative fact-checking subsystem. - Archiving metadata does not delete cited runs; narrative changes create a revision while underlying results remain immutable. ## Mandatory tests - hypothesis_vs_evidence, evidence_fk_integrity, authorship_audit, cited_metric_matches_run. - Migration upgrade fixture retains existing runs/results. 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: /api/v2/research-projects, /hypotheses, /analysis-artifacts with explicit evidence references and archive actions. - Backend/data dependencies: New metadata tables; reuse existing run/result IDs and strategy/version IDs. - Loading/error/empty behavior: Typed404/409/422, empty evidence lists and explicit unvalidated state; R04 supplies UI. - 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. ## Implemented contract — 2026-10-23 R03 adds metadata APIs only; R04 owns the research workspace screens. Migration 20 introduces projects, hypotheses and their revisions, note/finding artifacts and their revisions, evidence references, and project/strategy membership. Existing runs, results, strategy versions, queues and financial engines are reused unchanged. The implementation is in `services/research.service.ts`, `services/research-evidence.ts`, `routes/research.routes.ts` and pure DTOs/schemas at `libs/core/types/src/research.ts` and `@stock-bot/stock-config/research`. Every narrative revision remains `validationState: 'unvalidated'`. `evidenceState: 'referenced'` means citations exist, not that the conclusion is true. `submittedBy` comes from verified operator/service credentials; `contentOrigin: human | ai | unknown` is explicitly declared provenance. Operator submissions default to human, service submissions to unknown; a service cannot claim human authorship. Operator imports may be labelled AI. No model identity, AI credential system, approval workflow or trading authority is inferred. Project edits require `expectedRevision`; actual strategy-link changes also advance it and record the actor. Hypothesis/artifact content changes append a complete immutable revision under the project/entity lock and require the current ordinal. A stale editor receives 409. Archive/restore preserves history and records the latest metadata actor/time. Archived projects reject child writes; archived records remain readable. A finding can link an exact hypothesis revision from the same project; later hypothesis edits/archive never rewrite that link or prevent independent revisions of an existing finding. Findings require at least one reference; notes may have none. References contain `runId`, `metricsVersion`, `metricPath` and optionally a matching retained `strategyVersionId`. They have foreign keys to retained result/version rows and never store copied metric values. Only the known scalar paths in the shared schema are accepted. `canonical-analytics/v1` reads accepted F08 analytics; `legacy-display/v1` versions the existing compatibility reader, **not** a recorded legacy engine or financial policy. Completed runs/results are required. Null stays unavailable with its reason, zero stays zero, fractions are not rescaled, fills do not become round trips, and legacy/model limitations accompany measurements. Reads use `BacktestServiceV2.getRunResults`; an optional query client lets evidence resolution share the active metadata transaction. This prevents a nested-pool deadlock with one connection. SQL rejects revision/reference update/delete/truncate, dangling references and later insertion into an old revision's evidence set. Reference creation is limited to its narrative revision's creation transaction, with a deferred nonempty-finding check. There is no second metric store or simulator. ### API for R04 and other authorized clients All routes use `/api/v2`; list payloads may be empty and mutations require real credentials even when development authentication bypass is enabled. Each route sets `Cache-Control: no-store` without changing unrelated APIs. | Resource | Operations | | --- | --- | | `/research-projects` | GET `{projects}`; POST `{title, description?}` → 201 `{project}` | | `/research-projects/:id` | GET `{project}`; PATCH `{expectedRevision, title?, description?, archived?}` | | `/research-projects/:id/strategies` | GET `{strategies}`; PUT/DELETE `/:strategyId` → 204, no body or `{}` | | `/research-projects/:id/hypotheses` | GET `{hypotheses}`; POST `{title, proposition, validationCriteria?, contentOrigin?}` → 201 `{hypothesis}` | | `/hypotheses/:id` | GET `{hypothesis}`; PATCH `{archived}` | | `/hypotheses/:id/revisions` | GET ascending `{revisions}`; POST full new content + `expectedRevision` → 201 `{hypothesis}` | | `/research-projects/:id/analysis-artifacts` | GET `{artifacts}`; POST `{kind, title, body, hypothesisRevisionId?, contentOrigin?, evidence?}` → 201 `{artifact}` | | `/analysis-artifacts/:id` | GET `{artifact}`; PATCH `{archived}` | | `/analysis-artifacts/:id/revisions` | GET ascending `{revisions}`; POST full narrative/evidence + `expectedRevision` → 201 `{artifact}` | Project/hypothesis/artifact lists accept `includeArchived=true|false`. Missing resources return 404; stale revisions and archived writes 409; malformed bodies/unknown metric selectors 400; a valid reference incompatible with its retained result 422. Corrupt retained results return a sanitized 500 with internal diagnostics, not a false client-input error. No hard-delete, execution or validation-promotion endpoint exists. Initial metadata creation uses ordinary POST semantics; clients should not automatically retry an ambiguous creation response as though it had an idempotency receipt. Mandatory cases are covered by `test/postgres/research-workspace.test.ts`, `test/integration/research-api.test.ts` and `test/integration/research-evidence.test.ts`. The PostgreSQL fixture includes a real retained native run, legacy conversion, exact revisions, direct-SQL guards, concurrent edits/archive, a one-connection pool and migration upgrade/reapply preservation. Combined validation and reviewed source hashes are recorded in the manifest's twenty-fourth-wave handoff. No production/development schema or catalog was changed during implementation.