diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..1f07c9e7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,13 @@ +# Auto detect text files and perform LF normalization on checkout +* text=auto eol=lf +*.md text eol=lf +*.ts text eol=lf +*.tsx text eol=lf +*.js text eol=lf +*.mjs text eol=lf +*.cjs text eol=lf +*.json text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.css text eol=lf +*.py text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ddff96a5..947ceda4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ concurrency: jobs: lint: name: Lint - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 @@ -29,7 +29,7 @@ jobs: typecheck: name: Type Check - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: lint steps: - uses: actions/checkout@v4 @@ -49,7 +49,7 @@ jobs: format: name: Format Check - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: lint steps: - uses: actions/checkout@v4 @@ -67,7 +67,7 @@ jobs: pytest: name: Pytest - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: lint steps: - uses: actions/checkout@v4 @@ -87,7 +87,7 @@ jobs: test: name: Test - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: lint services: postgres: @@ -116,7 +116,7 @@ jobs: - run: pnpm db:generate env: DATABASE_URL: postgresql://test:test@localhost:5432/test - - run: pnpm db:push + - run: pnpm db:migrate:deploy env: DATABASE_URL: postgresql://test:test@localhost:5432/test - run: pnpm test @@ -133,7 +133,7 @@ jobs: db-harness: name: DB Harness - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: [typecheck, test] services: postgres: @@ -162,7 +162,7 @@ jobs: - run: pnpm db:generate env: DATABASE_URL: postgresql://test:test@localhost:5432/test - - run: pnpm db:push + - run: pnpm db:migrate:deploy env: DATABASE_URL: postgresql://test:test@localhost:5432/test - run: pnpm build @@ -187,7 +187,7 @@ jobs: migration-chain: name: Migration Chain - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: [lint] services: postgres: @@ -249,7 +249,7 @@ jobs: build: name: Build - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: [typecheck, format, pytest, test, db-harness, migration-chain] steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 858a2b01..b6af31eb 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -8,7 +8,7 @@ on: jobs: e2e: name: Playwright E2E - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 diff --git a/.planning/MILESTONES.md b/.planning/MILESTONES.md index c3e9aa54..2589152e 100644 --- a/.planning/MILESTONES.md +++ b/.planning/MILESTONES.md @@ -60,36 +60,36 @@ Build a deployable portfolio piece — one real dataset, one real annotation flo ### Phase Progress -| # | Name | Goal | Status | -| ----- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------ | -| 11 | Public README & Portfolio First Impression | Root README, architecture diagram, demo GIF, setup docs | ✅ Done | -| 12A | CI/CD Completeness | Full CI pipeline, db:generate, format check, pytest | ✅ Done | -| 12B | Local Stack & Seed Reliability | Docker compose, boot scripts, seed, .env.example | ✅ Done | -| 12C | Dev Flow & Local Reliability Closeout | DB scripts, CV port alignment, script fixes | ✅ Done | -| 13 | Security & Input Validation Hardening | ValidationPipe, CORS, upload hardening, safe errors | ✅ Done | -| 14A | Adapter Boundary Cleanup | Repository interfaces, adapter implementations | ✅ Done | -| 14B | Domain Invariants & State Machines | Zod validation, job state machine, audit logs | ✅ Done | -| 15 | Observability & Health Checks | Request IDs, structured logs, /health endpoints | ✅ Done | -| 15.5 | Runtime Truth & State Consistency | WorkbenchRuntimeState, eligibility selectors | ✅ Done | -| 15.6 | Workflow Guidance & Primary Next Action | NextAction model, disabled reasons, recovery paths | ✅ Done | -| 15.7 | Contextual Inspector | Section-aware inspectors (Media, Dataset, Annotation, Pipeline, Jobs) | ✅ Done | -| 15.8 | UX States & Table Actions | EmptyState, ErrorState, DisabledReason, RowActions | ✅ Done | -| 15.9 | Visual System Hardening | Focus-visible, semantic colors, consistent spacing | ✅ Done | -| 15.10 | Motion, Portfolio Mode & Regression Tests | Purposeful motion, isPortfolioSafe, 32 regression tests | ✅ Done | -| 16A | Frontend Split Minimum | Feature module extraction (media, inference) | ✅ Done | -| 17 | Real Media Processing | Pillow thumbnails, MinIO read/write, BullMQ consumer, derivative persistence, checksum field | ✅ Done | -| 18 | Dataset Locking & COCO Export | Lock invariants, annotation immutability, deterministic COCO export, real image dimensions | ✅ Done | -| 19 | Real ONNX Detector & Prediction Persistence | YOLOv8n ONNX, prediction traceability, SHA-256 pinned, runtime smoke verified | ✅ FULL PASS | -| 20 | Evaluation Report E2E | IoU matching, persisted reports, per-class metrics, label mapping | ✅ FULL PASS | -| 20B | Evaluation Correctness Hardening | 7 correctness bugs fixed: per-class agg, LOCKED check, GT scoping, strict parse, non-lossy hash, matches, metricsHash | ✅ Done | -| 20C | Evaluation Integrity Finalization | Shared hash module, seed alignment, safe legacy adapter, 12-point harness, README fixed | ✅ Done | -| 20D | Evaluation Persistence & CI Hardening | DB columns, upsert-by-hash, read consistency, hex regex, strict harness fix, phase20d harness, DB-backed integration tests, CI wiring | ✅ FULL PASS | -| 20E | Evaluation Migration Finalization | Explicit migration SQL, backfill scripts, CI test job fix, phase20e harness, Phase 20D/20E artifact closeout | ✅ FULL PASS | -| 20F | Migration Chain Baseline & Backfill Hardening | Baseline migration, migrate deploy, migration-chain CI job, backfill hardening, phase20f harness, Phase 20E harness fixes | ✅ FULL PASS | -| 21 | Frontend Split Completion | Phase 21A/21B/21C/21D all complete. InspectorRouter fake state removed. AppRoutes prop surface clean. Phase 21 closed. | ✅ Done | -| 22A | Test Harness & Fixtures | Fixture contract, deterministic fixture harness, meta-harness, CI wiring | ✅ Done | -| 22B | Production-Path Test Suite | API harness (8 checks), meta-harness (DB-only CI-safe), Playwright smoke (10 tests), CI wiring. FIXTURE_IDS canonical source. | ✅ FULL PASS | -| 23 | Full E2E Playwright & Demo Video | Complete E2E flow: 19 Playwright tests, meta-harness (22A+22B+Playwright), demo docs (README-DEMO.md, DEMO-CHECKLIST.md), README portfolio cleanup, all planning artifacts updated | ✅ FULL PASS | +| # | Name | Goal | Status | +| ----- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | +| 11 | Public README & Portfolio First Impression | Root README, architecture diagram, demo GIF, setup docs | ✅ Done | +| 12A | CI/CD Completeness | Full CI pipeline, db:generate, format check, pytest | ✅ Done | +| 12B | Local Stack & Seed Reliability | Docker compose, boot scripts, seed, .env.example | ✅ Done | +| 12C | Dev Flow & Local Reliability Closeout | DB scripts, CV port alignment, script fixes | ✅ Done | +| 13 | Security & Input Validation Hardening | ValidationPipe, CORS, upload hardening, safe errors | ✅ Done | +| 14A | Adapter Boundary Cleanup | Repository interfaces, adapter implementations | ✅ Done | +| 14B | Domain Invariants & State Machines | Zod validation, job state machine, audit logs | ✅ Done | +| 15 | Observability & Health Checks | Request IDs, structured logs, /health endpoints | ✅ Done | +| 15.5 | Runtime Truth & State Consistency | WorkbenchRuntimeState, eligibility selectors | ✅ Done | +| 15.6 | Workflow Guidance & Primary Next Action | NextAction model, disabled reasons, recovery paths | ✅ Done | +| 15.7 | Contextual Inspector | Section-aware inspectors (Media, Dataset, Annotation, Pipeline, Jobs) | ✅ Done | +| 15.8 | UX States & Table Actions | EmptyState, ErrorState, DisabledReason, RowActions | ✅ Done | +| 15.9 | Visual System Hardening | Focus-visible, semantic colors, consistent spacing | ✅ Done | +| 15.10 | Motion, Portfolio Mode & Regression Tests | Purposeful motion, isPortfolioSafe, 32 regression tests | ✅ Done | +| 16A | Frontend Split Minimum | Feature module extraction (media, inference) | ✅ Done | +| 17 | Real Media Processing | Pillow thumbnails, MinIO read/write, BullMQ consumer, derivative persistence, checksum field | ✅ Done | +| 18 | Dataset Locking & COCO Export | Lock invariants, annotation immutability, deterministic COCO export, real image dimensions | ✅ Done | +| 19 | Real ONNX Detector & Prediction Persistence | YOLOv8n ONNX, prediction traceability, SHA-256 pinned, runtime smoke verified | ✅ FULL PASS | +| 20 | Evaluation Report E2E | IoU matching, persisted reports, per-class metrics, label mapping | ✅ FULL PASS | +| 20B | Evaluation Correctness Hardening | 7 correctness bugs fixed: per-class agg, LOCKED check, GT scoping, strict parse, non-lossy hash, matches, metricsHash | ✅ Done | +| 20C | Evaluation Integrity Finalization | Shared hash module, seed alignment, safe legacy adapter, 12-point harness, README fixed | ✅ Done | +| 20D | Evaluation Persistence & CI Hardening | DB columns, upsert-by-hash, read consistency, hex regex, strict harness fix, phase20d harness, DB-backed integration tests, CI wiring | ✅ FULL PASS | +| 20E | Evaluation Migration Finalization | Explicit migration SQL, backfill scripts, CI test job fix, phase20e harness, Phase 20D/20E artifact closeout | ✅ FULL PASS | +| 20F | Migration Chain Baseline & Backfill Hardening | Baseline migration, migrate deploy, migration-chain CI job, backfill hardening, phase20f harness, Phase 20E harness fixes | ✅ FULL PASS | +| 21 | Frontend Split Completion | Phase 21A/21B/21C/21D all complete. InspectorRouter fake state removed. AppRoutes prop surface clean. Phase 21 closed. | ✅ Done | +| 22A | Test Harness & Fixtures | Fixture contract, deterministic fixture harness, meta-harness, CI wiring | ✅ Done | +| 22B | Production-Path Test Suite | API harness (8 checks), meta-harness (DB-only CI-safe), Playwright smoke (10 tests), CI wiring. FIXTURE_IDS canonical source. | ✅ FULL PASS | +| 23 | Full E2E Playwright & Demo Video | Complete E2E flow: 19 Playwright tests, meta-harness (22A+22B+Playwright), demo docs (README-DEMO.md, DEMO-CHECKLIST.md), README portfolio cleanup, all planning artifacts updated | ✅ FULL PASS | ### Phase 11 Key Outcomes diff --git a/.planning/REQUIREMENTS.md b/.planning/REQUIREMENTS.md index d02b9b83..fbb6a0b4 100644 --- a/.planning/REQUIREMENTS.md +++ b/.planning/REQUIREMENTS.md @@ -203,26 +203,26 @@ The following are explicitly out of scope for v1.1: ## Traceability -| REQ-ID | Phase | Status | -| ------------------------- | ---------- | -------- | -| PORT-01 through PORT-06 | 11 | Done | -| CI-01 through CI-04 | 12 | Done | -| SEC-01 through SEC-11 | 13 | Done | -| ABS-01 through ABS-10 | 14A | Done | -| DOM-01 through DOM-07 | 14B | Done | -| OBS-01 through OBS-07 | 15 | Done | -| PRE16-01 through PRE16-17 | 15.5-15.10 | Done | -| UI-01 through UI-09 | 16A | Partial | -| MED-01 through MED-09 | 17 | Partial | -| LOCK-01 through LOCK-09 | 18 | Done | -| DET-01 through DET-08 | 19 | Done | -| EVAL-01 through EVAL-09 | 20 | Done | -| FSC-01 | 21A | Partial | -| FSC-02 through FSC-05 | 21B | Pending | -| FSC-06 | 21D | Pending | -| FSC-07 | 21B | Pending | -| FSC-08 through FSC-10 | 21A | Done | -| TEST-01 through TEST-13 | 22 | Pending | -| E2E-01 through E2E-10 | 23 | Pending | +| REQ-ID | Phase | Status | +| ------------------------- | ---------- | ------- | +| PORT-01 through PORT-06 | 11 | Done | +| CI-01 through CI-04 | 12 | Done | +| SEC-01 through SEC-11 | 13 | Done | +| ABS-01 through ABS-10 | 14A | Done | +| DOM-01 through DOM-07 | 14B | Done | +| OBS-01 through OBS-07 | 15 | Done | +| PRE16-01 through PRE16-17 | 15.5-15.10 | Done | +| UI-01 through UI-09 | 16A | Partial | +| MED-01 through MED-09 | 17 | Partial | +| LOCK-01 through LOCK-09 | 18 | Done | +| DET-01 through DET-08 | 19 | Done | +| EVAL-01 through EVAL-09 | 20 | Done | +| FSC-01 | 21A | Partial | +| FSC-02 through FSC-05 | 21B | Pending | +| FSC-06 | 21D | Pending | +| FSC-07 | 21B | Pending | +| FSC-08 through FSC-10 | 21A | Done | +| TEST-01 through TEST-13 | 22 | Pending | +| E2E-01 through E2E-10 | 23 | Pending | **Total:** 149 requirements | **Done:** 90 | **Partial:** 12 | **Pending:** 47 diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md index 4a9c7ba5..c10e5e5c 100644 --- a/.planning/ROADMAP.md +++ b/.planning/ROADMAP.md @@ -1360,16 +1360,16 @@ Wave E (Annotation + Timeline + Inspector Final Split) is structurally complete 8 endpoint checks proving the live NestJS API surface works against seeded PostgreSQL fixtures: -| # | Endpoint | Check | -|---|----------|-------| -| 1 | `GET /api/health` | `ok: true`, `service: 'visionflow-api'` | -| 2 | `GET /api/health/runtime/status` | `api.ok: true`, `database.status: 'ready'` | -| 3 | `GET /api/projects/:projectId/datasets` | Canonical dataset present | -| 4 | `GET /api/.../annotation-workspace?assetId=asset_frame_1482` | MANUAL annotations present | -| 5 | `GET /api/.../export/coco` | LOCKED status, deterministic hash, COCO schema valid, hash stable across 2 calls | -| 6 | `GET /api/.../inference-jobs` | Canonical job visible | -| 7 | `GET /api/.../predictions` | >= 3 predictions | -| 8 | `GET /api/.../evaluation` | `report.inputHash === FIXTURE_IDS.evaluation.inputHash` | +| # | Endpoint | Check | +| --- | ------------------------------------------------------------ | -------------------------------------------------------------------------------- | +| 1 | `GET /api/health` | `ok: true`, `service: 'visionflow-api'` | +| 2 | `GET /api/health/runtime/status` | `api.ok: true`, `database.status: 'ready'` | +| 3 | `GET /api/projects/:projectId/datasets` | Canonical dataset present | +| 4 | `GET /api/.../annotation-workspace?assetId=asset_frame_1482` | MANUAL annotations present | +| 5 | `GET /api/.../export/coco` | LOCKED status, deterministic hash, COCO schema valid, hash stable across 2 calls | +| 6 | `GET /api/.../inference-jobs` | Canonical job visible | +| 7 | `GET /api/.../predictions` | >= 3 predictions | +| 8 | `GET /api/.../evaluation` | `report.inputHash === FIXTURE_IDS.evaluation.inputHash` | - Uses `FIXTURE_IDS` from `scripts/fixtures/visionflow-fixtures.ts` — no hard-coded IDs - `--strict` mode: exit 1 if API unreachable or any check fails @@ -1508,37 +1508,37 @@ v1.1 is complete only when all of the following are true: ## Recommended Execution Order -| # | Phase | Blocked By | -| ----- | ------------------------------------------- | ---------------------------------------------------- | -| 11 | Public README & Portfolio First Impression | Phase 10 | -| 12A | CI/CD Completeness | Phase 10 | -| 12B | Local Stack & Seed Reliability | Phase 12A | -| 12C | Dev Flow & Local Reliability Closeout | Phase 12A | -| 13 | Security & Input Validation Hardening | Phase 11, Phase 12A | -| 14A | Adapter Boundary Cleanup | Phase 12A | -| 14B | Domain Invariants & State Machines | Phase 14A | -| 15 | Observability & Health Checks | Phase 14A | -| 15.5 | Runtime Truth & State Consistency | Phase 15 | -| 15.6 | Workflow Guidance & Primary Next Action | Phase 15.5 | -| 15.7 | Contextual Inspector | Phase 15.5 | -| 15.8 | UX States & Table Actions | Phase 15.6, Phase 15.7 | -| 15.9 | Visual System Hardening | Phase 15.8 | -| 15.10 | Motion, Portfolio Mode & Regression Tests | Phase 15.9 | -| 16A | Frontend Split Minimum | Phase 15.10 | -| 17 | Real Media Processing | Phase 14A, Phase 14B, Phase 15 | -| 18 | Dataset Locking & Deterministic COCO Export | Phase 14B | -| 19 | Real ONNX Detector & Prediction Persistence | Phase 17, Phase 18 | -| 20 | Evaluation Report End-to-End | Phase 19 | -| 20B | Evaluation Correctness Hardening | Phase 20 | -| 20C | Evaluation Integrity Finalization | Phase 20B | -| 20D | Evaluation Persistence & CI Hardening | Phase 20C | -| 20E | Evaluation Migration Finalization | Phase 20D | -| 20F | Migration Chain Baseline & Backfill | Phase 20E | -| 21-0 | Planning Cleanup Patch | Phase 20F | -| 21 | Frontend Feature Split Completion | Phase 20F | -| 22A | Fixture & Test Infrastructure | Phase 14A | -| 22B | Production-Path Test Suite | Phase 22A | ✅ Done 2026-05-05 | -| 23 | Full E2E Playwright & Demo Video | Phase 22B | ✅ Done 2026-05-05 | +| # | Phase | Blocked By | +| ----- | ------------------------------------------- | ------------------------------ | ------------------ | +| 11 | Public README & Portfolio First Impression | Phase 10 | +| 12A | CI/CD Completeness | Phase 10 | +| 12B | Local Stack & Seed Reliability | Phase 12A | +| 12C | Dev Flow & Local Reliability Closeout | Phase 12A | +| 13 | Security & Input Validation Hardening | Phase 11, Phase 12A | +| 14A | Adapter Boundary Cleanup | Phase 12A | +| 14B | Domain Invariants & State Machines | Phase 14A | +| 15 | Observability & Health Checks | Phase 14A | +| 15.5 | Runtime Truth & State Consistency | Phase 15 | +| 15.6 | Workflow Guidance & Primary Next Action | Phase 15.5 | +| 15.7 | Contextual Inspector | Phase 15.5 | +| 15.8 | UX States & Table Actions | Phase 15.6, Phase 15.7 | +| 15.9 | Visual System Hardening | Phase 15.8 | +| 15.10 | Motion, Portfolio Mode & Regression Tests | Phase 15.9 | +| 16A | Frontend Split Minimum | Phase 15.10 | +| 17 | Real Media Processing | Phase 14A, Phase 14B, Phase 15 | +| 18 | Dataset Locking & Deterministic COCO Export | Phase 14B | +| 19 | Real ONNX Detector & Prediction Persistence | Phase 17, Phase 18 | +| 20 | Evaluation Report End-to-End | Phase 19 | +| 20B | Evaluation Correctness Hardening | Phase 20 | +| 20C | Evaluation Integrity Finalization | Phase 20B | +| 20D | Evaluation Persistence & CI Hardening | Phase 20C | +| 20E | Evaluation Migration Finalization | Phase 20D | +| 20F | Migration Chain Baseline & Backfill | Phase 20E | +| 21-0 | Planning Cleanup Patch | Phase 20F | +| 21 | Frontend Feature Split Completion | Phase 20F | +| 22A | Fixture & Test Infrastructure | Phase 14A | +| 22B | Production-Path Test Suite | Phase 22A | ✅ Done 2026-05-05 | +| 23 | Full E2E Playwright & Demo Video | Phase 22B | ✅ Done 2026-05-05 | ## Brutal Scope Rules diff --git a/.planning/STATE.md b/.planning/STATE.md index d315fef5..e948871a 100644 --- a/.planning/STATE.md +++ b/.planning/STATE.md @@ -501,12 +501,14 @@ Phase 20B summary stated that seed hash was aligned with the runtime. Upon close Phase 21A established the app composition boundary. `App.tsx` is now the thin composition root. All route rendering is in `AppRoutes.tsx`. All panel components are in the `app/` directory. **Files extracted (commit 86416bf):** + - `AppRoutes.tsx` — route rendering with conditional panel display - `OverviewPanel.tsx`, `MediaPanel.tsx`, `DatasetPanel.tsx`, `PipelinePanel.tsx`, `JobsPanel.tsx` — panel components - `Panel`, `VisionPreview`, `StateRow`, `OverviewStateRow` — shared UI primitives - `NavRail`, `ShellHeader`, `ReadinessStrip`, `StatusPill` — shell components **Import cleanup (this pass):** + - Removed 11 unused icon imports from App.tsx - Removed 8 unused type imports from App.tsx - Removed 40+ unused value/component imports from App.tsx @@ -517,17 +519,20 @@ Phase 21A established the app composition boundary. `App.tsx` is now the thin co - Removed unused `MediaInspectorData`/`DatasetInspectorData` type imports from AppRoutes.tsx **App.tsx line counts:** + - Before Phase 21A: 799 lines - After extraction (86416bf): 638 lines - After cleanup (this pass): 548 lines **Boundary maintained:** + - `app/` imports `features/` — correct - `features/` does not import `app/` — correct - `shared/` does not import `app/` or `features/` — correct - No circular dependencies **Not changed:** + - No hook extraction — reserved for Phase 21B - No state management changes — React useState/useEffect remain - No backend changes diff --git a/.planning/phases/phase-20f-migration-chain-baseline/20F-REVIEW.md b/.planning/phases/phase-20f-migration-chain-baseline/20F-REVIEW.md index 6af13d85..e8b462ff 100644 --- a/.planning/phases/phase-20f-migration-chain-baseline/20F-REVIEW.md +++ b/.planning/phases/phase-20f-migration-chain-baseline/20F-REVIEW.md @@ -111,12 +111,12 @@ None. Phase 20F adds infrastructure (baseline migration, CI job, harness) that i ## Outstanding Limitations -| Limitation | Severity | Acceptable? | -| ------------------------------------------------------- | -------- | ----------------------------------------------------------- | -| Local harness exec() fails for `@visionflow/contracts` | LOW | Yes — CI runs proper subprocesses, inline checks cover locally | -| `db:migrate:deploy` not tested offline/air-gapped | LOW | Yes — CI environment has network access | -| `reset-schema.sql.ts` is destructive | LOW | Yes — dev-only utility, clearly labeled | -| Baseline includes Phase 20D/20E columns at init | LOW | Yes — new DBs should have full schema from start | +| Limitation | Severity | Acceptable? | +| ------------------------------------------------------ | -------- | -------------------------------------------------------------- | +| Local harness exec() fails for `@visionflow/contracts` | LOW | Yes — CI runs proper subprocesses, inline checks cover locally | +| `db:migrate:deploy` not tested offline/air-gapped | LOW | Yes — CI environment has network access | +| `reset-schema.sql.ts` is destructive | LOW | Yes — dev-only utility, clearly labeled | +| Baseline includes Phase 20D/20E columns at init | LOW | Yes — new DBs should have full schema from start | ## Verification diff --git a/.planning/phases/phase-20f-migration-chain-baseline/20F-SUMMARY.md b/.planning/phases/phase-20f-migration-chain-baseline/20F-SUMMARY.md index 34e97877..381afe23 100644 --- a/.planning/phases/phase-20f-migration-chain-baseline/20F-SUMMARY.md +++ b/.planning/phases/phase-20f-migration-chain-baseline/20F-SUMMARY.md @@ -111,6 +111,7 @@ Note: Sub-harness checks use inline DB queries instead of `exec()` to avoid loca All gates pass: `pnpm db:generate`, `pnpm typecheck`, `pnpm build`, `pnpm lint`. Migration chain verified end-to-end: + 1. Fresh DB: `pnpm db:migrate:deploy` — all 3 migrations applied 2. `pnpm db:migrate:status` — clean (3 applied, 0 pending, 0 failed) 3. `pnpm seed:db -- --reset` — seed data created @@ -119,24 +120,24 @@ Migration chain verified end-to-end: ## Success Criteria -| # | Criterion | Status | -| --- | -------------------------------------------------------------- | ------ | -| 1 | Baseline migration `00000000000000_init` exists | ✅ | -| 2 | Baseline covers all 16 models, all enums, all constraints | ✅ | -| 3 | Fresh DB runs `db:migrate:deploy` without failing | ✅ | -| 4 | Phase 20E patch migration idempotent after baseline | ✅ | -| 5 | `db:migrate:deploy` and `db:migrate:status` scripts exist | ✅ | -| 6 | Phase 20F harness verifies 11 DB integrity points | ✅ | -| 7 | CI has `migration-chain` job proving deploy from fresh DB | ✅ | -| 8 | `build` job depends on `migration-chain` | ✅ | -| 9 | Backfill script correctly handles `null` row + valid JSON | ✅ | -| 10 | Backfill script validates JSON hash format before applying | ✅ | -| 11 | Phase 20E `logFail` is red | ✅ | -| 12 | Phase 20E latest report uses `ORDER BY createdAt DESC` | ✅ | -| 13 | Phase 20F planning artifacts complete | ✅ | -| 14 | STATE/ROADMAP/MILESTONES updated | ✅ | -| 15 | README updated | ✅ | -| 16 | Documentation distinguishes `db:push` (dev) from `migrate:deploy` (prod) | ✅ | +| # | Criterion | Status | +| --- | ------------------------------------------------------------------------ | ------ | +| 1 | Baseline migration `00000000000000_init` exists | ✅ | +| 2 | Baseline covers all 16 models, all enums, all constraints | ✅ | +| 3 | Fresh DB runs `db:migrate:deploy` without failing | ✅ | +| 4 | Phase 20E patch migration idempotent after baseline | ✅ | +| 5 | `db:migrate:deploy` and `db:migrate:status` scripts exist | ✅ | +| 6 | Phase 20F harness verifies 11 DB integrity points | ✅ | +| 7 | CI has `migration-chain` job proving deploy from fresh DB | ✅ | +| 8 | `build` job depends on `migration-chain` | ✅ | +| 9 | Backfill script correctly handles `null` row + valid JSON | ✅ | +| 10 | Backfill script validates JSON hash format before applying | ✅ | +| 11 | Phase 20E `logFail` is red | ✅ | +| 12 | Phase 20E latest report uses `ORDER BY createdAt DESC` | ✅ | +| 13 | Phase 20F planning artifacts complete | ✅ | +| 14 | STATE/ROADMAP/MILESTONES updated | ✅ | +| 15 | README updated | ✅ | +| 16 | Documentation distinguishes `db:push` (dev) from `migrate:deploy` (prod) | ✅ | ## Phase 20 Evaluation Subsystem — Final Score: 10/10 diff --git a/.planning/phases/phase-21-0-planning-cleanup-patch/21-0-PLAN.md b/.planning/phases/phase-21-0-planning-cleanup-patch/21-0-PLAN.md index a1d6f84e..f5db7735 100644 --- a/.planning/phases/phase-21-0-planning-cleanup-patch/21-0-PLAN.md +++ b/.planning/phases/phase-21-0-planning-cleanup-patch/21-0-PLAN.md @@ -16,17 +16,17 @@ Several phases (13, 14A, 14B, 16A, 17, 18, 20B, 20C, 20D, 20E, 20F) completed th ### A. REQUIREMENTS.md sync -| Section | Before | After | Phase | -|---------|--------|-------|-------| -| PORT-01–06 | Pending | Done | 11 | -| SEC-01–11 | Pending | Done | 13 | -| ABS-01–10 | Pending | Done | 14A | -| DOM-01–07 | Pending | Done | 14B | -| UI-01–09 | Pending | Partial | 16A | -| MED-01–09 | Pending | Partial | 17 | -| LOCK-01–09 | Pending | Done | 18 | -| DET-01–08 | Pending | Done | 19 | -| EVAL-01–09 | Pending | Done | 20 | +| Section | Before | After | Phase | +| ---------- | ------- | ------- | ----- | +| PORT-01–06 | Pending | Done | 11 | +| SEC-01–11 | Pending | Done | 13 | +| ABS-01–10 | Pending | Done | 14A | +| DOM-01–07 | Pending | Done | 14B | +| UI-01–09 | Pending | Partial | 16A | +| MED-01–09 | Pending | Partial | 17 | +| LOCK-01–09 | Pending | Done | 18 | +| DET-01–08 | Pending | Done | 19 | +| EVAL-01–09 | Pending | Done | 20 | - MED-02: Frame extraction deferred → Partial - MED-07: Failure flow documented @@ -70,12 +70,12 @@ Several phases (13, 14A, 14B, 16A, 17, 18, 20B, 20C, 20D, 20E, 20F) completed th ## Files Changed -| File | Changes | -|------|---------| -| `.planning/REQUIREMENTS.md` | PORT/SEC/ABS/DOM/UI/MED/LOCK/DET/EVAL checked, trace table updated, TEST/E2E tagged | -| `.planning/MILESTONES.md` | v1.1 completion list, Phase 20F status | -| `README.md` | DB migration commands, architecture block, Implementation Status, Known Limitations | -| `.planning/ROADMAP.md` | Header, Phase 21-0 section, Phase 21 waves, Phase 22A/B adjustments, execution table | +| File | Changes | +| --------------------------- | ------------------------------------------------------------------------------------ | +| `.planning/REQUIREMENTS.md` | PORT/SEC/ABS/DOM/UI/MED/LOCK/DET/EVAL checked, trace table updated, TEST/E2E tagged | +| `.planning/MILESTONES.md` | v1.1 completion list, Phase 20F status | +| `README.md` | DB migration commands, architecture block, Implementation Status, Known Limitations | +| `.planning/ROADMAP.md` | Header, Phase 21-0 section, Phase 21 waves, Phase 22A/B adjustments, execution table | ## Verification diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21A-PLAN.md b/.planning/phases/phase-21-frontend-feature-split-completion/21A-PLAN.md index 89ed480a..40507c37 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21A-PLAN.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21A-PLAN.md @@ -8,6 +8,7 @@ ## Scope Phase 21A establishes the app composition boundary by: + 1. Extracting route rendering to `AppRoutes.tsx` 2. Extracting panel components to `app/` directory 3. Removing all route/panel JSX blocks from `App.tsx` @@ -27,22 +28,22 @@ Phase 21A establishes the app composition boundary by: ## Deliverables -| Deliverable | Status | -|---|---| -| `AppRoutes.tsx` extracted | Done (commit 86416bf) | -| `OverviewPanel.tsx` extracted | Done (commit 86416bf) | -| `MediaPanel.tsx` extracted | Done (commit 86416bf) | -| `DatasetPanel.tsx` extracted | Done (commit 86416bf) | -| `PipelinePanel.tsx` extracted | Done (commit 86416bf) | -| `JobsPanel.tsx` extracted | Done (commit 86416bf) | -| `Panel`/`VisionPreview`/`StateRow` extracted | Done (commit 86416bf) | +| Deliverable | Status | +| -------------------------------------------------------- | --------------------- | +| `AppRoutes.tsx` extracted | Done (commit 86416bf) | +| `OverviewPanel.tsx` extracted | Done (commit 86416bf) | +| `MediaPanel.tsx` extracted | Done (commit 86416bf) | +| `DatasetPanel.tsx` extracted | Done (commit 86416bf) | +| `PipelinePanel.tsx` extracted | Done (commit 86416bf) | +| `JobsPanel.tsx` extracted | Done (commit 86416bf) | +| `Panel`/`VisionPreview`/`StateRow` extracted | Done (commit 86416bf) | | `NavRail`, `ShellHeader`, `ReadinessStrip`, `StatusPill` | Done (commit 86416bf) | -| `App.tsx` import cleanup | Done (this pass) | -| `AppRoutes.tsx` import cleanup | Done (this pass) | -| Dead `visibleMediaRows` removed from App.tsx | Done (this pass) | -| Dead `showPipelineExecution` removed from App.tsx | Done (this pass) | -| Dead `useRef` removed from App.tsx | Done (this pass) | -| Inline `MediaUploadRow` import fixed in AppRoutes | Done (this pass) | +| `App.tsx` import cleanup | Done (this pass) | +| `AppRoutes.tsx` import cleanup | Done (this pass) | +| Dead `visibleMediaRows` removed from App.tsx | Done (this pass) | +| Dead `showPipelineExecution` removed from App.tsx | Done (this pass) | +| Dead `useRef` removed from App.tsx | Done (this pass) | +| Inline `MediaUploadRow` import fixed in AppRoutes | Done (this pass) | ## Acceptance Criteria diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21A-REVIEW.md b/.planning/phases/phase-21-frontend-feature-split-completion/21A-REVIEW.md index e03a07fe..e79cfe39 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21A-REVIEW.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21A-REVIEW.md @@ -7,6 +7,7 @@ Phase 21A is complete after two cleanup rounds. Round 1 (27d78bb) addressed bulk import removal. Round 2 (2f3a1c4) fixed residual unused imports found by brutal audit. Score breakdown: + - Route extraction: 9/10 - App.tsx reduction: 9/10 - Import cleanup: 9/10 (9 more unused imports found and fixed in round 2) @@ -30,10 +31,12 @@ Remaining gap to 10/10: root `pnpm test` has 1 pre-existing unrelated failure; r `Panel`, `OverviewPanel`, `MediaPanel`, `DatasetPanel`, `PipelinePanel`, `JobsPanel`, `VisionPreview`, `StateRow`, `buildDatasetInspectorData`, `buildMediaInspectorData`, `AnnotationEnginePanel`, `AnnotationInspector`, `DatasetInspector`, `InspectorRouter`, `JobInspector`, `MediaInspector`, `PipelineInspector`, `EmptyState`, `EvaluationEmptyState`, `MediaEmptyState`, `DatasetEmptyState`, `PredictionsEmptyState`, `ErrorState`, `FailedJobErrorState`, `ActionHint`, `Background`, `Controls`, `Edge as FlowEdge`, `MarkerType`, `Node as FlowNode`, `Position`, `ReactFlow`, `AnimatePresence`, `motion`, `useReducedMotion`, `motionTokens`, `createEmptySplitSummary`, `SplitSummary`, `summarizeDatasetSplits`, `validateMediaMime`, `EvaluationMetricsPanel`, `PredictionOverlayCanvas`, `TimelineReplayPanel`, `DatasetVersionDiff`, `PipelineExecutionFlow`, `assignDatasetVersionAssets`, `createDataset`, `createDatasetVersion`, `lockDatasetVersion`, `checksumFile`, `uploadMediaFile`, `updateProjectPipeline`, `validateProjectPipeline`, `canShowPredictionOverlay`, `datasetSplits`, `DatasetActionState`, `DatasetSourceState`, `PipelineSourceState` **Removed dead derived values (2):** + - `visibleMediaRows` — duplicated; `AppRoutes.tsx` computes it independently - `showPipelineExecution` — computed but never consumed **Removed unused hook (1):** + - `useRef` ### App.tsx Import Cleanup — Round 2 (2f3a1c4) — Residual Unused Imports @@ -106,11 +109,13 @@ Grep across all `.tsx` files in `src/` for `from '../app'` and `from './app'` ## Behavior Preservation Review ### Route Behavior + - All routes (`overview`, `media`, `datasets`, `annotate`, `pipeline`, `jobs`, `timeline`, `diff`) render identically - No route logic changed in `App.tsx` - `AppRoutes` uses the same route-to-panel mapping ### State Behavior + - All state is still managed in `App.tsx` — no state moved - All effects (dataset loading, SSE, polling, evaluation fetching) remain in `App.tsx` - No behavior changes to runtime state derivation @@ -140,31 +145,31 @@ Grep across all `.tsx` files in `src/` for `from '../app'` and `from './app'` ## Verification Checklist -| Check | Status | Notes | -|---|---|---| -| App.tsx has no unused imports | ✅ Done (round 1 + round 2) | | -| AppRoutes.tsx has no unused imports | ✅ Done (round 1 + round 2) | | -| `visibleMediaRows` dead code removed | ✅ Done | | -| `showPipelineExecution` dead code removed | ✅ Done | | -| `useRef` unused hook removed | ✅ Done | | -| `ActivityIcon`, `StatusPill`, etc. removed | ✅ Done (round 2) | | -| `MediaInspectorData`/`DatasetInspectorData` removed | ✅ Done (round 2) | | -| `pnpm --filter @visionflow/web typecheck` | ✅ PASS | | -| `pnpm --filter @visionflow/web test` | ✅ PASS (63/63) | | -| `pnpm --filter @visionflow/web lint` | ✅ PASS | | -| `pnpm --filter @visionflow/web build` | ✅ PASS | | -| Touched files pass Prettier check | ✅ PASS | | -| `pnpm typecheck` (root) | ✅ PASS | | -| `pnpm test` (root) | ⚠️ PARTIAL FAIL | 1 pre-existing unrelated flaky API test | -| `pnpm lint` (root) | ✅ PASS | | -| `pnpm format:check` (root) | ❌ FAIL | 17 pre-existing unrelated format failures | -| No backend files changed | ✅ Confirmed | | -| No .cursor files changed | ✅ Confirmed | | -| No .metaharness files changed | ✅ Confirmed | | -| No circular imports | ✅ Confirmed | | -| No route behavior changed | ✅ Confirmed | | -| App.tsx contains orchestration only | ✅ Confirmed | | -| Boundary: `app/` → `features/` only | ✅ Confirmed | | -| Boundary: `shared/` → no `app/` or `features/` | ✅ Confirmed | | +| Check | Status | Notes | +| --------------------------------------------------- | --------------------------- | ----------------------------------------- | +| App.tsx has no unused imports | ✅ Done (round 1 + round 2) | | +| AppRoutes.tsx has no unused imports | ✅ Done (round 1 + round 2) | | +| `visibleMediaRows` dead code removed | ✅ Done | | +| `showPipelineExecution` dead code removed | ✅ Done | | +| `useRef` unused hook removed | ✅ Done | | +| `ActivityIcon`, `StatusPill`, etc. removed | ✅ Done (round 2) | | +| `MediaInspectorData`/`DatasetInspectorData` removed | ✅ Done (round 2) | | +| `pnpm --filter @visionflow/web typecheck` | ✅ PASS | | +| `pnpm --filter @visionflow/web test` | ✅ PASS (63/63) | | +| `pnpm --filter @visionflow/web lint` | ✅ PASS | | +| `pnpm --filter @visionflow/web build` | ✅ PASS | | +| Touched files pass Prettier check | ✅ PASS | | +| `pnpm typecheck` (root) | ✅ PASS | | +| `pnpm test` (root) | ⚠️ PARTIAL FAIL | 1 pre-existing unrelated flaky API test | +| `pnpm lint` (root) | ✅ PASS | | +| `pnpm format:check` (root) | ❌ FAIL | 17 pre-existing unrelated format failures | +| No backend files changed | ✅ Confirmed | | +| No .cursor files changed | ✅ Confirmed | | +| No .metaharness files changed | ✅ Confirmed | | +| No circular imports | ✅ Confirmed | | +| No route behavior changed | ✅ Confirmed | | +| App.tsx contains orchestration only | ✅ Confirmed | | +| Boundary: `app/` → `features/` only | ✅ Confirmed | | +| Boundary: `shared/` → no `app/` or `features/` | ✅ Confirmed | | **Phase 21A is 9.5/10.** Route extraction, composition boundary, and import cleanup are solid. Score docked for: residual unused imports (fixed in round 2), pre-existing test/format failures not from Phase 21A, browser smoke not run, and artifact overclaim in round 1. diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21A-SUMMARY.md b/.planning/phases/phase-21-frontend-feature-split-completion/21A-SUMMARY.md index 03e70ea9..4912c466 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21A-SUMMARY.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21A-SUMMARY.md @@ -9,6 +9,7 @@ ## Files Changed ### Extraction (Commit 86416bf) + - `apps/web/src/App.tsx` — reduced from 799 to 638 lines - `apps/web/src/app/AppRoutes.tsx` — created (route rendering) - `apps/web/src/app/OverviewPanel.tsx` — extracted @@ -22,21 +23,23 @@ - `apps/web/src/app/ui/OverviewStateRow.tsx` — extracted ### Cleanup Round 1 (Commit 27d78bb) + - `apps/web/src/App.tsx` — reduced from 638 to 548 lines - `apps/web/src/app/AppRoutes.tsx` — import cleanup **Audit finding:** Commit 27d78bb left residual unused imports (see below). ### Cleanup Round 2 — Leftovers Fix (Commit 2f3a1c4) + - `apps/web/src/App.tsx` — reduced from 548 to 529 lines; removed 9 more unused imports - `apps/web/src/app/AppRoutes.tsx` — removed 2 unused type imports ## Line Counts -| File | Before Phase 21A | After Extraction (86416bf) | After Cleanup R1 (27d78bb) | After Cleanup R2 (2f3a1c4) | -|---|---|---|---|---| -| `App.tsx` | 799 | 638 | 548 | **529** | -| `AppRoutes.tsx` | N/A | 206 | 209 | 210 | +| File | Before Phase 21A | After Extraction (86416bf) | After Cleanup R1 (27d78bb) | After Cleanup R2 (2f3a1c4) | +| --------------- | ---------------- | -------------------------- | -------------------------- | -------------------------- | +| `App.tsx` | 799 | 638 | 548 | **529** | +| `AppRoutes.tsx` | N/A | 206 | 209 | 210 | ## What Changed (Cleanup Pass — All Rounds) @@ -52,10 +55,12 @@ `Panel`, `OverviewPanel`, `MediaPanel`, `DatasetPanel`, `PipelinePanel`, `JobsPanel`, `VisionPreview`, `StateRow`, `buildDatasetInspectorData`, `buildMediaInspectorData`, `AnnotationEnginePanel`, `AnnotationInspector`, `DatasetInspector`, `InspectorRouter`, `JobInspector`, `MediaInspector`, `PipelineInspector`, `EmptyState`, `EvaluationEmptyState`, `MediaEmptyState`, `DatasetEmptyState`, `PredictionsEmptyState`, `ErrorState`, `FailedJobErrorState`, `ActionHint`, `Background`, `Controls`, `Edge as FlowEdge`, `MarkerType`, `Node as FlowNode`, `Position`, `ReactFlow`, `AnimatePresence`, `motion`, `useReducedMotion`, `motionTokens`, `createEmptySplitSummary`, `SplitSummary`, `summarizeDatasetSplits`, `validateMediaMime`, `EvaluationMetricsPanel`, `PredictionOverlayCanvas`, `TimelineReplayPanel`, `DatasetVersionDiff`, `PipelineExecutionFlow`, `assignDatasetVersionAssets`, `createDataset`, `createDatasetVersion`, `lockDatasetVersion`, `checksumFile`, `uploadMediaFile`, `updateProjectPipeline`, `validateProjectPipeline`, `canShowPredictionOverlay`, `datasetSplits`, `DatasetActionState`, `DatasetSourceState`, `PipelineSourceState` **Removed dead derived values (2):** + - `visibleMediaRows` — duplicated; `AppRoutes.tsx` computes it independently - `showPipelineExecution` — computed but never consumed **Removed unused hook (1):** + - `useRef` ### Import Cleanup in `App.tsx` — Round 2 (2f3a1c4) — Leftovers Found by Audit @@ -77,18 +82,18 @@ These were not used in the App component's JSX render or helper functions. ## Verification Results -| Command | Result | Notes | -|---|---|---| -| `pnpm --filter @visionflow/web typecheck` | **PASS** | | -| `pnpm --filter @visionflow/web test` | **PASS** | 63/63 | -| `pnpm --filter @visionflow/web lint` | **PASS** | | -| `pnpm --filter @visionflow/web build` | **PASS** | | -| `pnpm --filter @visionflow/web prettier --check` | **PASS** | Touched files only | -| `pnpm typecheck` (root) | **PASS** | | -| `pnpm test` (root) | **PARTIAL FAIL** | 1 pre-existing flaky API test in `inference.service.test.ts` — CV_WORKER_URL timeout, unrelated to Phase 21A | -| `pnpm lint` (root) | **PASS** | | -| `pnpm format:check` (root) | **FAIL** | 17 pre-existing formatting failures in unrelated files | -| Browser smoke | Not run | Verification limited to typecheck/test/build/lint | +| Command | Result | Notes | +| ------------------------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------ | +| `pnpm --filter @visionflow/web typecheck` | **PASS** | | +| `pnpm --filter @visionflow/web test` | **PASS** | 63/63 | +| `pnpm --filter @visionflow/web lint` | **PASS** | | +| `pnpm --filter @visionflow/web build` | **PASS** | | +| `pnpm --filter @visionflow/web prettier --check` | **PASS** | Touched files only | +| `pnpm typecheck` (root) | **PASS** | | +| `pnpm test` (root) | **PARTIAL FAIL** | 1 pre-existing flaky API test in `inference.service.test.ts` — CV_WORKER_URL timeout, unrelated to Phase 21A | +| `pnpm lint` (root) | **PASS** | | +| `pnpm format:check` (root) | **FAIL** | 17 pre-existing formatting failures in unrelated files | +| Browser smoke | Not run | Verification limited to typecheck/test/build/lint | ### Pre-existing Failures (Not From Phase 21A) @@ -98,12 +103,12 @@ These were not used in the App component's JSX render or helper functions. ## Boundary Review -| Direction | Status | -|---|---| -| `app/` imports `features/` | Clean — `AppRoutes.tsx` imports from `features/annotations`, `features/timeline`, `features/inspector`, `features/media`, `features/inference` | -| `features/` imports `app/` | Clean — no `features/*` files import from `app/` | -| `shared/` imports `app/` or `features/` | Clean — no `shared/*` files import from `app/` or `features/` | -| Circular dependencies | None detected | +| Direction | Status | +| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `app/` imports `features/` | Clean — `AppRoutes.tsx` imports from `features/annotations`, `features/timeline`, `features/inspector`, `features/media`, `features/inference` | +| `features/` imports `app/` | Clean — no `features/*` files import from `app/` | +| `shared/` imports `app/` or `features/` | Clean — no `shared/*` files import from `app/` or `features/` | +| Circular dependencies | None detected | ## Remaining Limitations diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21B-PLAN.md b/.planning/phases/phase-21-frontend-feature-split-completion/21B-PLAN.md index 9a87f951..5a6837a5 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21B-PLAN.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21B-PLAN.md @@ -1,9 +1,11 @@ # Phase 21B Plan — FE/BE Runtime Sync and Controller Extraction ## Goal + Synchronize frontend runtime readiness with real backend/CV worker state, remove stale hard-coded readiness labels, and extract App.tsx orchestration into controller hooks. ## Context + Phase 21A established the app composition boundary. `App.tsx` was reduced from 799 to 529 lines. It still owns dataset loading, inference job SSE/polling, evaluation fetch/run, runtimeState derivation, and startJob. ReadinessStrip still uses static/hard-coded readiness text ("Mock detector mounted"). The frontend reads nothing from the backend about actual runtime state. ## Scope @@ -13,6 +15,7 @@ Phase 21A established the app composition boundary. `App.tsx` was reduced from 7 **Goal:** Add `GET /api/health/runtime/status` returning real state of API, database, queue, and CV worker. **Implementation:** + - Extend `HealthService` with `getRuntimeStatus()` method - Add `RuntimeStatusResponseDto` and `RuntimeStatusResponseSchema` (Zod) - Endpoint returns 200 even if CV worker is down (only marks `cvWorker.ok = false`) @@ -20,6 +23,7 @@ Phase 21A established the app composition boundary. `App.tsx` was reduced from 7 - No secret leaking (model paths masked) **Contract:** + ```typescript RuntimeStatusResponse = { api: { ok: boolean; mode: 'database' | 'memory' | 'unknown' }; @@ -41,6 +45,7 @@ RuntimeStatusResponse = { **Goal:** Replace client-side guessing with real backend data. **Implementation:** + - Create `features/runtime/runtime.api.ts` — calls `/api/health/runtime/status` - Create `features/runtime/runtime.types.ts` — derived state types (CvReadinessState, QueueReadinessState, etc.) - Create `features/runtime/useRuntimeStatus.ts` — polls every 8s, exposes loading/error/data @@ -51,6 +56,7 @@ RuntimeStatusResponse = { **Goal:** `ReadinessStrip` reflects real state. `App.tsx` shrinks. **ReadinessStrip:** + - Replace hard-coded "Mock detector mounted" with real runtime data - States: ONNX detector ready / ONNX configured unavailable / Mock fallback / Worker unavailable / Loading / Unknown - Queue states: BullMQ ready / Memory fallback / Unavailable / Loading / Unknown @@ -68,6 +74,7 @@ RuntimeStatusResponse = { ### 21B.4 — Browser Smoke **Checklist:** + - App loads at http://localhost:5173 - ReadinessStrip shows ONNX detector ready if env ONNX + worker healthy - ReadinessStrip shows correct fallback states when services are down @@ -75,6 +82,7 @@ RuntimeStatusResponse = { - Navigation between sections works ## Verification + - [x] `pnpm --filter @visionflow/contracts typecheck` — pass - [x] `pnpm --filter @visionflow/api typecheck` — pass - [x] `pnpm --filter @visionflow/web typecheck` — pass @@ -88,6 +96,7 @@ RuntimeStatusResponse = { - [ ] Browser smoke: Navigation across sections ## Non-Goals + - No UI redesign - No new state management library (Redux/Zustand/React Query) - No algorithm changes @@ -95,16 +104,20 @@ RuntimeStatusResponse = { - No breaking contract changes ## Files + ### New (backend) + - `apps/api/src/health/dto/runtime-status-response.dto.ts` ### Modified (backend) + - `apps/api/src/health/health.service.ts` — added `getRuntimeStatus()` - `apps/api/src/health/health.controller.ts` — added `/runtime/status` endpoint - `packages/contracts/src/cv-worker.ts` — added RuntimeStatus schemas - `packages/contracts/src/index.ts` — re-exported RuntimeStatus types ### New (frontend) + - `apps/web/src/features/runtime/runtime.api.ts` - `apps/web/src/features/runtime/runtime.types.ts` - `apps/web/src/features/runtime/useRuntimeStatus.ts` @@ -114,5 +127,6 @@ RuntimeStatusResponse = { - `apps/web/src/features/inference/useEvaluationController.ts` ### Modified (frontend) + - `apps/web/src/app/ReadinessStrip.tsx` — uses `useRuntimeStatus` hook - `apps/web/src/App.tsx` — uses extracted controllers diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21B-REVIEW.md b/.planning/phases/phase-21-frontend-feature-split-completion/21B-REVIEW.md index 7ec9f399..eb7f733f 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21B-REVIEW.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21B-REVIEW.md @@ -8,15 +8,15 @@ ## Score Breakdown -| Dimension | Score | Notes | -|---|---|---| -| FE/BE contract | 9/10 | Runtime status schema is solid; frameExtractionAvailable always null | -| Runtime status failure-mode | 9/10 | API returns 200 even when CV worker is down | -| CV ONNX/mock display | 10/10 | 6 distinct CV states mapped to readable labels | -| Dependency boundary | 10/10 | No circular deps; correct import direction | -| AppRoutes prop surface | 8/10 | Reduced but still 20+ props; acceptable for now | -| Verification coverage | 10/10 | Playwright browser smoke: "Database ready", "ONNX detector ready", "BullMQ ready", no errors, no "Mock detector mounted" | -| **Overall** | **10/10** | | +| Dimension | Score | Notes | +| --------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------ | +| FE/BE contract | 9/10 | Runtime status schema is solid; frameExtractionAvailable always null | +| Runtime status failure-mode | 9/10 | API returns 200 even when CV worker is down | +| CV ONNX/mock display | 10/10 | 6 distinct CV states mapped to readable labels | +| Dependency boundary | 10/10 | No circular deps; correct import direction | +| AppRoutes prop surface | 8/10 | Reduced but still 20+ props; acceptable for now | +| Verification coverage | 10/10 | Playwright browser smoke: "Database ready", "ONNX detector ready", "BullMQ ready", no errors, no "Mock detector mounted" | +| **Overall** | **10/10** | | --- @@ -26,20 +26,20 @@ The `RuntimeStatusResponse` contract covers all critical runtime dimensions: -| Field | Source | Validation | -|---|---|---| -| `api.ok` | Always `true` | Intentional — API is the source of truth | -| `api.mode` | `detectMode()` | Reads `DATA_MODE` or falls back | -| `database.ok` | PostgresHealthService | ping() check with 5s timeout | -| `database.status` | Derived from `ok` | `'ready' \| 'unavailable' \| 'unknown'` | -| `queue.mode` | `INFERENCE_QUEUE_MODE` env | Not `DATA_MODE` — correct | -| `queue.status` | Redis ping result | `'ready' \| 'fallback' \| 'unavailable' \| 'unknown'` | -| `cvWorker.ok` | `/health` fetch | 5s timeout; `false` if unreachable | -| `cvWorker.configured` | `CV_WORKER_URL !== '' && !== 'mock'` | Correct | -| `cvWorker.requestedDetectorMode` | `CV_WORKER_DETECTOR_MODE` | `'onnx' \| 'mock'` | -| `cvWorker.activeDetectorMode` | From worker `/health` response | Matches what worker actually uses | -| `cvWorker.onnxAvailable` | From worker `/health` response | True only if onnxruntime is importable | -| `cvWorker.modelVersion` | From worker `/health` response | Masked if path | +| Field | Source | Validation | +| -------------------------------- | ------------------------------------ | ----------------------------------------------------- | +| `api.ok` | Always `true` | Intentional — API is the source of truth | +| `api.mode` | `detectMode()` | Reads `DATA_MODE` or falls back | +| `database.ok` | PostgresHealthService | ping() check with 5s timeout | +| `database.status` | Derived from `ok` | `'ready' \| 'unavailable' \| 'unknown'` | +| `queue.mode` | `INFERENCE_QUEUE_MODE` env | Not `DATA_MODE` — correct | +| `queue.status` | Redis ping result | `'ready' \| 'fallback' \| 'unavailable' \| 'unknown'` | +| `cvWorker.ok` | `/health` fetch | 5s timeout; `false` if unreachable | +| `cvWorker.configured` | `CV_WORKER_URL !== '' && !== 'mock'` | Correct | +| `cvWorker.requestedDetectorMode` | `CV_WORKER_DETECTOR_MODE` | `'onnx' \| 'mock'` | +| `cvWorker.activeDetectorMode` | From worker `/health` response | Matches what worker actually uses | +| `cvWorker.onnxAvailable` | From worker `/health` response | True only if onnxruntime is importable | +| `cvWorker.modelVersion` | From worker `/health` response | Masked if path | ### Schema Safety @@ -50,6 +50,7 @@ The `RuntimeStatusResponse` contract covers all critical runtime dimensions: ### Zod Schema Alignment `RuntimeStatusResponseSchema` in `packages/contracts/src/cv-worker.ts` matches the API DTO exactly: + - All enum variants match (`'database' | 'memory' | 'unknown'`, `'ready' | 'fallback' | 'unavailable' | 'unknown'`, `'onnx' | 'mock'`) - Frontend `runtime.types.ts` derives readable state types from the raw API response - No data loss between API and frontend consumption @@ -60,19 +61,19 @@ The `RuntimeStatusResponse` contract covers all critical runtime dimensions: ### Failure Scenarios -| Scenario | API Response | Frontend Behavior | -|---|---|---| -| CV Worker down | `cvWorker.ok = false, error = ` | Shows "Worker unavailable" (red) | -| CV Worker URL invalid hostname | `cvWorker.ok = false, error = ` | Shows "Worker unavailable" (red) | -| CV Worker URL = 'mock' | `cvWorker.ok = true, configured = false` | Shows "Mock detector fallback" (neutral) | -| No CV_WORKER_URL set | `cvWorker.ok = true, configured = false` | Shows "Mock detector fallback" (neutral) | -| Redis down | `queue.status = 'unavailable'` | Shows "Unavailable" (red) | -| PostgreSQL down | `database.ok = false` | Shows "Unavailable" (red) | -| API itself unreachable | Frontend hook catches error | Shows "Unavailable" (red) | +| Scenario | API Response | Frontend Behavior | +| ------------------------------ | ---------------------------------------------- | ---------------------------------------- | +| CV Worker down | `cvWorker.ok = false, error = ` | Shows "Worker unavailable" (red) | +| CV Worker URL invalid hostname | `cvWorker.ok = false, error = ` | Shows "Worker unavailable" (red) | +| CV Worker URL = 'mock' | `cvWorker.ok = true, configured = false` | Shows "Mock detector fallback" (neutral) | +| No CV_WORKER_URL set | `cvWorker.ok = true, configured = false` | Shows "Mock detector fallback" (neutral) | +| Redis down | `queue.status = 'unavailable'` | Shows "Unavailable" (red) | +| PostgreSQL down | `database.ok = false` | Shows "Unavailable" (red) | +| API itself unreachable | Frontend hook catches error | Shows "Unavailable" (red) | ### Key Design Decisions -1. **API always returns 200.** `getRuntimeStatus()` never throws `ServiceUnavailableException`. The endpoint aggregates all dependency health checks and returns a 200 with honest status flags. This means frontend always gets *some* response, never a network error for the endpoint itself. +1. **API always returns 200.** `getRuntimeStatus()` never throws `ServiceUnavailableException`. The endpoint aggregates all dependency health checks and returns a 200 with honest status flags. This means frontend always gets _some_ response, never a network error for the endpoint itself. 2. **`queue.mode` uses `INFERENCE_QUEUE_MODE`, not `DATA_MODE`.** This is correct — even in database mode, if `INFERENCE_QUEUE_MODE=memory`, the queue is in fallback mode. @@ -84,15 +85,15 @@ The `RuntimeStatusResponse` contract covers all critical runtime dimensions: ### State Mapping -| Backend state | Frontend state | UI label | Color | -|---|---|---|---| -| `configured=true, ok=true, requestedMode=onnx, onnxAvailable=true` | `onnx-ready` | "ONNX detector ready" | Green | -| `configured=true, ok=true, requestedMode=onnx, onnxAvailable=false` | `onnx-configured-unavailable` | "ONNX configured, unavailable" | Amber | -| `configured=true, ok=true, requestedMode=mock` | `mock-fallback` | "Mock detector fallback" | Neutral | -| `configured=true, ok=false` | `worker-unavailable` | "Worker unavailable" | Red | -| `configured=false` | `mock-fallback` | "Mock detector fallback" | Neutral | -| API unreachable (hook error) | Initial loading state | "Loading..." | Spinning | -| Not yet fetched | Initial loading state | "Loading..." | Spinning | +| Backend state | Frontend state | UI label | Color | +| ------------------------------------------------------------------- | ----------------------------- | ------------------------------ | -------- | +| `configured=true, ok=true, requestedMode=onnx, onnxAvailable=true` | `onnx-ready` | "ONNX detector ready" | Green | +| `configured=true, ok=true, requestedMode=onnx, onnxAvailable=false` | `onnx-configured-unavailable` | "ONNX configured, unavailable" | Amber | +| `configured=true, ok=true, requestedMode=mock` | `mock-fallback` | "Mock detector fallback" | Neutral | +| `configured=true, ok=false` | `worker-unavailable` | "Worker unavailable" | Red | +| `configured=false` | `mock-fallback` | "Mock detector fallback" | Neutral | +| API unreachable (hook error) | Initial loading state | "Loading..." | Spinning | +| Not yet fetched | Initial loading state | "Loading..." | Spinning | ### No Fake Readiness @@ -170,13 +171,13 @@ After Phase 21B, `App.tsx` passes ~22 props to `AppRoutes`. This is slightly red ## Behavioral Risk Assessment -| Risk | Level | Mitigation | -|---|---|---| -| ReadinessStrip shows wrong state | LOW | Hook polls every 8s; initial state is `loading` | -| ONNX status stale after startup | LOW | 8s refresh is acceptable for dev UX | -| startJob moved to hook loses setSection | LOW | App.tsx now calls `setSection('jobs')` before `startJob()` | -| Controller effects re-run on unmount | LOW | All effects use `cancelled` ref pattern | -| React StrictMode cancels hook | LOW | Removed `React.StrictMode` from `main.tsx` | +| Risk | Level | Mitigation | +| --------------------------------------- | ----- | ---------------------------------------------------------- | +| ReadinessStrip shows wrong state | LOW | Hook polls every 8s; initial state is `loading` | +| ONNX status stale after startup | LOW | 8s refresh is acceptable for dev UX | +| startJob moved to hook loses setSection | LOW | App.tsx now calls `setSection('jobs')` before `startJob()` | +| Controller effects re-run on unmount | LOW | All effects use `cancelled` ref pattern | +| React StrictMode cancels hook | LOW | Removed `React.StrictMode` from `main.tsx` | --- @@ -196,40 +197,40 @@ After Phase 21B, `App.tsx` passes ~22 props to `AppRoutes`. This is slightly red The following changes were made to close the final gap — making `runtimeState.health` derive from backend truth (not client-side guessing): -| File | Change | -|---|---| -| `apps/web/src/features/runtime/runtime.api.ts` | Fixed missing `/api` global prefix: `apiJson('/api/health/runtime/status')` | -| `apps/web/src/shared/state/workbench-runtime.ts` | Expanded `HealthStatus` union: `'fallback'`, `'unknown'`, `'mock'` | -| `apps/web/src/App.tsx` | Moved `useRuntimeStatus` to composition root; derived `runtimeState.health` from backend truth | -| `apps/web/src/app/ReadinessStrip.tsx` | Accepts `readiness` prop; no longer calls `useRuntimeStatus` internally | -| `apps/web/src/app/AppRoutes.tsx` | Passes `runtimeReadiness` prop to `ReadinessStrip` | -| `apps/web/src/main.tsx` | Removed `React.StrictMode` to prevent `cancelledRef` cancellation | -| `apps/api/src/health/health.service.ts` | Hardened `requestedDetectorMode` normalization; reads `frameExtractionAvailable` from CV worker capabilities | -| `scripts/start-dev.ps1` | Fixed misleading CV timeout text | +| File | Change | +| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | +| `apps/web/src/features/runtime/runtime.api.ts` | Fixed missing `/api` global prefix: `apiJson('/api/health/runtime/status')` | +| `apps/web/src/shared/state/workbench-runtime.ts` | Expanded `HealthStatus` union: `'fallback'`, `'unknown'`, `'mock'` | +| `apps/web/src/App.tsx` | Moved `useRuntimeStatus` to composition root; derived `runtimeState.health` from backend truth | +| `apps/web/src/app/ReadinessStrip.tsx` | Accepts `readiness` prop; no longer calls `useRuntimeStatus` internally | +| `apps/web/src/app/AppRoutes.tsx` | Passes `runtimeReadiness` prop to `ReadinessStrip` | +| `apps/web/src/main.tsx` | Removed `React.StrictMode` to prevent `cancelledRef` cancellation | +| `apps/api/src/health/health.service.ts` | Hardened `requestedDetectorMode` normalization; reads `frameExtractionAvailable` from CV worker capabilities | +| `scripts/start-dev.ps1` | Fixed misleading CV timeout text | --- ## Verification Checklist -| Check | Status | Notes | -|---|---|---| -| `pnpm --filter @visionflow/contracts typecheck` | PASS | | -| `pnpm --filter @visionflow/api typecheck` | PASS | | -| `pnpm --filter @visionflow/web typecheck` | PASS | | -| `pnpm test` | PASS (314 tests) | | -| `pnpm lint` | PASS | | -| `pnpm build` | PASS | | -| `curl http://localhost:3000/api/health` | HTTP 200 | | -| `curl http://localhost:3000/api/health/runtime/status` | HTTP 200, correct payload | | -| `curl http://localhost:8000/health` | HTTP 200 | | -| `App.tsx` line count | ~144 lines | Down from 529 | -| No circular imports | Confirmed | | -| No fake readiness states | Confirmed | | -| No "Mock detector mounted" hard-code | Confirmed | Removed | -| Boundary: app/ → features/ only | Confirmed | | -| Boundary: features/ → shared/ only | Confirmed | | -| `frameExtractionAvailable` handling | Confirmed | `null` → "Unknown" | -| Browser smoke | PASS | Playwright: "Database ready", "ONNX detector ready", "BullMQ ready", 0x "Mock detector mounted", no errors | -| `runtimeState.health` derives from backend | PASS | `useRuntimeStatus` at App root, `runtimeHealth` mapped from backend | -| Dev boot text corrected | PASS | `start-dev.ps1` no longer claims "Run button uses mock" | -| Duplicate runtime polling removed | PASS | `useRuntimeStatus` called exactly once at App level | +| Check | Status | Notes | +| ------------------------------------------------------ | ------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `pnpm --filter @visionflow/contracts typecheck` | PASS | | +| `pnpm --filter @visionflow/api typecheck` | PASS | | +| `pnpm --filter @visionflow/web typecheck` | PASS | | +| `pnpm test` | PASS (314 tests) | | +| `pnpm lint` | PASS | | +| `pnpm build` | PASS | | +| `curl http://localhost:3000/api/health` | HTTP 200 | | +| `curl http://localhost:3000/api/health/runtime/status` | HTTP 200, correct payload | | +| `curl http://localhost:8000/health` | HTTP 200 | | +| `App.tsx` line count | ~144 lines | Down from 529 | +| No circular imports | Confirmed | | +| No fake readiness states | Confirmed | | +| No "Mock detector mounted" hard-code | Confirmed | Removed | +| Boundary: app/ → features/ only | Confirmed | | +| Boundary: features/ → shared/ only | Confirmed | | +| `frameExtractionAvailable` handling | Confirmed | `null` → "Unknown" | +| Browser smoke | PASS | Playwright: "Database ready", "ONNX detector ready", "BullMQ ready", 0x "Mock detector mounted", no errors | +| `runtimeState.health` derives from backend | PASS | `useRuntimeStatus` at App root, `runtimeHealth` mapped from backend | +| Dev boot text corrected | PASS | `start-dev.ps1` no longer claims "Run button uses mock" | +| Duplicate runtime polling removed | PASS | `useRuntimeStatus` called exactly once at App level | diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21B-SUMMARY.md b/.planning/phases/phase-21-frontend-feature-split-completion/21B-SUMMARY.md index 4767979f..5d989020 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21B-SUMMARY.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21B-SUMMARY.md @@ -16,28 +16,36 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte **Endpoint:** `http://localhost:3000/api/health/runtime/status` **Response shape:** + ```json { "api": { "ok": true, "mode": "database" }, "database": { "ok": true, "status": "ready" }, "queue": { "ok": true, "mode": "bullmq", "status": "ready" }, "cvWorker": { - "ok": true, "configured": true, "url": "http://localhost:8000", - "requestedDetectorMode": "onnx", "activeDetectorMode": "onnx", - "onnxAvailable": true, "modelVersion": "yolov8n-640", + "ok": true, + "configured": true, + "url": "http://localhost:8000", + "requestedDetectorMode": "onnx", + "activeDetectorMode": "onnx", + "onnxAvailable": true, + "modelVersion": "yolov8n-640", "modelPath": "models\\yolov8n.onnx", - "frameExtractionAvailable": null, "error": null + "frameExtractionAvailable": null, + "error": null } } ``` **Key behavior:** + - Always returns HTTP 200 — even if CV worker is down (only `cvWorker.ok = false`) - CV worker details sourced from live `/health` call to `http://localhost:8000/health` - `INFERENCE_QUEUE_MODE` env var drives queue mode detection (not `DATA_MODE`) - No secret leaking — model paths are masked **Files changed:** + - `apps/api/src/health/dto/runtime-status-response.dto.ts` — new DTO - `apps/api/src/health/health.service.ts` — added `getRuntimeStatus()` - `apps/api/src/health/health.controller.ts` — added `GET /runtime/status` @@ -47,6 +55,7 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte ### 21B.2 — Frontend Runtime API + Hook **`useRuntimeStatus` hook behavior:** + - Fetches `/api/health/runtime/status` on mount - Refreshes every 8 seconds - 5-second fetch timeout @@ -70,6 +79,7 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte | `unavailable` | Unavailable (red) | **Files created:** + - `apps/web/src/features/runtime/runtime.api.ts` - `apps/web/src/features/runtime/runtime.types.ts` - `apps/web/src/features/runtime/useRuntimeStatus.ts` @@ -78,6 +88,7 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte ### 21B.3 — ReadinessStrip + Controller Extraction **`ReadinessStrip` before:** + ```tsx // hard-coded { label: 'CV', value: 'Mock detector mounted', icon: Activity, tone: '...' } @@ -104,19 +115,19 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte **Automated Playwright smoke test passed** (`scripts/smoke-21b.cjs`, now removed after use): -| Check | Result | -|---|---| -| App loads at `http://localhost:5173` | PASS | -| Page title "VisionFlow Studio" | PASS | -| `/api/health/runtime/status` called | PASS (200, called twice — initial + 8s refresh) | -| "Database ready" shown | PASS | -| "ONNX detector ready" shown | PASS | -| "BullMQ ready" shown | PASS | -| "Mock detector mounted" (hard-coded) | 0 occurrences — ELIMINATED | -| "Mock detector fallback" shown | 0 occurrences (ONNX configured) | -| "Worker unavailable" shown | 0 occurrences (worker healthy) | -| Run button visible | PASS | -| App-level console errors | None | +| Check | Result | +| ------------------------------------ | ----------------------------------------------- | +| App loads at `http://localhost:5173` | PASS | +| Page title "VisionFlow Studio" | PASS | +| `/api/health/runtime/status` called | PASS (200, called twice — initial + 8s refresh) | +| "Database ready" shown | PASS | +| "ONNX detector ready" shown | PASS | +| "BullMQ ready" shown | PASS | +| "Mock detector mounted" (hard-coded) | 0 occurrences — ELIMINATED | +| "Mock detector fallback" shown | 0 occurrences (ONNX configured) | +| "Worker unavailable" shown | 0 occurrences (worker healthy) | +| Run button visible | PASS | +| App-level console errors | None | **Key finding:** The `useRuntimeStatus` hook in App.tsx was calling `apiJson('/health/runtime/status')` (missing `/api` global prefix). Fixed to `apiJson('/api/health/runtime/status')`. Without this fix, the endpoint returned 404 and ReadinessStrip was stuck in "Loading..." state indefinitely. @@ -124,38 +135,41 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte ## Verification Results -| Check | Result | -|---|---| -| `pnpm --filter @visionflow/contracts typecheck` | PASS | -| `pnpm --filter @visionflow/api typecheck` | PASS | -| `pnpm --filter @visionflow/web typecheck` | PASS | -| `pnpm test` | 314 tests PASS | -| `pnpm lint` | PASS | -| `pnpm build` | PASS | -| `curl http://localhost:3000/api/health` | HTTP 200 | -| `curl http://localhost:3000/api/health/runtime/status` | HTTP 200, correct payload | -| `curl http://localhost:8000/health` | HTTP 200 | -| Browser smoke | PASS — Playwright: "Database ready", "ONNX detector ready", "BullMQ ready", no "Mock detector mounted", no errors | +| Check | Result | +| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | +| `pnpm --filter @visionflow/contracts typecheck` | PASS | +| `pnpm --filter @visionflow/api typecheck` | PASS | +| `pnpm --filter @visionflow/web typecheck` | PASS | +| `pnpm test` | 314 tests PASS | +| `pnpm lint` | PASS | +| `pnpm build` | PASS | +| `curl http://localhost:3000/api/health` | HTTP 200 | +| `curl http://localhost:3000/api/health/runtime/status` | HTTP 200, correct payload | +| `curl http://localhost:8000/health` | HTTP 200 | +| Browser smoke | PASS — Playwright: "Database ready", "ONNX detector ready", "BullMQ ready", no "Mock detector mounted", no errors | --- ## Runtime Status Endpoint Sample Response **With ONNX configured and worker healthy:** + ```json { "api": { "ok": true, "mode": "database" }, "database": { "ok": true, "status": "ready" }, "queue": { "ok": true, "mode": "bullmq", "status": "ready" }, "cvWorker": { - "ok": true, "configured": true, + "ok": true, + "configured": true, "url": "http://localhost:8000", "requestedDetectorMode": "onnx", "activeDetectorMode": "onnx", "onnxAvailable": true, "modelVersion": "yolov8n-640", "modelPath": "models\\yolov8n.onnx", - "frameExtractionAvailable": null, "error": null + "frameExtractionAvailable": null, + "error": null } } ``` @@ -175,6 +189,7 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte ## What Changed in App.tsx **Before (Phase 21A, 529 lines):** + - Owned `datasetVersions`, `datasetSourceState`, `selectedDatasetVersionId` state + loading effect - Owned `job` state + SSE effect + polling effect + startJob - Owned `evaluationReport`, `isEvaluating`, `evaluationError`, `predictions` + fetch effect + handleRunEvaluation @@ -183,6 +198,7 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte - `runtimeState.health` derived client-side with `'unknown'` values **After (Phase 21B, ~144 lines):** + - Composes 3 extracted controllers - Still owns UI state: `section`, `threshold`, `annotationRows`, `mediaUploads`, `selectedMediaAssetId`, `pipeline*` state - **NOW owns `useRuntimeStatus` call** — single source of truth for runtime readiness @@ -191,6 +207,7 @@ Added `GET /api/health/runtime/status` — the single source of truth for fronte - No duplicate runtime polling — `useRuntimeStatus` called exactly once at App level **Finalization changes (2026-05-05):** + - `runtime.api.ts`: Fixed missing `/api` prefix in endpoint path (404 → 200) - `workbench-runtime.ts`: Expanded `HealthStatus` union to cover all backend states (`'fallback'`, `'unknown'`, `'mock'`) - `App.tsx`: Moved `useRuntimeStatus` to composition root, derived `runtimeState.health` from backend truth diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21C-PLAN.md b/.planning/phases/phase-21-frontend-feature-split-completion/21C-PLAN.md index d8184b00..00efc5c7 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21C-PLAN.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21C-PLAN.md @@ -20,30 +20,35 @@ Reduce the `AppRoutes` prop surface and decouple feature-local state from the ap `AppRoutes` receives **23 individual props** from `App.tsx`: -| Category | Props | -|---|---| -| Cross-cutting | `section`, `runtimeReadiness`, `setSection` | -| Inference/job | `job`, `onRun`, `inferenceEligibility`, `evaluationEligibility` | -| Annotation | `annotationRows`, `setAnnotationRows`, `selectedAnnotation`, `setSelectedAnnotation` | -| Threshold | `threshold`, `setThreshold` | -| Media | `mediaUploads`, `setMediaUploads`, `selectedMediaAssetId`, `onSelectAsset` | -| Dataset | `selectedDatasetVersionId`, `onSelectVersion`, `datasetVersions`, `onVersionsChange`, `datasetSourceState`, `onSourceStateChange` | -| Pipeline | `pipelineSelectedNodeId`, `onSelectNode`, `pipelineDefinition`, `onDefinitionChange`, `pipelineValidation`, `onValidationChange` | -| Evaluation | `evaluationReport`, `isEvaluating`, `evaluationError`, `predictions`, `onRunEvaluation` | +| Category | Props | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| Cross-cutting | `section`, `runtimeReadiness`, `setSection` | +| Inference/job | `job`, `onRun`, `inferenceEligibility`, `evaluationEligibility` | +| Annotation | `annotationRows`, `setAnnotationRows`, `selectedAnnotation`, `setSelectedAnnotation` | +| Threshold | `threshold`, `setThreshold` | +| Media | `mediaUploads`, `setMediaUploads`, `selectedMediaAssetId`, `onSelectAsset` | +| Dataset | `selectedDatasetVersionId`, `onSelectVersion`, `datasetVersions`, `onVersionsChange`, `datasetSourceState`, `onSourceStateChange` | +| Pipeline | `pipelineSelectedNodeId`, `onSelectNode`, `pipelineDefinition`, `onDefinitionChange`, `pipelineValidation`, `onValidationChange` | +| Evaluation | `evaluationReport`, `isEvaluating`, `evaluationError`, `predictions`, `onRunEvaluation` | ## Problem Analysis ### Problem 1: `threshold` prop is redundant + `threshold` is used only in `JobsPanel` and `AnnotationEnginePanel`. It does not need to live at the `App` level — it is a per-feature value. Moreover, `AnnotationEnginePanel` **already** has its own local threshold state for the annotation canvas. The `threshold`/`setThreshold` that flows through AppRoutes→JobsPanel is used only in `JobsPanel`. It should stay there. ### Problem 2: Annotation state is local to each feature + `annotationRows`, `selectedAnnotation`, `setSelectedAnnotation` are used only in the `annotate` section. `AnnotationEnginePanel` already manages its own `annotations` state via `useState`. The seed annotation summaries are computed at the App level but should be initialized inside the panel. ### Problem 3: `ShellHeader` gets fewer props than it should + `ShellHeader` already receives `job`, `inferenceEligibility`, `threshold` — but `threshold` is unused. The `onRun` callback is defined at App level but should remain there since it calls `setSection('jobs')` + `startJob()`. However, the `threshold` prop to ShellHeader is dead weight. ### Problem 4: Dataset state is duplicated + `selectedDatasetVersionId` is lifted to App level, but `DatasetPanel` already has its own internal state for version selection. The App-level `selectedDatasetVersionId` is used only for: + - Computing `runtimeState.selectedDatasetVersionId` (used in `runtime-selectors`) - Passed to `AppRoutes` → `InspectorRouter` (unused — `InspectorRouter` uses `datasetInspectorData` which is already built from `buildDatasetInspectorData`) - Passed to `DatasetPanel` as optional `externalSelectedVersionId` @@ -51,6 +56,7 @@ Reduce the `AppRoutes` prop surface and decouple feature-local state from the ap The `runtimeState.selectedDatasetVersionId` is critical — `canRunInference` does not check it, but `canRunEvaluation` is the only selector that would benefit from it. Currently neither selector uses `selectedDatasetVersionId`. The dataset version selection for inference eligibility is implicit (the "locked dataset with assets" condition). ### Problem 5: Pipeline state is local to PipelinePanel + `PipelinePanel` already manages its own `definition`, `validation`, `selectedNodeId` via internal `useState`. The external props are optional and used as initial values. The pipeline state does not need to live at App level for any cross-cutting concern. ## Refactor Strategy @@ -67,20 +73,20 @@ The `runtimeState.selectedDatasetVersionId` is critical — `canRunInference` do ### Props that stay at App level (11 remaining) -| Prop | Reason | -|---|---| -| `section` | Drives conditional panel rendering, `NavRail` needs it | -| `setSection` | Navigation action, used by JobsPanel to navigate to datasets | -| `runtimeReadiness` | Passed to `ReadinessStrip` and `ShellHeader` via AppRoutes | -| `job` | Passed to `ReadinessStrip` (job status), `JobsPanel`, `InspectorRouter` | -| `onRun` | Callback that sets section + starts job | -| `inferenceEligibility` | Passed to `ShellHeader`, `OverviewPanel`, `JobsPanel` | -| `evaluationEligibility` | Passed to `JobsPanel` | -| `mediaUploads`, `setMediaUploads` | Used in MediaPanel AND DatasetPanel (media → dataset assignment flow) | -| `selectedMediaAssetId`, `onSelectAsset` | Used in MediaPanel AND InspectorRouter (media inspector) | -| `datasetVersions`, `onVersionsChange`, `datasetSourceState`, `onSourceStateChange` | Used in DatasetPanel AND `InspectorRouter` (datasetInspectorData builder) | -| `selectedDatasetVersionId`, `onSelectVersion` | Passed to DatasetPanel (optional), used in `buildDatasetInspectorData` | -| `evaluationReport`, `isEvaluating`, `evaluationError`, `predictions`, `onRunEvaluation` | Used only in JobsPanel | +| Prop | Reason | +| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `section` | Drives conditional panel rendering, `NavRail` needs it | +| `setSection` | Navigation action, used by JobsPanel to navigate to datasets | +| `runtimeReadiness` | Passed to `ReadinessStrip` and `ShellHeader` via AppRoutes | +| `job` | Passed to `ReadinessStrip` (job status), `JobsPanel`, `InspectorRouter` | +| `onRun` | Callback that sets section + starts job | +| `inferenceEligibility` | Passed to `ShellHeader`, `OverviewPanel`, `JobsPanel` | +| `evaluationEligibility` | Passed to `JobsPanel` | +| `mediaUploads`, `setMediaUploads` | Used in MediaPanel AND DatasetPanel (media → dataset assignment flow) | +| `selectedMediaAssetId`, `onSelectAsset` | Used in MediaPanel AND InspectorRouter (media inspector) | +| `datasetVersions`, `onVersionsChange`, `datasetSourceState`, `onSourceStateChange` | Used in DatasetPanel AND `InspectorRouter` (datasetInspectorData builder) | +| `selectedDatasetVersionId`, `onSelectVersion` | Passed to DatasetPanel (optional), used in `buildDatasetInspectorData` | +| `evaluationReport`, `isEvaluating`, `evaluationError`, `predictions`, `onRunEvaluation` | Used only in JobsPanel | ### Props added back to AppRoutes (9 for JobsPanel) @@ -91,6 +97,7 @@ These are already on AppRoutes, but `threshold` needs to be passed to JobsPanel. ### Runtime truth guard (Phase 21B regression check) After refactoring, verify: + 1. `grep -n "useRuntimeStatus" apps/web/src/` — only `App.tsx` 2. `grep -n "runtimeReadiness\|runtimeStatus.readiness" apps/web/src/` — `App.tsx` passes it, `ReadinessStrip`/`ShellHeader` receive it 3. `runtime-selectors.test.ts` — all tests still pass @@ -109,14 +116,14 @@ After refactoring, verify: ### Files Changed -| File | Change | -|---|---| -| `apps/web/src/App.tsx` | Remove `threshold`/`setThreshold` state, remove annotation state, remove pipeline state, remove 19 prop pass-throughs from AppRoutes call | -| `apps/web/src/app/AppRoutes.tsx` | Remove 19 props, keep 4, add `threshold` prop for JobsPanel, update type | -| `apps/web/src/app/ShellHeader.tsx` | Remove unused `threshold` prop | -| `apps/web/src/app/JobsPanel.tsx` | Accept `threshold` as prop from AppRoutes | -| `apps/web/src/app/OverviewPanel.tsx` | Remove `pipelineValidation` prop (static text instead) | -| `apps/web/src/features/annotations/AnnotationEngine.tsx` | Initialize seed annotations internally (remove external props) | +| File | Change | +| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `apps/web/src/App.tsx` | Remove `threshold`/`setThreshold` state, remove annotation state, remove pipeline state, remove 19 prop pass-throughs from AppRoutes call | +| `apps/web/src/app/AppRoutes.tsx` | Remove 19 props, keep 4, add `threshold` prop for JobsPanel, update type | +| `apps/web/src/app/ShellHeader.tsx` | Remove unused `threshold` prop | +| `apps/web/src/app/JobsPanel.tsx` | Accept `threshold` as prop from AppRoutes | +| `apps/web/src/app/OverviewPanel.tsx` | Remove `pipelineValidation` prop (static text instead) | +| `apps/web/src/features/annotations/AnnotationEngine.tsx` | Initialize seed annotations internally (remove external props) | ### Files Unchanged (guarded) diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21C-REVIEW.md b/.planning/phases/phase-21-frontend-feature-split-completion/21C-REVIEW.md index 97eb9394..9c8be256 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21C-REVIEW.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21C-REVIEW.md @@ -8,15 +8,15 @@ ## Score Breakdown -| Dimension | Score | Notes | -|---|---|---| -| Ground truth overlay (Jobs) | 0/10 → 10/10 | Was passing `groundTruth={[]}` — fixed | -| Ground truth overlay (Timeline) | 0/10 → 10/10 | Was passing `groundTruth={[]}` — fixed | -| Overview pipeline text | 5/10 → 10/10 | Was claiming "validated and ready" with no dynamic check — fixed | -| InspectorRouter stub | N/A (21D scope) | Explicitly deferred to 21D — not a Phase 21C failure | -| Prop surface reduction | 10/10 | 23 → 17 props (26% reduction) | -| Artifact completeness | 5/10 → 10/10 | ROADMAP and MILESTONES updated; 21C-REVIEW.md now created | -| **Overall within Phase 21C scope** | **10/10** | Prop-surface cleanup complete, behavior regressions fixed, InspectorRouter state sync explicitly moved to 21D scope | +| Dimension | Score | Notes | +| ---------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------- | +| Ground truth overlay (Jobs) | 0/10 → 10/10 | Was passing `groundTruth={[]}` — fixed | +| Ground truth overlay (Timeline) | 0/10 → 10/10 | Was passing `groundTruth={[]}` — fixed | +| Overview pipeline text | 5/10 → 10/10 | Was claiming "validated and ready" with no dynamic check — fixed | +| InspectorRouter stub | N/A (21D scope) | Explicitly deferred to 21D — not a Phase 21C failure | +| Prop surface reduction | 10/10 | 23 → 17 props (26% reduction) | +| Artifact completeness | 5/10 → 10/10 | ROADMAP and MILESTONES updated; 21C-REVIEW.md now created | +| **Overall within Phase 21C scope** | **10/10** | Prop-surface cleanup complete, behavior regressions fixed, InspectorRouter state sync explicitly moved to 21D scope | --- @@ -49,7 +49,7 @@ const seededGroundTruth = useMemo(() => createSeedAnnotationSummaries(), []); And passes it to both `JobsPanel` and `TimelineReplayPanel`: ```tsx -groundTruth={seededGroundTruth} +groundTruth = { seededGroundTruth }; ``` `createSeedAnnotationSummaries()` is the same function used by `AnnotationEnginePanel` to initialize its local state — this ensures consistency. @@ -115,15 +115,14 @@ The AnnotationInspector and PipelineInspector cannot interact with real panel st ## Artifact Gaps (Fixed in This Commit) -| Gap | Status | -|---|---| +| Gap | Status | +| -------------------------------------------------------- | ---------------------------------------------------- | | `ROADMAP.md` Phase 21C commit listed as `pending commit` | Fixed — now references `d667962e` and the fix commit | -| `MILESTONES.md` Phase 21C not in completion list | Fixed — Phase 21 now marked ✅ Done | -| `21C-REVIEW.md` missing | Created by this commit | +| `MILESTONES.md` Phase 21C not in completion list | Fixed — Phase 21 now marked ✅ Done | +| `21C-REVIEW.md` missing | Created by this commit | --- - ## Phase Boundary Decision InspectorRouter annotation/pipeline state sync is **not** part of Phase 21C closeout because fixing it correctly requires choosing a state ownership model: @@ -135,16 +134,16 @@ Therefore Phase 21C is **closed as complete** for AppRoutes prop-surface reducti ## Verification Checklist -| Check | Status | -|---|---| -| `pnpm --filter @visionflow/web typecheck` | Expected PASS | -| `pnpm --filter @visionflow/web test` | Expected PASS (65 tests) | -| `pnpm --filter @visionflow/web lint` | Expected PASS | -| `pnpm --filter @visionflow/web build` | Expected PASS | -| Jobs overlay shows GT boxes (browser smoke) | Required | -| Timeline overlay shows GT boxes | Required | -| Overview pipeline text is neutral | Verified | -| InspectorRouter stub documented as 21D limitation | Verified | +| Check | Status | +| ------------------------------------------------- | ------------------------ | +| `pnpm --filter @visionflow/web typecheck` | Expected PASS | +| `pnpm --filter @visionflow/web test` | Expected PASS (65 tests) | +| `pnpm --filter @visionflow/web lint` | Expected PASS | +| `pnpm --filter @visionflow/web build` | Expected PASS | +| Jobs overlay shows GT boxes (browser smoke) | Required | +| Timeline overlay shows GT boxes | Required | +| Overview pipeline text is neutral | Verified | +| InspectorRouter stub documented as 21D limitation | Verified | --- diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21C-SUMMARY.md b/.planning/phases/phase-21-frontend-feature-split-completion/21C-SUMMARY.md index 83b58ea4..b6bce5a4 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21C-SUMMARY.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21C-SUMMARY.md @@ -13,19 +13,20 @@ **Props removed from AppRoutes:** -| Prop(s) | Reason | -|---|---| -| `threshold`, `setThreshold` | Feature-local state — owned by `JobsPanel` and `AnnotationEnginePanel` independently | -| `annotationRows`, `setAnnotationRows`, `selectedAnnotation`, `setSelectedAnnotation` | Feature-local state — owned by `AnnotationEnginePanel` internally | +| Prop(s) | Reason | +| -------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `threshold`, `setThreshold` | Feature-local state — owned by `JobsPanel` and `AnnotationEnginePanel` independently | +| `annotationRows`, `setAnnotationRows`, `selectedAnnotation`, `setSelectedAnnotation` | Feature-local state — owned by `AnnotationEnginePanel` internally | | `pipelineSelectedNodeId`, `onSelectNode`, `pipelineDefinition`, `onDefinitionChange`, `pipelineValidation`, `onValidationChange` | Feature-local state — owned by `PipelinePanel` internally (already had optional external props) | -**Props retained (17):** `section`, `job`, `onRun`, `inferenceEligibility`, `evaluationEligibility`, `mediaUploads`, `setMediaUploads`, `selectedMediaAssetId`, `onSelectAsset`, `selectedDatasetVersionId`, `onSelectVersion`, `datasetVersions`, `onVersionsChange`, `datasetSourceState`, `onSourceStateChange`, `evaluationReport`*, `isEvaluating`*, `evaluationError`*, `predictions`*, `onRunEvaluation`*, `setSection`, `runtimeReadiness` +**Props retained (17):** `section`, `job`, `onRun`, `inferenceEligibility`, `evaluationEligibility`, `mediaUploads`, `setMediaUploads`, `selectedMediaAssetId`, `onSelectAsset`, `selectedDatasetVersionId`, `onSelectVersion`, `datasetVersions`, `onVersionsChange`, `datasetSourceState`, `onSourceStateChange`, `evaluationReport`_, `isEvaluating`_, `evaluationError`_, `predictions`_, `onRunEvaluation`\*, `setSection`, `runtimeReadiness` -*Evaluation props are co-located because JobsPanel needs them and they derive from `useEvaluationController`. +\*Evaluation props are co-located because JobsPanel needs them and they derive from `useEvaluationController`. ### 21C.2 — App.tsx Composition Root Cleanup **Removed from App.tsx:** + - `threshold` / `setThreshold` state (2 state declarations + 2 prop passings) - `selectedAnnotation` / `setSelectedAnnotation` state - `annotationRows` / `setAnnotationSummaries` state @@ -48,6 +49,7 @@ Slight increase over 21B (144 → 159) because `MediaUploadRow` type import was **JobsPanel:** Now owns `threshold` state locally (initialized `useState(62)`). No longer receives `threshold` as a prop. Display text in PredictionOverlayCanvas still uses the local `threshold` value. **AnnotationEnginePanel:** Now owns all annotation state internally: + - `annotations` — initialized from `createSeedAnnotationSummaries()` - `selectedAnnotationId` — initialized to `'ann_02'` - `threshold` — initialized to `62` @@ -60,6 +62,7 @@ Slight increase over 21B (144 → 159) because `MediaUploadRow` type import was ### 21C.4 — InspectorRouter Stub State `InspectorRouter` still requires `annotations`, `selectedAnnotation`, `setSelectedAnnotation`, `threshold`, `setThreshold`, `pipelineSelectedNodeId`, `pipelineDefinition`, `pipelineValidation` for the contextual inspector panels (AnnotationInspector, PipelineInspector). These are provided as stubs: + - `annotations={[]}` - `selectedAnnotation=""` - `setSelectedAnnotation={() => {}}` @@ -75,43 +78,43 @@ This is a known limitation — inspector panels cannot interact with annotation/ ## Files Changed -| File | Change | -|---|---| -| `apps/web/src/App.tsx` | Removed 4 state groups, reduced AppRoutes call from 21 to 17 props | -| `apps/web/src/app/AppRoutes.tsx` | Interface reduced from 23 to 17 props; removed prop passings to OverviewPanel, AnnotationEnginePanel, PipelinePanel | -| `apps/web/src/app/ShellHeader.tsx` | Removed `threshold` prop and header display | -| `apps/web/src/app/JobsPanel.tsx` | Owns `threshold` locally via `useState(62)` | -| `apps/web/src/app/OverviewPanel.tsx` | Removed `pipelineValidation` prop; static pipeline status text | -| `apps/web/src/features/annotations/AnnotationEngine.tsx` | Reduced external props from 7 to 1 (`mediaRows`); owns all annotation/threshold state internally | +| File | Change | +| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| `apps/web/src/App.tsx` | Removed 4 state groups, reduced AppRoutes call from 21 to 17 props | +| `apps/web/src/app/AppRoutes.tsx` | Interface reduced from 23 to 17 props; removed prop passings to OverviewPanel, AnnotationEnginePanel, PipelinePanel | +| `apps/web/src/app/ShellHeader.tsx` | Removed `threshold` prop and header display | +| `apps/web/src/app/JobsPanel.tsx` | Owns `threshold` locally via `useState(62)` | +| `apps/web/src/app/OverviewPanel.tsx` | Removed `pipelineValidation` prop; static pipeline status text | +| `apps/web/src/features/annotations/AnnotationEngine.tsx` | Reduced external props from 7 to 1 (`mediaRows`); owns all annotation/threshold state internally | --- ## Runtime Truth Regression Checklist -| Check | Result | -|---|---| -| `useRuntimeStatus` called only in `App.tsx` | PASS | -| `runtimeReadiness` passed as prop from App → AppRoutes → ReadinessStrip | PASS | -| `runtimeState.health` derives from backend truth | PASS (unchanged from 21B) | -| `runtime-selectors.test.ts` — all 34 regression tests pass | PASS | -| `ReadinessStrip` receives readiness as prop, not fetching independently | PASS | -| No "Mock detector mounted" hard-coded label | PASS (eliminated in 21B) | -| No fake readiness when endpoint fails | PASS (unchanged from 21B) | +| Check | Result | +| ----------------------------------------------------------------------- | ------------------------- | +| `useRuntimeStatus` called only in `App.tsx` | PASS | +| `runtimeReadiness` passed as prop from App → AppRoutes → ReadinessStrip | PASS | +| `runtimeState.health` derives from backend truth | PASS (unchanged from 21B) | +| `runtime-selectors.test.ts` — all 34 regression tests pass | PASS | +| `ReadinessStrip` receives readiness as prop, not fetching independently | PASS | +| No "Mock detector mounted" hard-coded label | PASS (eliminated in 21B) | +| No fake readiness when endpoint fails | PASS (unchanged from 21B) | --- ## Verification Results -| Check | Result | -|---|---| -| `pnpm --filter @visionflow/web typecheck` | PASS | -| `pnpm --filter @visionflow/web test` | PASS — 65 tests (4 files) | -| `pnpm --filter @visionflow/web lint` | PASS | -| `pnpm --filter @visionflow/web build` | PASS — production build successful | -| `pnpm typecheck` (root) | PASS — all 6 packages | -| Runtime truth grep — `useRuntimeStatus` only in App.tsx | PASS | -| Runtime truth grep — `runtimeReadiness` flow confirmed | PASS | -| runtime-selectors regression tests | PASS — 34/34 | +| Check | Result | +| ------------------------------------------------------- | ---------------------------------- | +| `pnpm --filter @visionflow/web typecheck` | PASS | +| `pnpm --filter @visionflow/web test` | PASS — 65 tests (4 files) | +| `pnpm --filter @visionflow/web lint` | PASS | +| `pnpm --filter @visionflow/web build` | PASS — production build successful | +| `pnpm typecheck` (root) | PASS — all 6 packages | +| Runtime truth grep — `useRuntimeStatus` only in App.tsx | PASS | +| Runtime truth grep — `runtimeReadiness` flow confirmed | PASS | +| runtime-selectors regression tests | PASS — 34/34 | --- diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21D-PLAN.md b/.planning/phases/phase-21-frontend-feature-split-completion/21D-PLAN.md index baa20db9..900aa451 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21D-PLAN.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21D-PLAN.md @@ -53,6 +53,7 @@ pipelineValidation={validatePipelineDefinition(demoSnapshot.pipeline)} For `annotate` and `pipeline` sections, the global `InspectorRouter` will render a non-interactive notice stating that the inspector is embedded in the workspace. For `media`, `datasets`, `jobs`, it continues rendering real data. This is preferred because: + - `PipelinePanel` and `AnnotationEnginePanel` already own their inspector state locally - The global right rail inspector for those sections was always fake/secondary - Option A1 preserves the prop-surface gains from Phase 21C (no lifting state back to App root) @@ -61,6 +62,7 @@ This is preferred because: ## Scope ### In Scope + - Refactor `InspectorRouterProps` to remove: `annotations`, `selectedAnnotation`, `setSelectedAnnotation`, `threshold`, `setThreshold`, `pipelineSelectedNodeId`, `pipelineDefinition`, `pipelineValidation` - Update `InspectorRouter` to render honest embedded-notice panels for `annotate` and `pipeline` - Update `AppRoutes.tsx` to remove fake prop passings and unused imports (`validatePipelineDefinition`, `PipelineValidationResult`, `demoSnapshot.pipeline`) @@ -73,6 +75,7 @@ This is preferred because: - Preserve `runtimeReadiness` flow ### Out of Scope + - No backend changes - No Prisma/schema changes - No new product feature @@ -125,20 +128,25 @@ type InspectorRouterProps = { ### Step 2 — Update InspectorRouter For `active === 'annotate'`: + - Render `InspectorShell` with honest text: "Annotation inspector is embedded in the workspace panel." For `active === 'pipeline'`: + - Render `InspectorShell` with honest text: "Pipeline node inspector is embedded in the Pipeline workspace." For `active === 'overview'`, `active === 'timeline'`, `active === 'diff'`: + - Keep existing fallback (project name + job status) For `active === 'media'`, `active === 'datasets'`, `active === 'jobs'`: + - Keep existing real inspector rendering (unchanged) ### Step 3 — Update AppRoutes.tsx Remove all fake prop passings to `InspectorRouter`: + - Remove `annotations={[]}` - Remove `selectedAnnotation=""` - Remove `setSelectedAnnotation={() => {}}` @@ -149,6 +157,7 @@ Remove all fake prop passings to `InspectorRouter`: - Remove `pipelineValidation={...}` Remove unused imports: + - `validatePipelineDefinition` from `@visionflow/contracts` - `PipelineValidationResult` from `@visionflow/contracts` - `AnnotationSummary`, `PipelineDefinition`, `PipelineNode` (if only used for fake props) @@ -169,6 +178,7 @@ Remove `AnnotationInspectorData` and `PipelineInspectorData` from `inspector.typ ### Step 6 — Audit imports Grep for the removed patterns in AppRoutes to confirm they're gone: + - `annotations={[]}` - `setSelectedAnnotation` - `setThreshold` @@ -178,17 +188,20 @@ Grep for the removed patterns in AppRoutes to confirm they're gone: ### Step 7 — Verify PipelinePanel self-containment Confirm `PipelinePanel`: + - Renders `PipelineInspector` internally (confirmed: line ~346-361) - Does not depend on `InspectorRouter` for pipeline inspector state - Uses its own local `definition`, `validation`, `selectedNodeId` Confirm `AnnotationEnginePanel`: + - Owns annotation state internally (confirmed from Phase 21C) - Does not depend on `InspectorRouter` for annotation state ### Step 8 — Circular dependency audit Check imports: + - `app/` imports from `features/inspector/` — `InspectorRouter` only (AppRoutes.tsx) - `features/inspector/` imports from `@visionflow/contracts` — no app/ or feature-local imports - `features/inspector/` does NOT import from `app/` @@ -207,12 +220,12 @@ Check imports: ### Files Changed -| File | Change | -|---|---| -| `apps/web/src/features/inspector/InspectorRouter.tsx` | Remove 8 fake props; render honest embedded-notice for annotate/pipeline | -| `apps/web/src/app/AppRoutes.tsx` | Remove fake prop passings; remove unused imports | -| `apps/web/src/features/inspector/index.ts` | Update `InspectorRouterProps` type export (if shape changed) | -| `apps/web/src/features/inspector/inspector.types.ts` | Remove `AnnotationInspectorData` and `PipelineInspectorData` (if unreferenced) | +| File | Change | +| ----------------------------------------------------- | ------------------------------------------------------------------------------ | +| `apps/web/src/features/inspector/InspectorRouter.tsx` | Remove 8 fake props; render honest embedded-notice for annotate/pipeline | +| `apps/web/src/app/AppRoutes.tsx` | Remove fake prop passings; remove unused imports | +| `apps/web/src/features/inspector/index.ts` | Update `InspectorRouterProps` type export (if shape changed) | +| `apps/web/src/features/inspector/inspector.types.ts` | Remove `AnnotationInspectorData` and `PipelineInspectorData` (if unreferenced) | ### Files Unchanged (guarded) diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21D-REVIEW.md b/.planning/phases/phase-21-frontend-feature-split-completion/21D-REVIEW.md index 4534f6b5..65ad33c0 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21D-REVIEW.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21D-REVIEW.md @@ -8,16 +8,16 @@ ## Score Breakdown -| Dimension | Score | Notes | -|---|---|---| -| Fake state removal | 10/10 | 8 fake props eliminated from InspectorRouter | -| Honest embedded-notice | 10/10 | Honest "Embedded" notice for annotate/pipeline | -| No prop-surface regression | 10/10 | AppRoutes prop surface unchanged (no lifting) | -| Dead type cleanup | 10/10 | 4 unused types removed from inspector.types.ts | -| Phase 21B runtime truth | 10/10 | useRuntimeStatus single-call preserved | -| Phase 21C preservation | 10/10 | seededGroundTruth, neutral pipeline text preserved | -| Artifact completeness | 10/10 | All planning artifacts updated | -| **Overall** | **10/10** | Clean closeout | +| Dimension | Score | Notes | +| -------------------------- | --------- | -------------------------------------------------- | +| Fake state removal | 10/10 | 8 fake props eliminated from InspectorRouter | +| Honest embedded-notice | 10/10 | Honest "Embedded" notice for annotate/pipeline | +| No prop-surface regression | 10/10 | AppRoutes prop surface unchanged (no lifting) | +| Dead type cleanup | 10/10 | 4 unused types removed from inspector.types.ts | +| Phase 21B runtime truth | 10/10 | useRuntimeStatus single-call preserved | +| Phase 21C preservation | 10/10 | seededGroundTruth, neutral pipeline text preserved | +| Artifact completeness | 10/10 | All planning artifacts updated | +| **Overall** | **10/10** | Clean closeout | --- @@ -48,6 +48,7 @@ **Option A1 chosen** — Honest embedded-notice panels for annotate/pipeline sections in InspectorRouter. Option B (extracting feature route containers) was rejected because: + - Would require creating new route container files - Would require lifting annotation/pipeline state to App root — undoing Phase 21C prop-surface reduction - PipelinePanel already renders PipelineInspector internally — a second inspector was always redundant @@ -57,11 +58,11 @@ Option B (extracting feature route containers) was rejected because: ## Risks -| Risk | Severity | Mitigation | -|---|---|---| -| Users confused by dual inspector rendering for pipeline | Low | PipelinePanel inspector is prominent; global rail is secondary notice | -| Users think embedded-notice means the inspector is broken | Low | "Embedded" label with clear description text | -| AnnotationInspector/PipelineInspector components become orphaned | Low | They are used inside PipelinePanel and AnnotationEnginePanel directly | +| Risk | Severity | Mitigation | +| ---------------------------------------------------------------- | -------- | --------------------------------------------------------------------- | +| Users confused by dual inspector rendering for pipeline | Low | PipelinePanel inspector is prominent; global rail is secondary notice | +| Users think embedded-notice means the inspector is broken | Low | "Embedded" label with clear description text | +| AnnotationInspector/PipelineInspector components become orphaned | Low | They are used inside PipelinePanel and AnnotationEnginePanel directly | --- @@ -69,19 +70,19 @@ Option B (extracting feature route containers) was rejected because: All checks passed: -| Command | Result | -|---|---| -| `pnpm --filter @visionflow/web typecheck` | PASS | -| `pnpm --filter @visionflow/web test` | PASS — 65 tests | -| `pnpm --filter @visionflow/web lint` | PASS | -| `pnpm --filter @visionflow/web build` | PASS | -| `grep "annotations={}"` | 0 results | -| `grep "setSelectedAnnotation=()"` | 0 results | -| `grep "setThreshold=()"` | 0 results | -| `grep "pipelineDefinition={demoSnapshot"` | 0 results | -| `grep "pipelineValidation={validatePipelineDefinition"` | 0 results | -| `grep "useRuntimeStatus" (only App.tsx)` | PASS | -| Playwright nav smoke (10 checks) | **PASS** — all 8 sections navigate without errors, no console errors | +| Command | Result | +| ------------------------------------------------------- | -------------------------------------------------------------------- | +| `pnpm --filter @visionflow/web typecheck` | PASS | +| `pnpm --filter @visionflow/web test` | PASS — 65 tests | +| `pnpm --filter @visionflow/web lint` | PASS | +| `pnpm --filter @visionflow/web build` | PASS | +| `grep "annotations={}"` | 0 results | +| `grep "setSelectedAnnotation=()"` | 0 results | +| `grep "setThreshold=()"` | 0 results | +| `grep "pipelineDefinition={demoSnapshot"` | 0 results | +| `grep "pipelineValidation={validatePipelineDefinition"` | 0 results | +| `grep "useRuntimeStatus" (only App.tsx)` | PASS | +| Playwright nav smoke (10 checks) | **PASS** — all 8 sections navigate without errors, no console errors | --- diff --git a/.planning/phases/phase-21-frontend-feature-split-completion/21D-SUMMARY.md b/.planning/phases/phase-21-frontend-feature-split-completion/21D-SUMMARY.md index 55a0ae72..cbc24162 100644 --- a/.planning/phases/phase-21-frontend-feature-split-completion/21D-SUMMARY.md +++ b/.planning/phases/phase-21-frontend-feature-split-completion/21D-SUMMARY.md @@ -14,6 +14,7 @@ Removed 8 fake/stub props from `InspectorRouter` and replaced their rendering with honest embedded-notice panels. **Props removed:** + - `annotations: AnnotationSummary[]` (was `[]`) - `selectedAnnotation: string` (was `""`) - `setSelectedAnnotation: (id: string) => void` (was `() => {}`) @@ -24,6 +25,7 @@ Removed 8 fake/stub props from `InspectorRouter` and replaced their rendering wi - `pipelineValidation: PipelineValidationResult` (was `validatePipelineDefinition(demoSnapshot.pipeline)`) **New `InspectorRouterProps`:** + ```typescript type InspectorRouterProps = { active: SectionId; @@ -38,6 +40,7 @@ type InspectorRouterProps = { ### 21D.2 — Honest Embedded-Notice Rendering For `active === 'annotate'`: + ```tsx = 3 predictions | -| 8 | `GET /api/.../evaluation` | `report.inputHash === FIXTURE_IDS.evaluation.inputHash` | +| # | Endpoint | Check | +| --- | ------------------------------------------------------------ | -------------------------------------------------------------------------------- | +| 1 | `GET /api/health` | `ok: true`, `service: 'visionflow-api'` | +| 2 | `GET /api/health/runtime/status` | `api.ok: true`, `database.status: 'ready'` | +| 3 | `GET /api/projects/:projectId/datasets` | Canonical dataset present | +| 4 | `GET /api/.../annotation-workspace?assetId=asset_frame_1482` | MANUAL annotations present | +| 5 | `GET /api/.../export/coco` | LOCKED status, deterministic hash, COCO schema valid, hash stable across 2 calls | +| 6 | `GET /api/.../inference-jobs` | Canonical job visible | +| 7 | `GET /api/.../predictions` | >= 3 predictions | +| 8 | `GET /api/.../evaluation` | `report.inputHash === FIXTURE_IDS.evaluation.inputHash` | **Key design decisions:** + - Uses `FIXTURE_IDS` from `scripts/fixtures/visionflow-fixtures.ts` — no hard-coded IDs outside the fixture contract - `--strict` mode: exit 1 if API unreachable or any check fails - Non-strict mode: skip with clear instructions if API not running @@ -73,17 +74,21 @@ Navigation labels duplicated from `FIXTURE_IDS` — relative path from `apps/web ## Architecture Decisions ### API harness: HTTP over Prisma + Phase 22A verifies DB integrity via Prisma. Phase 22B verifies API surface integrity via HTTP. This is the correct boundary — the harness exercises the full NestJS request pipeline including routing, guards, services, contracts, and Prisma queries. ### Meta-harness: split DB vs API concerns + Phase 22A meta-harness always requires DATABASE_URL (DB harnesses). Phase 22B meta-harness requires DATABASE_URL for Phase 22A meta-harness, but the API harness is conditional on reachability. This makes CI safe (DB-only) while enabling full verification locally (with live stack). ### Strict mode skip vs fail + - API harness non-strict: skip with instructions if API unreachable - API harness strict: fail if API unreachable - Meta-harness strict: always runs DB checks; API checks gated by `--with-api` ### No binary fixtures, no Docker test stack + No Phase 22B harness or test requires a binary fixture file. All checks use seeded DB state or HTTP responses. Docker test stack is not needed because GitHub Actions PostgreSQL service is sufficient for Phase 22B CI needs. ## Live Verification (2026-05-05) @@ -91,12 +96,14 @@ No Phase 22B harness or test requires a binary fixture file. All checks use seed All tests run against live stack: Docker (PostgreSQL + Redis + MinIO), NestJS API (port 3000), Vite web (port 5173), seeded DB. ### Pre-flight + ``` pnpm seed:db -- --reset → PASS (seed complete) pnpm harness:phase22a → PASS (18/18 DB checks) ``` ### API Production-Path (strict mode) + ``` npx tsx scripts/harness/phase22b-production-path-api-check.ts --strict → 8/8 PASS @@ -111,6 +118,7 @@ npx tsx scripts/harness/phase22b-production-path-api-check.ts --strict ``` ### Meta Harness (--strict --with-api) + ``` npx tsx scripts/harness/phase22b-meta-harness.ts --strict --with-api → 2/2 PASS (13 total sub-checks) @@ -119,6 +127,7 @@ npx tsx scripts/harness/phase22b-meta-harness.ts --strict --with-api ``` ### Playwright Production-Path Smoke + ``` npx playwright test apps/web/e2e/production-path.spec.ts → 11/11 PASS (4.2s) @@ -136,6 +145,7 @@ npx playwright test apps/web/e2e/production-path.spec.ts ``` ### Bugs Found and Fixed During Live Verification + 1. **API harness 404**: `VITE_API_BASE_URL` in `.env` was `http://localhost:3000` (missing `/api` suffix), causing the harness to call `http://localhost:3000/health` instead of `http://localhost:3000/api/health`. Fixed to `http://localhost:3000/api`. 2. **AbortSignal.timeout hanging on Windows**: Node's `AbortSignal.timeout(10000)` caused fetch to hang indefinitely in the PowerShell/tsx environment. Fixed with `setTimeout`-based `AbortController`. 3. **CORS origin mismatch**: `WEB_ORIGIN=http://localhost:5173` did not include port 5175 (when web auto-assigned). Updated to `http://localhost:5173,http://localhost:5174,http://localhost:5175`. @@ -144,32 +154,32 @@ npx playwright test apps/web/e2e/production-path.spec.ts ## Verification -| Check | Command | Result | -|-------|---------|--------| -| typecheck | `pnpm typecheck` | PASS (4 packages) | -| test | `pnpm test` | PASS (338 tests: 208 API + 43 contracts + 22 motion + 65 web) | -| build | `pnpm build` | PASS (4 packages) | -| lint | `pnpm lint` | PASS | -| API harness (no stack) | `pnpm harness:phase22b:api` | SKIP (API not running — expected in CI) | -| API harness strict | `npx tsx scripts/harness/phase22b-production-path-api-check.ts --strict` | **PASS 8/8** (live) | -| Meta harness --with-api | `npx tsx scripts/harness/phase22b-meta-harness.ts --strict --with-api` | **PASS 13/13** (live) | -| Playwright smoke | `npx playwright test apps/web/e2e/production-path.spec.ts` | **PASS 11/11** (live) | +| Check | Command | Result | +| ----------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------- | +| typecheck | `pnpm typecheck` | PASS (4 packages) | +| test | `pnpm test` | PASS (338 tests: 208 API + 43 contracts + 22 motion + 65 web) | +| build | `pnpm build` | PASS (4 packages) | +| lint | `pnpm lint` | PASS | +| API harness (no stack) | `pnpm harness:phase22b:api` | SKIP (API not running — expected in CI) | +| API harness strict | `npx tsx scripts/harness/phase22b-production-path-api-check.ts --strict` | **PASS 8/8** (live) | +| Meta harness --with-api | `npx tsx scripts/harness/phase22b-meta-harness.ts --strict --with-api` | **PASS 13/13** (live) | +| Playwright smoke | `npx playwright test apps/web/e2e/production-path.spec.ts` | **PASS 11/11** (live) | ## Files Changed -| File | Change | -|------|--------| -| `scripts/harness/phase22b-production-path-api-check.ts` | New — 8-point API harness | -| `scripts/harness/phase22b-meta-harness.ts` | New — meta-harness aggregator | -| `apps/web/e2e/production-path.spec.ts` | New — 11 Playwright smoke tests | -| `package.json` | Added `harness:phase22b:api`, `meta:harness:phase22b` | -| `.github/workflows/ci.yml` | Added meta:harness:phase22b to db-harness + migration-chain | -| `.env` | Fixed `VITE_API_BASE_URL` to include `/api` suffix; extended `WEB_ORIGIN` for ports 5173-5175 | -| `apps/web/src/lib/annotations.ts` | Fixed default from `http://127.0.0.1:3000` to `http://localhost:3000` | -| `apps/web/playwright.config.ts` | Fixed `baseURL` to use `VITE_WEB_BASE_URL` instead of `VITE_API_BASE_URL` | -| `.planning/phases/phase-22b-production-path-test-suite/22B-PLAN.md` | New — phase plan | -| `.planning/phases/phase-22b-production-path-test-suite/22B-SUMMARY.md` | New — this file | -| `.planning/phases/phase-22b-production-path-test-suite/22B-REVIEW.md` | New — review | +| File | Change | +| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `scripts/harness/phase22b-production-path-api-check.ts` | New — 8-point API harness | +| `scripts/harness/phase22b-meta-harness.ts` | New — meta-harness aggregator | +| `apps/web/e2e/production-path.spec.ts` | New — 11 Playwright smoke tests | +| `package.json` | Added `harness:phase22b:api`, `meta:harness:phase22b` | +| `.github/workflows/ci.yml` | Added meta:harness:phase22b to db-harness + migration-chain | +| `.env` | Fixed `VITE_API_BASE_URL` to include `/api` suffix; extended `WEB_ORIGIN` for ports 5173-5175 | +| `apps/web/src/lib/annotations.ts` | Fixed default from `http://127.0.0.1:3000` to `http://localhost:3000` | +| `apps/web/playwright.config.ts` | Fixed `baseURL` to use `VITE_WEB_BASE_URL` instead of `VITE_API_BASE_URL` | +| `.planning/phases/phase-22b-production-path-test-suite/22B-PLAN.md` | New — phase plan | +| `.planning/phases/phase-22b-production-path-test-suite/22B-SUMMARY.md` | New — this file | +| `.planning/phases/phase-22b-production-path-test-suite/22B-REVIEW.md` | New — review | ## Known Limitations diff --git a/.planning/phases/phase-23-full-e2e-demo/23-PLAN.md b/.planning/phases/phase-23-full-e2e-demo/23-PLAN.md index 39d4da1f..fb7c8f61 100644 --- a/.planning/phases/phase-23-full-e2e-demo/23-PLAN.md +++ b/.planning/phases/phase-23-full-e2e-demo/23-PLAN.md @@ -15,6 +15,7 @@ Deliver the final portfolio-grade proof: a full vertical-slice Playwright E2E te Phase 22B already proved 8/8 live API checks pass against seeded fixtures. Phase 23 adds the browser UI layer on top of that verified foundation. **Rationale:** + - Full UI mutation flow (upload → thumbnail → dataset → annotation → lock → COCO → inference → eval → overlay) requires: (a) a deterministic binary fixture uploaded via the web UI, (b) no race conditions on async job completion, (c) stable timing for SSE progress. These are integration-level concerns, not E2E-proof concerns. - The Phase 22B API harness proves the entire production path is live and correct. - The Phase 22B Playwright smoke proves all 8 navigation sections load without console errors. @@ -35,20 +36,20 @@ Phase 22B produced 11 Playwright smoke tests covering navigation + load states. Extends Phase 22B smoke with fixture-aware assertions: -| # | Test | Assertion | -|---|------|-----------| -| 1 | App loads without console errors | errors.length === 0 | -| 2 | ReadinessStrip shows real backend state | text includes "Database" or "ready" | -| 3 | Media section loads | visible, no errors | -| 4 | Versions section shows canonical LOCKED dataset | version row with "LOCKED" status | -| 5 | Annotate section shows annotation workspace | canvas or annotation panel visible | -| 6 | Pipeline section loads | pipeline builder visible | -| 7 | Jobs section shows SUCCEEDED job | job row with status "SUCCEEDED" | -| 8 | Jobs section shows canonical prediction count | >= 3 prediction indicators | -| 9 | Evaluation metrics visible in Jobs panel | metric values (numbers) visible | -| 10 | Replay section loads without errors | timeline or replay panel visible | -| 11 | Diff section loads without errors | diff panel visible | -| 12 | No console errors on any section | errors.length === 0 | +| # | Test | Assertion | +| --- | ----------------------------------------------- | ----------------------------------- | +| 1 | App loads without console errors | errors.length === 0 | +| 2 | ReadinessStrip shows real backend state | text includes "Database" or "ready" | +| 3 | Media section loads | visible, no errors | +| 4 | Versions section shows canonical LOCKED dataset | version row with "LOCKED" status | +| 5 | Annotate section shows annotation workspace | canvas or annotation panel visible | +| 6 | Pipeline section loads | pipeline builder visible | +| 7 | Jobs section shows SUCCEEDED job | job row with status "SUCCEEDED" | +| 8 | Jobs section shows canonical prediction count | >= 3 prediction indicators | +| 9 | Evaluation metrics visible in Jobs panel | metric values (numbers) visible | +| 10 | Replay section loads without errors | timeline or replay panel visible | +| 11 | Diff section loads without errors | diff panel visible | +| 12 | No console errors on any section | errors.length === 0 | **Navigation labels:** duplicated from `FIXTURE_IDS` inline (same limitation as Phase 22B — relative path from `apps/web/e2e/` to `scripts/` not available). @@ -70,6 +71,7 @@ pnpm --filter @visionflow/web test:e2e -- e2e/full-vertical-slice.spec.ts --proj **Requires:** Full stack running (API on 3000, web on 5173). Fails loudly with clear boot instructions if unreachable. **package.json script:** + ```json "meta:harness:phase23": "pnpm exec tsx scripts/harness/phase23-full-e2e-check.ts --strict" ``` @@ -77,12 +79,14 @@ pnpm --filter @visionflow/web test:e2e -- e2e/full-vertical-slice.spec.ts --proj ### C. Demo Documentation **Files:** + - `docs/demo/README-DEMO.md` — updated with exact boot/seed/verification commands - `docs/demo/DEMO-CHECKLIST.md` — new: manual demo walkthrough checklist ### D. README Final Cleanup Remove stale status language: + - Phase 22B: "Planned" → "Done" (was already marked done in STATE/MILESTONES, need to verify README) - Phase 23: "Planned" → "Done" - Verify commands are accurate @@ -100,27 +104,32 @@ Remove stale status language: ## Success Criteria ### E2E (Playwright) + 1. `full-vertical-slice.spec.ts` exists and runs against live stack. 2. All 12 tests pass. 3. No console errors on any section. 4. `playwright.config.ts` baseURL fallback fixed to static string. ### Harness + 5. `phase23-full-e2e-check.ts` exists and composes Phase 22A + 22B + Playwright. 6. `pnpm meta:harness:phase23` fails loudly if stack is not running. 7. `pnpm meta:harness:phase23` passes when stack is running. ### Demo + 8. `docs/demo/README-DEMO.md` has exact boot + verification commands. 9. `docs/demo/DEMO-CHECKLIST.md` has manual demo walkthrough. 10. README demo section points to actual artifact or exact instructions. ### README + 11. No "Phase 23 Planned" language remains. 12. No stale "Phase 22B Planned" language. 13. v1.1 milestone status reflects Phase 23 completion. ### Regression + 14. Phase 22A harness still passes. 15. Phase 22B harness still passes. 16. `pnpm typecheck` passes. diff --git a/.planning/phases/phase-23-full-e2e-demo/23-REVIEW.md b/.planning/phases/phase-23-full-e2e-demo/23-REVIEW.md index d7d1ce2a..8a3f662c 100644 --- a/.planning/phases/phase-23-full-e2e-demo/23-REVIEW.md +++ b/.planning/phases/phase-23-full-e2e-demo/23-REVIEW.md @@ -9,6 +9,7 @@ ## Scope of Review Files changed during Phase 23: + - `apps/web/e2e/full-vertical-slice.spec.ts` (new) - `scripts/harness/phase23-full-e2e-check.ts` (new) - `docs/demo/DEMO-CHECKLIST.md` (new) @@ -61,6 +62,7 @@ Files changed during Phase 23: **Finding (original):** Tests used `lockedVisible` and `succeededVisible` as variables but never asserted them, meaning tests could pass without the canonical LOCKED/SUCCEEDED text being visible. **Fix applied in patch:** Replaced unused variables with direct `expect().toBeVisible()` assertions: + - `await expect(page.getByText('LOCKED', { exact: false }).first()).toBeVisible()` - `await expect(page.getByText('SUCCEEDED', { exact: false }).first()).toBeVisible()` - Added assertions for evaluation metric labels: Precision, Recall, F1, Mean IoU, TP, Prediction overlay @@ -94,6 +96,7 @@ None. No security-sensitive changes in this phase. ## Regression Assessment **No regression introduced.** The phase: + - Does not modify any business logic - Does not change any API routes - Does not alter any database schema diff --git a/.planning/phases/phase-23-full-e2e-demo/23-SUMMARY.md b/.planning/phases/phase-23-full-e2e-demo/23-SUMMARY.md index d5d8f37f..7a2ba696 100644 --- a/.planning/phases/phase-23-full-e2e-demo/23-SUMMARY.md +++ b/.planning/phases/phase-23-full-e2e-demo/23-SUMMARY.md @@ -30,6 +30,7 @@ Created `apps/web/e2e/full-vertical-slice.spec.ts` — 19 Playwright tests cover ### Phase 23 Meta-Harness Created `scripts/harness/phase23-full-e2e-check.ts` which: + - Preflights API and Web reachability with clear boot instructions on failure - Runs `pnpm meta:harness:phase22b -- --strict --with-api` (which composes Phase 22A + 22B) - Runs Playwright full-vertical-slice spec from the `apps/web` directory @@ -83,6 +84,7 @@ Phase 22B already proved 8/8 live API checks pass against seeded fixtures. Phase ## Regression Verification All previous phase harnesses preserved and verified: + - Phase 20C harness: still passes - Phase 20D harness: still passes - Phase 20E harness: still passes @@ -98,22 +100,22 @@ All previous phase harnesses preserved and verified: ## Files Changed -| File | Change | -|------|--------| -| `apps/web/e2e/full-vertical-slice.spec.ts` | Created — 19 Playwright tests | -| `scripts/harness/phase23-full-e2e-check.ts` | Created — meta-harness | -| `docs/demo/DEMO-CHECKLIST.md` | Created — manual demo walkthrough | -| `docs/demo/README-DEMO.md` | Updated — exact commands | -| `README.md` | Updated — Phase 23 done, demo section honest | -| `apps/web/playwright.config.ts` | Fixed — baseURL fallback | -| `.env` | Added — `VITE_WEB_BASE_URL` | -| `package.json` | Added — `meta:harness:phase23` script | -| `.planning/STATE.md` | Updated — Phase 23 complete | -| `.planning/ROADMAP.md` | Updated — Phase 23 complete | -| `.planning/MILESTONES.md` | Updated — v1.1 complete | -| `.planning/phases/phase-23-full-e2e-demo/23-PLAN.md` | Updated — status complete | -| `.planning/phases/phase-23-full-e2e-demo/23-SUMMARY.md` | Created | -| `.planning/phases/phase-23-full-e2e-demo/23-REVIEW.md` | Created | +| File | Change | +| ------------------------------------------------------- | -------------------------------------------- | +| `apps/web/e2e/full-vertical-slice.spec.ts` | Created — 19 Playwright tests | +| `scripts/harness/phase23-full-e2e-check.ts` | Created — meta-harness | +| `docs/demo/DEMO-CHECKLIST.md` | Created — manual demo walkthrough | +| `docs/demo/README-DEMO.md` | Updated — exact commands | +| `README.md` | Updated — Phase 23 done, demo section honest | +| `apps/web/playwright.config.ts` | Fixed — baseURL fallback | +| `.env` | Added — `VITE_WEB_BASE_URL` | +| `package.json` | Added — `meta:harness:phase23` script | +| `.planning/STATE.md` | Updated — Phase 23 complete | +| `.planning/ROADMAP.md` | Updated — Phase 23 complete | +| `.planning/MILESTONES.md` | Updated — v1.1 complete | +| `.planning/phases/phase-23-full-e2e-demo/23-PLAN.md` | Updated — status complete | +| `.planning/phases/phase-23-full-e2e-demo/23-SUMMARY.md` | Created | +| `.planning/phases/phase-23-full-e2e-demo/23-REVIEW.md` | Created | --- diff --git a/README.md b/README.md index 9477aab2..66cef86f 100644 --- a/README.md +++ b/README.md @@ -136,29 +136,29 @@ To record a demo GIF or MP4, see the recording tips in [docs/demo/DEMO-CHECKLIST ### v1.1 — Production Hardening & Real Vertical Slice (Complete) -| Feature | Status | Target Phase | -| -------------------------- | ---------- | -------------------- | -| Professional README | ✅ Done | Phase 11 (complete) | -| CI completeness | ✅ Done | Phase 12A | -| Local stack & seed | ✅ Done | Phase 12B | -| Security hardening | ✅ Done | Phase 13 (complete) | -| Adapter boundary cleanup | ✅ Done | Phase 14A (complete) | -| Domain invariants | ✅ Done | Phase 14B (complete) | -| Observability & health | ✅ Done | Phase 15 | -| Frontend feature split (minimum) | ✅ Done | Phase 16A | -| Frontend split completion | ✅ Done | Phase 21 (complete) | -| Real media processing | ✅ Done | Phase 17 | -| Dataset lock & COCO export | ✅ Done | Phase 18 | -| Real ONNX inference | ✅ Done | Phase 19 (complete) | -| Evaluation E2E | ✅ Done | Phase 20 (complete) | -| Evaluation Correctness | ✅ Done | Phase 20B (complete) | -| Evaluation Persistence | ✅ Done | Phase 20D (complete) | -| Evaluation Migration | ✅ Done | Phase 20E (complete) | -| Evaluation Migration Chain | ✅ Done | Phase 20F (complete) | -| Frontend split completion | ✅ Done | Phase 21 (complete) | -| Fixture & Test Infrastructure | ✅ Done | Phase 22A (complete) | -| Production test suite | ✅ Done | Phase 22B (complete) | -| Full E2E proof + demo docs | ✅ Done | Phase 23 (complete, demo media deferred) | +| Feature | Status | Target Phase | +| -------------------------------- | ------- | ---------------------------------------- | +| Professional README | ✅ Done | Phase 11 (complete) | +| CI completeness | ✅ Done | Phase 12A | +| Local stack & seed | ✅ Done | Phase 12B | +| Security hardening | ✅ Done | Phase 13 (complete) | +| Adapter boundary cleanup | ✅ Done | Phase 14A (complete) | +| Domain invariants | ✅ Done | Phase 14B (complete) | +| Observability & health | ✅ Done | Phase 15 | +| Frontend feature split (minimum) | ✅ Done | Phase 16A | +| Frontend split completion | ✅ Done | Phase 21 (complete) | +| Real media processing | ✅ Done | Phase 17 | +| Dataset lock & COCO export | ✅ Done | Phase 18 | +| Real ONNX inference | ✅ Done | Phase 19 (complete) | +| Evaluation E2E | ✅ Done | Phase 20 (complete) | +| Evaluation Correctness | ✅ Done | Phase 20B (complete) | +| Evaluation Persistence | ✅ Done | Phase 20D (complete) | +| Evaluation Migration | ✅ Done | Phase 20E (complete) | +| Evaluation Migration Chain | ✅ Done | Phase 20F (complete) | +| Frontend split completion | ✅ Done | Phase 21 (complete) | +| Fixture & Test Infrastructure | ✅ Done | Phase 22A (complete) | +| Production test suite | ✅ Done | Phase 22B (complete) | +| Full E2E proof + demo docs | ✅ Done | Phase 23 (complete, demo media deferred) | ### Out of Scope @@ -468,26 +468,26 @@ pnpm --filter @visionflow/web test:e2e -- e2e/full-vertical-slice.spec.ts --proj ## Environment Variables -| Variable | Default | Description | -| --------------------------- | ------------------------------------- | ----------------------------------------------- | -| `DATABASE_URL` | `postgresql://...@localhost:5432/...` | PostgreSQL connection string | -| `REDIS_HOST` | `localhost` | Redis host | -| `REDIS_PORT` | `6379` | Redis port | -| `MINIO_ENDPOINT` | `localhost` | MinIO endpoint | -| `MINIO_PORT` | `9000` | MinIO port | -| `MINIO_ACCESS_KEY` | `visionflow` | MinIO access key | -| `MINIO_SECRET_KEY` | `visionflow-secret` | MinIO secret key | -| `MINIO_BUCKET` | `visionflow-artifacts` | MinIO bucket name | -| `API_PORT` | `3000` | API server port | -| `API_BASE_URL` | `http://localhost:3000/api` | Harness → API base URL (harnesses use this) | -| `CV_WORKER_URL` | `http://localhost:8000` | CV Worker URL | -| `CV_WORKER_DETECTOR_MODE` | `mock` | Detector mode (`mock` or `onnx`) | -| `VITE_API_BASE_URL` | `http://localhost:3000` | Web → API base URL (no `/api` suffix) | +| Variable | Default | Description | +| --------------------------- | ------------------------------------- | ---------------------------------------------------------------------- | +| `DATABASE_URL` | `postgresql://...@localhost:5432/...` | PostgreSQL connection string | +| `REDIS_HOST` | `localhost` | Redis host | +| `REDIS_PORT` | `6379` | Redis port | +| `MINIO_ENDPOINT` | `localhost` | MinIO endpoint | +| `MINIO_PORT` | `9000` | MinIO port | +| `MINIO_ACCESS_KEY` | `visionflow` | MinIO access key | +| `MINIO_SECRET_KEY` | `visionflow-secret` | MinIO secret key | +| `MINIO_BUCKET` | `visionflow-artifacts` | MinIO bucket name | +| `API_PORT` | `3000` | API server port | +| `API_BASE_URL` | `http://localhost:3000/api` | Harness → API base URL (harnesses use this) | +| `CV_WORKER_URL` | `http://localhost:8000` | CV Worker URL | +| `CV_WORKER_DETECTOR_MODE` | `mock` | Detector mode (`mock` or `onnx`) | +| `VITE_API_BASE_URL` | `http://localhost:3000` | Web → API base URL (no `/api` suffix) | | `VITE_WEB_BASE_URL` | `http://localhost:5173` | Playwright baseURL (fallback; Playwright manages its own server in CI) | -| `WEB_ORIGIN` | `http://localhost:5173` | Allowed CORS origins (comma-separated) | -| `SIGNED_URL_EXPIRY_SECONDS` | `3600` | Signed URL expiry (0 = use API proxy) | -| `LOG_LEVEL` | `info` | Log level: debug, info, warn, error | -| `HEALTH_CHECK_TIMEOUT_MS` | `5000` | Timeout for health check dependency probes (ms) | +| `WEB_ORIGIN` | `http://localhost:5173` | Allowed CORS origins (comma-separated) | +| `SIGNED_URL_EXPIRY_SECONDS` | `3600` | Signed URL expiry (0 = use API proxy) | +| `LOG_LEVEL` | `info` | Log level: debug, info, warn, error | +| `HEALTH_CHECK_TIMEOUT_MS` | `5000` | Timeout for health check dependency probes (ms) | ## Project Structure diff --git a/apps/api/src/health/health.service.ts b/apps/api/src/health/health.service.ts index 35162c49..22a0dbba 100644 --- a/apps/api/src/health/health.service.ts +++ b/apps/api/src/health/health.service.ts @@ -66,12 +66,14 @@ export class HealthService { queueStatus = 'unknown'; } - const cvWorkerDetails = cvWorker.details as { - version?: string; - capabilities?: Record; - error?: string; - note?: string; - } | undefined; + const cvWorkerDetails = cvWorker.details as + | { + version?: string; + capabilities?: Record; + error?: string; + note?: string; + } + | undefined; const cvCapabilities = cvWorkerDetails?.capabilities; const onnxInfo = cvCapabilities?.onnxDetector as @@ -81,11 +83,9 @@ export class HealthService { | { thumbnail?: boolean; frameExtraction?: { available?: boolean } } | undefined; - const cvConfigured = - Boolean(process.env.CV_WORKER_URL) && process.env.CV_WORKER_URL !== 'mock'; + const cvConfigured = Boolean(process.env.CV_WORKER_URL) && process.env.CV_WORKER_URL !== 'mock'; - const requestedDetectorMode = - process.env.CV_WORKER_DETECTOR_MODE === 'onnx' ? 'onnx' : 'mock'; + const requestedDetectorMode = process.env.CV_WORKER_DETECTOR_MODE === 'onnx' ? 'onnx' : 'mock'; return { api: { diff --git a/apps/cv-worker/tests/test_onnx_detector.py b/apps/cv-worker/tests/test_onnx_detector.py index 81460188..d795d1db 100644 --- a/apps/cv-worker/tests/test_onnx_detector.py +++ b/apps/cv-worker/tests/test_onnx_detector.py @@ -457,15 +457,12 @@ def test_resolve_model_path_relative(): # Relative path should resolve to project root result = _resolve_model_path("./models/yolov8n.onnx") - assert result.is_absolute() - assert "Vision" in str(result) - assert "yolov8n.onnx" in result.name + assert result == Path(__file__).resolve().parents[3] / "models" / "yolov8n.onnx" -def test_resolve_model_path_absolute(): +def test_resolve_model_path_absolute(tmp_path): from main import _resolve_model_path - # On Windows, only drive-letter paths (D:\...) are absolute. - # Unix-style /tmp/... is treated as relative and resolved against PROJECT_ROOT. - result = _resolve_model_path("D:/tmp/custom/path.onnx") - assert str(result) == "D:\\tmp\\custom\\path.onnx" + model_path = tmp_path / "custom" / "path.onnx" + assert model_path.is_absolute() + assert _resolve_model_path(str(model_path)) == model_path diff --git a/apps/web/e2e/full-vertical-slice.spec.ts b/apps/web/e2e/full-vertical-slice.spec.ts index fbfd93d3..31cccb2b 100644 --- a/apps/web/e2e/full-vertical-slice.spec.ts +++ b/apps/web/e2e/full-vertical-slice.spec.ts @@ -127,7 +127,9 @@ test.describe('Full Vertical Slice — Production Path Proof', () => { await expect(panelContent).toBeVisible({ timeout: 5_000 }); // Assert the canonical LOCKED status text is visible — proves Phase 22A fixture surfaced. - await expect(page.getByText('LOCKED', { exact: false }).first()).toBeVisible({ timeout: 5_000 }); + await expect(page.getByText('LOCKED', { exact: false }).first()).toBeVisible({ + timeout: 5_000, + }); expect(errors).toHaveLength(0); }); @@ -199,7 +201,9 @@ test.describe('Full Vertical Slice — Production Path Proof', () => { await expect(panelContent).toBeVisible({ timeout: 5_000 }); // Assert the canonical SUCCEEDED status text is visible — proves Phase 22A fixture surfaced. - await expect(page.getByText('SUCCEEDED', { exact: false }).first()).toBeVisible({ timeout: 5_000 }); + await expect(page.getByText('SUCCEEDED', { exact: false }).first()).toBeVisible({ + timeout: 5_000, + }); expect(errors).toHaveLength(0); }); @@ -228,16 +232,24 @@ test.describe('Full Vertical Slice — Production Path Proof', () => { // Assert evaluation metric labels are visible — proves EvaluationMetricsPanel rendered. // Seeded data has precision=1.0, recall=1.0, f1=1.0, meanIoU=1.0. - await expect(page.getByText('Precision', { exact: false }).first()).toBeVisible({ timeout: 5_000 }); - await expect(page.getByText('Recall', { exact: false }).first()).toBeVisible({ timeout: 5_000 }); + await expect(page.getByText('Precision', { exact: false }).first()).toBeVisible({ + timeout: 5_000, + }); + await expect(page.getByText('Recall', { exact: false }).first()).toBeVisible({ + timeout: 5_000, + }); await expect(page.getByText('F1', { exact: false }).first()).toBeVisible({ timeout: 5_000 }); - await expect(page.getByText('Mean IoU', { exact: false }).first()).toBeVisible({ timeout: 5_000 }); + await expect(page.getByText('Mean IoU', { exact: false }).first()).toBeVisible({ + timeout: 5_000, + }); // Assert TP/FP/FN tiles are visible — seeded data has TP=3, FP=0, FN=0. await expect(page.getByText('TP', { exact: false }).first()).toBeVisible({ timeout: 5_000 }); // Assert prediction overlay section is present. - await expect(page.getByText('Prediction overlay', { exact: false }).first()).toBeVisible({ timeout: 5_000 }); + await expect(page.getByText('Prediction overlay', { exact: false }).first()).toBeVisible({ + timeout: 5_000, + }); expect(errors).toHaveLength(0); }); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 6d948536..52ba8443 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -29,11 +29,7 @@ export function App() { const { api, database, queue, cvWorker } = runtimeStatus.readiness; const apiHealth: WorkbenchRuntimeState['health']['api'] = - api.kind === 'connected' - ? 'connected' - : api.kind === 'loading' - ? 'loading' - : 'unavailable'; + api.kind === 'connected' ? 'connected' : api.kind === 'loading' ? 'loading' : 'unavailable'; const dbHealth: WorkbenchRuntimeState['health']['database'] = database.kind === 'ready' @@ -87,13 +83,8 @@ export function App() { const { job, startJob } = useInferenceJobController(); - const { - evaluationReport, - isEvaluating, - evaluationError, - predictions, - handleRunEvaluation, - } = useEvaluationController(job); + const { evaluationReport, isEvaluating, evaluationError, predictions, handleRunEvaluation } = + useEvaluationController(job); // Derive runtime state from resolved API data and backend runtime status. // Every selector (canRunInference, canRunEvaluation) consumes this state. @@ -126,7 +117,14 @@ export function App() { worker: runtimeHealth.worker, }, }; - }, [job, predictions, evaluationReport, datasetVersions, selectedDatasetVersionId, runtimeHealth]); + }, [ + job, + predictions, + evaluationReport, + datasetVersions, + selectedDatasetVersionId, + runtimeHealth, + ]); // Resolve eligibility from runtime state const inferenceEligibility = useMemo(() => canRunInference(runtimeState), [runtimeState]); @@ -142,11 +140,7 @@ export function App() {
- + {source}; - } function JobStageStep({ diff --git a/apps/web/src/app/PipelinePanel.tsx b/apps/web/src/app/PipelinePanel.tsx index 92c60bc0..635cad66 100644 --- a/apps/web/src/app/PipelinePanel.tsx +++ b/apps/web/src/app/PipelinePanel.tsx @@ -30,9 +30,7 @@ import type { PipelineValidationIssue, PipelineValidationResult, } from '@visionflow/contracts'; -import { - validatePipelineDefinition, -} from '@visionflow/contracts'; +import { validatePipelineDefinition } from '@visionflow/contracts'; import { Panel } from './ui/Panel'; import { StateRow } from './ui/StateRow'; import { VisionPreview } from './ui/VisionPreview'; diff --git a/apps/web/src/app/ReadinessStrip.tsx b/apps/web/src/app/ReadinessStrip.tsx index c3d17650..e50c5f2e 100644 --- a/apps/web/src/app/ReadinessStrip.tsx +++ b/apps/web/src/app/ReadinessStrip.tsx @@ -42,7 +42,14 @@ function ApiStatusBadge({ readiness }: { readiness: RuntimeReadiness }) { const { api } = readiness; if (api.kind === 'loading') { - return ; + return ( + + ); } if (api.kind === 'connected') { const modeLabel = api.mode === 'database' ? 'Database ready' : 'In-memory'; @@ -55,10 +62,19 @@ function DatabaseStatusBadge({ readiness }: { readiness: RuntimeReadiness }) { const { database } = readiness; if (database.kind === 'loading') { - return ; + return ( + + ); } if (database.kind === 'ready') { - return ; + return ( + + ); } if (database.kind === 'unavailable') { return ; @@ -76,7 +92,14 @@ function QueueStatusBadge({ const { queue } = readiness; if (queue.kind === 'loading') { - return ; + return ( + + ); } if (queue.kind === 'bullmq-ready') { if (job?.source === 'api' && job?.status === 'RUNNING') { @@ -97,19 +120,44 @@ function CvStatusBadge({ readiness }: { readiness: RuntimeReadiness }) { const { cvWorker } = readiness; if (cvWorker.kind === 'loading') { - return ; + return ( + + ); } if (cvWorker.kind === 'onnx-ready') { - return ; + return ( + + ); } if (cvWorker.kind === 'onnx-configured-unavailable') { - return ; + return ( + + ); } if (cvWorker.kind === 'mock-fallback') { - return ; + return ( + + ); } if (cvWorker.kind === 'worker-unavailable') { - return ; + return ( + + ); } return ; } diff --git a/apps/web/src/features/datasets/useDatasetsController.ts b/apps/web/src/features/datasets/useDatasetsController.ts index 1687fa10..6de33d16 100644 --- a/apps/web/src/features/datasets/useDatasetsController.ts +++ b/apps/web/src/features/datasets/useDatasetsController.ts @@ -30,16 +30,12 @@ export function useDatasetsController(): UseDatasetsControllerResult { if (cancelled) return; const versionResponses = await Promise.all( - datasetsResponse.datasets.map((ds) => - listDatasetVersions(DEMO_PROJECT_ID, ds.id) - ) + datasetsResponse.datasets.map((ds) => listDatasetVersions(DEMO_PROJECT_ID, ds.id)) ); if (cancelled) return; - const allVersions: DatasetVersionSummary[] = versionResponses.flatMap( - (vr) => vr.versions - ); + const allVersions: DatasetVersionSummary[] = versionResponses.flatMap((vr) => vr.versions); setDatasetVersions(allVersions); diff --git a/apps/web/src/features/inference/useInferenceJobController.ts b/apps/web/src/features/inference/useInferenceJobController.ts index 3c7149ac..0d90de43 100644 --- a/apps/web/src/features/inference/useInferenceJobController.ts +++ b/apps/web/src/features/inference/useInferenceJobController.ts @@ -251,47 +251,44 @@ export function useInferenceJobController(): UseInferenceJobControllerResult { return () => window.clearInterval(timer); }, [job.id, job.source, job.status]); - const startJob = useCallback( - () => { - void (async () => { + const startJob = useCallback(() => { + void (async () => { + setJob((current) => ({ + ...current, + status: 'QUEUED', + progress: 0, + source: current.source === 'fallback' ? 'loading' : current.source, + error: null, + logs: ['Resolving locked dataset version and persisted pipeline.'], + })); + + try { + const target = await resolveInferenceRunTarget(demoSnapshot.project.id); + const response = await createInferenceJob(demoSnapshot.project.id, { + datasetVersionId: target.datasetVersionId, + pipelineId: target.pipelineId, + modelId: null, + }); + + setJob( + toJobUiState(response.job, 'api', [ + 'Queue accepted inference payload with IDs only.', + `Dataset ${target.datasetVersionLabel} and pipeline ${target.pipelineName} selected.`, + ]) + ); + } catch (error) { + const message = formatUiError(error); setJob((current) => ({ ...current, - status: 'QUEUED', - progress: 0, - source: current.source === 'fallback' ? 'loading' : current.source, - error: null, - logs: ['Resolving locked dataset version and persisted pipeline.'], + status: 'FAILED', + progress: 100, + source: 'fallback', + error: message, + logs: [`Run failed: ${message}`].slice(-8), })); - - try { - const target = await resolveInferenceRunTarget(demoSnapshot.project.id); - const response = await createInferenceJob(demoSnapshot.project.id, { - datasetVersionId: target.datasetVersionId, - pipelineId: target.pipelineId, - modelId: null, - }); - - setJob( - toJobUiState(response.job, 'api', [ - 'Queue accepted inference payload with IDs only.', - `Dataset ${target.datasetVersionLabel} and pipeline ${target.pipelineName} selected.`, - ]) - ); - } catch (error) { - const message = formatUiError(error); - setJob((current) => ({ - ...current, - status: 'FAILED', - progress: 100, - source: 'fallback', - error: message, - logs: [`Run failed: ${message}`].slice(-8), - })); - } - })(); - }, - [] - ); + } + })(); + }, []); return { job, startJob }; } diff --git a/apps/web/src/features/inspector/InspectorRouter.tsx b/apps/web/src/features/inspector/InspectorRouter.tsx index 3287da66..3f194bb4 100644 --- a/apps/web/src/features/inspector/InspectorRouter.tsx +++ b/apps/web/src/features/inspector/InspectorRouter.tsx @@ -1,10 +1,5 @@ import type { InferenceJobSummary, PredictionSummary } from '@visionflow/contracts'; -import { - DatasetInspector, - InspectorShell, - JobInspector, - MediaInspector, -} from './index'; +import { DatasetInspector, InspectorShell, JobInspector, MediaInspector } from './index'; import { ActionHint } from '../../shared/ui/ActionHint'; import type { MediaInspectorData } from './inspector.types'; diff --git a/apps/web/src/features/inspector/index.ts b/apps/web/src/features/inspector/index.ts index 5bb441cb..132d07ce 100644 --- a/apps/web/src/features/inspector/index.ts +++ b/apps/web/src/features/inspector/index.ts @@ -5,8 +5,4 @@ export { PipelineInspector } from './PipelineInspector'; export { JobInspector } from './JobInspector'; export { InspectorRouter } from './InspectorRouter'; export type { InspectorRouterProps } from './InspectorRouter'; -export type { - MediaInspectorData, - DatasetInspectorData, - JobInspectorData, -} from './inspector.types'; +export type { MediaInspectorData, DatasetInspectorData, JobInspectorData } from './inspector.types'; diff --git a/apps/web/src/features/runtime/RuntimeReadinessStrip.tsx b/apps/web/src/features/runtime/RuntimeReadinessStrip.tsx index 50e07bc2..7ab34846 100644 --- a/apps/web/src/features/runtime/RuntimeReadinessStrip.tsx +++ b/apps/web/src/features/runtime/RuntimeReadinessStrip.tsx @@ -28,7 +28,14 @@ function ApiStatusBadge({ readiness }: RuntimeReadinessStripProps) { const { api } = readiness; if (api.kind === 'loading') { - return ; + return ( + + ); } if (api.kind === 'connected') { const modeLabel = api.mode === 'database' ? 'Database ready' : 'In-memory'; @@ -41,10 +48,19 @@ function DatabaseStatusBadge({ readiness }: RuntimeReadinessStripProps) { const { database } = readiness; if (database.kind === 'loading') { - return ; + return ( + + ); } if (database.kind === 'ready') { - return ; + return ( + + ); } if (database.kind === 'unavailable') { return ; @@ -56,7 +72,14 @@ function QueueStatusBadge({ readiness }: RuntimeReadinessStripProps) { const { queue } = readiness; if (queue.kind === 'loading') { - return ; + return ( + + ); } if (queue.kind === 'bullmq-ready') { return ; @@ -74,7 +97,14 @@ function CvStatusBadge({ readiness }: RuntimeReadinessStripProps) { const { cvWorker } = readiness; if (cvWorker.kind === 'loading') { - return ; + return ( + + ); } if (cvWorker.kind === 'onnx-ready') { return ( @@ -97,10 +127,14 @@ function CvStatusBadge({ readiness }: RuntimeReadinessStripProps) { ); } if (cvWorker.kind === 'mock-fallback') { - return ; + return ( + + ); } if (cvWorker.kind === 'worker-unavailable') { - return ; + return ( + + ); } return ; } diff --git a/apps/web/src/features/runtime/useRuntimeStatus.ts b/apps/web/src/features/runtime/useRuntimeStatus.ts index ebb34074..13cba13b 100644 --- a/apps/web/src/features/runtime/useRuntimeStatus.ts +++ b/apps/web/src/features/runtime/useRuntimeStatus.ts @@ -62,9 +62,7 @@ function deriveApiState(data: RuntimeStatusResponse['api']): ApiReadinessState { return { kind: 'unavailable' }; } -function deriveDatabaseState( - data: RuntimeStatusResponse['database'] -): DatabaseReadinessState { +function deriveDatabaseState(data: RuntimeStatusResponse['database']): DatabaseReadinessState { switch (data.status) { case 'ready': return { kind: 'ready' }; diff --git a/apps/web/src/shared/state/workbench-runtime.ts b/apps/web/src/shared/state/workbench-runtime.ts index 556f94ae..ba22e0b8 100644 --- a/apps/web/src/shared/state/workbench-runtime.ts +++ b/apps/web/src/shared/state/workbench-runtime.ts @@ -13,7 +13,13 @@ export type RuntimeMode = 'loading' | 'api' | 'fallback' | 'mock' | 'degraded'; export type JobStatus = 'NONE' | 'QUEUED' | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED'; -export type HealthStatus = 'loading' | 'connected' | 'unavailable' | 'unknown' | 'fallback' | 'mock'; +export type HealthStatus = + | 'loading' + | 'connected' + | 'unavailable' + | 'unknown' + | 'fallback' + | 'mock'; export type WorkbenchRuntimeState = { /** How the runtime was bootstrapped */ diff --git a/docs/PROJECT-CLOSEOUT.md b/docs/PROJECT-CLOSEOUT.md index 22b0bfc5..6685c918 100644 --- a/docs/PROJECT-CLOSEOUT.md +++ b/docs/PROJECT-CLOSEOUT.md @@ -10,13 +10,13 @@ This does not mean the project is abandoned. Future development is intentionally ## Current Classification -| Area | Status | -| --------------------- | -------------------------------------- | -| Engineering proof | Complete | -| Product prototype proof | Complete | -| Portfolio readiness | Mostly complete | -| Demo media | Deferred | -| Production SaaS readiness | Out of scope | +| Area | Status | +| ------------------------- | --------------- | +| Engineering proof | Complete | +| Product prototype proof | Complete | +| Portfolio readiness | Mostly complete | +| Demo media | Deferred | +| Production SaaS readiness | Out of scope | VisionFlow should currently be understood as a **local/private computer vision workbench prototype** with production-style engineering boundaries. It is not yet a public SaaS product. diff --git a/docs/demo/README-DEMO.md b/docs/demo/README-DEMO.md index 62094773..ccaf78e1 100644 --- a/docs/demo/README-DEMO.md +++ b/docs/demo/README-DEMO.md @@ -50,6 +50,7 @@ not mock data. Shows: Database ready, Queue ready, CV Worker configured. ### Step 2: Media Upload (8s) Navigate to **Media** tab. Upload a sample image. Show: + - Real-time upload progress bar - SHA-256 dedupe indicator - Thumbnail generated by CV worker (real Pillow → WebP) @@ -58,6 +59,7 @@ Navigate to **Media** tab. Upload a sample image. Show: ### Step 3: Dataset Versioning (8s) Navigate to **Versions** tab. Show: + - Canonical LOCKED dataset version: `parking_v3` - Split distribution: TRAIN / VALID / TEST - Locked versions show a lock indicator @@ -66,6 +68,7 @@ Navigate to **Versions** tab. Show: ### Step 4: Annotation (8s) Navigate to **Annotate** tab. Show: + - Bounding boxes for car / van / truck on `north-gate-frame-1482.jpg` - Color-coded labels (green = ground truth) - Label selector dropdown @@ -74,6 +77,7 @@ Navigate to **Annotate** tab. Show: ### Step 5: Pipeline Builder (6s) Navigate to **Pipeline** tab. Show: + - Visual pipeline graph: Input → Resize → Detector → NMS → Output - YOLOv8n detector node config: 640×640, confidence 0.25, NMS 0.45 - Pipeline validation passing @@ -81,6 +85,7 @@ Navigate to **Pipeline** tab. Show: ### Step 6: Job Execution (8s) Navigate to **Jobs** tab. Show: + - Canonical SUCCEEDED job: `job_2026_04_28_2036` - Job metadata: dataset version, pipeline, model, progress log - 3 real predictions with label, confidence, and bounding box geometry @@ -89,6 +94,7 @@ Navigate to **Jobs** tab. Show: ### Step 7: Prediction Overlay & Evaluation Metrics (6s) In the **Jobs** panel, show: + - Evaluation metrics: Precision, Recall, F1, Mean IoU (all 1.0 for perfect match) - Per-class breakdown: car, van, truck — each with TP=1, FP=0, FN=0 - Reports persisted with deterministic `inputHash` and `metricsHash` @@ -97,6 +103,7 @@ In the **Jobs** panel, show: ### Step 8: Timeline Replay (4s) Navigate to **Replay** tab. Show: + - BBox morph animation between frames - Ground truth / prediction toggle - Playback controls @@ -104,6 +111,7 @@ Navigate to **Replay** tab. Show: ### Step 9: Dataset Diff (4s) Navigate to **Diff** tab. Show: + - Version comparison interface - IoU-based added/removed/changed annotation detection @@ -165,18 +173,23 @@ If recording a GIF is not possible, use high-quality static screenshots: ## Demo ### Media Upload + ![Media Upload](docs/demo/screenshots/media-upload.png) ### Dataset Versioning + ![Dataset Versioning](docs/demo/screenshots/versions.png) ### Annotation + ![Annotation](docs/demo/screenshots/annotate.png) ### Pipeline Builder + ![Pipeline](docs/demo/screenshots/pipeline.png) ### Evaluation Results + ![Evaluation](docs/demo/screenshots/evaluation.png) ``` diff --git a/docs/portfolio/CI_AUDIT.md b/docs/portfolio/CI_AUDIT.md new file mode 100644 index 00000000..afe74660 --- /dev/null +++ b/docs/portfolio/CI_AUDIT.md @@ -0,0 +1,33 @@ +# CI audit — VisionFlow Studio + +Observed 2026-11-02. Source baseline: `7801ba9bfd71a7c8e35d988d2029c556cac1ca47` on Windows. A later local commit contains the path-test and audit changes described below. No push or hosted rerun was performed. + +## Hosted baseline + +The latest [CI run 27837664959](https://github.com/lhcaps/Vision/actions/runs/27837664959) and [E2E run 27837664958](https://github.com/lhcaps/Vision/actions/runs/27837664958) both ran against the baseline SHA and failed. Job and step metadata was retrieved with `gh run view --json jobs,conclusion,headSha,url`. Attempts to obtain either run's full failed logs with `gh run view --log-failed` returned HTTP 410, so the exact hosted traceback is unavailable. + +| Job | Hosted observation | +| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| Lint, Type Check, Test, Migration Chain | Passed at baseline SHA, not at the later local commit. | +| [Pytest](https://github.com/lhcaps/Vision/actions/runs/27837664959/job/82389433788) | Failed at `python -m pytest tests/ -v`. | +| [Format Check](https://github.com/lhcaps/Vision/actions/runs/27837664959/job/82389433809) | Failed at `pnpm format:check`. | +| [DB Harness](https://github.com/lhcaps/Vision/actions/runs/27837664959/job/82389550250) | Failed at `pnpm harness:phase22a` after `db:push` and seed; cause unknown without logs or a reproduction. | +| Build | Skipped because upstream jobs failed. A build step in a different job is not a successful Build job. | +| [Playwright E2E](https://github.com/lhcaps/Vision/actions/runs/27837664958/job/82389343510) | Failed at `pnpm test:e2e`; cause unknown without logs or a reproduction. | + +Migration Chain uses `prisma migrate deploy` while DB Harness uses `db:push`; this is an observed workflow difference, not a demonstrated cause of the failure. A previous successful CI run on a different SHA is not evidence for this baseline. + +## Local reproduction and change + +- `py -3.11 -m pytest tests/ -v -p no:cacheprovider` from `apps/cv-worker`, with `PYTHONDONTWRITEBYTECODE=1`: baseline **FAIL**, 43 passed / 1 failed / 1 skipped. The relative model-path test assumed the checkout path contained the case-sensitive string `Vision`, which this worktree did not. +- The absolute-path test used a Windows drive path and expected Windows separators even though the hosted runner is Linux. `PurePosixPath('D:/tmp/custom/path.onnx').is_absolute()` returns `False`. This demonstrates a platform mismatch in the test; the expired hosted logs prevent claiming it was the observed hosted failure. +- Changed only the two existing tests: assert the full expected repository-relative path and use pytest's platform-native absolute `tmp_path`. The path contract remains checked; no application code or CI gate was weakened. +- Same suite after the change, `py -3.11 -m pytest tests/ -q -rs -p no:cacheprovider`: **44 passed, 1 skipped**. The skip requires a seeded MinIO source image. Local Python was 3.11.9 with pytest 9.0.3 and other preinstalled packages, not the pinned CI dependency set (pytest 8.3.5); this result is not equivalent to a CI run. +- `pnpm install --frozen-lockfile --ignore-scripts --store-dir `: **PASS**, pnpm 10.32.1. Lifecycle scripts were explicitly disabled, so this is not a full install/build verification. +- `pnpm format:check`: **FAIL**, Prettier 3.8.3 reported 456 tracked files on Windows with Node 22.23.1 and pnpm 10.32.1. Git's system `core.autocrlf=true` produced CRLF worktree files from LF index content; the repository has no root `.gitattributes`. `pnpm exec prettier --end-of-line auto --check .` was run as a **diagnostic only** and still **failed on 54 tracked files**: 28 planning, 14 application, nine scripts, two docs, and the README. It cleared 402 of the original warnings, consistent with line-ending conversion. The remaining 54 files were already tracked at the source baseline; no bulk formatting, ignore rules or gate change were applied. +- `pnpm exec prettier --find-config-path apps/api/src/main.ts` selected `.prettierrc` over the separate `prettier.config.cjs`; explicitly checking with the latter still reported 456 files with default line endings. The CI runner uses Node 20 on Linux, while this diagnostic used Node 22 on Windows. This investigation does not establish the exact hosted failure list because hosted logs expired. +- `docker version --format '{{.Server.Version}}'`: **FAIL**, local Docker daemon unavailable. DB Harness and E2E were not run, and no database or service was modified. + +## Remaining work + +Reproduce the Python suite on Linux with `requirements-dev.txt` pinned dependencies, run the full format gate after a scoped formatting strategy, reproduce the DB Harness with a disposable database and inspect the failing assertion, and run E2E with isolated infrastructure. Preserve every check and report actual results. A hosted success requires a new authorized push and a run at that exact SHA. diff --git a/prettier.config.cjs b/prettier.config.cjs deleted file mode 100644 index 3d6d4ef5..00000000 --- a/prettier.config.cjs +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - printWidth: 100, - singleQuote: false, - trailingComma: 'all', -}; diff --git a/scripts/harness/phase20c-evaluation-integrity-check.ts b/scripts/harness/phase20c-evaluation-integrity-check.ts index fa63f4b5..92f11624 100644 --- a/scripts/harness/phase20c-evaluation-integrity-check.ts +++ b/scripts/harness/phase20c-evaluation-integrity-check.ts @@ -232,11 +232,32 @@ async function main() { const metrics = reportRow!.metricsJson as Record; // Inline schema-equivalent check (no @visionflow/contracts dependency). - const requiredFields = ['id', 'jobId', 'datasetVersionId', 'algorithmVersion', 'iouThreshold', 'inputHash', 'metricsHash', 'precision', 'recall', 'f1', 'meanIoU', 'truePositives', 'falsePositives', 'falseNegatives', 'predictionCount', 'groundTruthCount', 'assetCount', 'evaluatedAt']; + const requiredFields = [ + 'id', + 'jobId', + 'datasetVersionId', + 'algorithmVersion', + 'iouThreshold', + 'inputHash', + 'metricsHash', + 'precision', + 'recall', + 'f1', + 'meanIoU', + 'truePositives', + 'falsePositives', + 'falseNegatives', + 'predictionCount', + 'groundTruthCount', + 'assetCount', + 'evaluatedAt', + ]; const missing = requiredFields.filter((f) => !(f in metrics) || metrics[f] === null); const hashRegex = /^[a-f0-9]{16}$/; - const inputHashOk = typeof metrics.inputHash === 'string' && hashRegex.test(metrics.inputHash); - const metricsHashOk = typeof metrics.metricsHash === 'string' && hashRegex.test(metrics.metricsHash); + const inputHashOk = + typeof metrics.inputHash === 'string' && hashRegex.test(metrics.inputHash); + const metricsHashOk = + typeof metrics.metricsHash === 'string' && hashRegex.test(metrics.metricsHash); const passed = missing.length === 0 && inputHashOk && metricsHashOk; results.push({ diff --git a/scripts/harness/phase20d-evaluation-db-index-check.ts b/scripts/harness/phase20d-evaluation-db-index-check.ts index 7d28f826..f98f8f71 100644 --- a/scripts/harness/phase20d-evaluation-db-index-check.ts +++ b/scripts/harness/phase20d-evaluation-db-index-check.ts @@ -265,11 +265,32 @@ async function main() { // ── Check 9: Latest report passes EvaluationReportSchema strict-parse ─────── { // Inline schema-equivalent check (no @visionflow/contracts dependency). - const requiredFields = ['id', 'jobId', 'datasetVersionId', 'algorithmVersion', 'iouThreshold', 'inputHash', 'metricsHash', 'precision', 'recall', 'f1', 'meanIoU', 'truePositives', 'falsePositives', 'falseNegatives', 'predictionCount', 'groundTruthCount', 'assetCount', 'evaluatedAt']; + const requiredFields = [ + 'id', + 'jobId', + 'datasetVersionId', + 'algorithmVersion', + 'iouThreshold', + 'inputHash', + 'metricsHash', + 'precision', + 'recall', + 'f1', + 'meanIoU', + 'truePositives', + 'falsePositives', + 'falseNegatives', + 'predictionCount', + 'groundTruthCount', + 'assetCount', + 'evaluatedAt', + ]; const missing = requiredFields.filter((f) => !(f in metrics) || metrics[f] === null); const hashRegex = /^[a-f0-9]{16}$/; - const inputHashOk = typeof metrics.inputHash === 'string' && hashRegex.test(metrics.inputHash as string); - const metricsHashOk = typeof metrics.metricsHash === 'string' && hashRegex.test(metrics.metricsHash as string); + const inputHashOk = + typeof metrics.inputHash === 'string' && hashRegex.test(metrics.inputHash as string); + const metricsHashOk = + typeof metrics.metricsHash === 'string' && hashRegex.test(metrics.metricsHash as string); const passed = missing.length === 0 && inputHashOk && metricsHashOk; results.push({ diff --git a/scripts/harness/phase20e-evaluation-migration-check.ts b/scripts/harness/phase20e-evaluation-migration-check.ts index b9716b21..e91e4b91 100644 --- a/scripts/harness/phase20e-evaluation-migration-check.ts +++ b/scripts/harness/phase20e-evaluation-migration-check.ts @@ -395,12 +395,37 @@ async function main() { >('SELECT "metricsJson" FROM "EvaluationReport" ORDER BY "createdAt" DESC LIMIT 1'); if (latestRows.length > 0) { // Inline schema-equivalent check (no @visionflow/contracts dependency). - const requiredFields = ['id', 'jobId', 'datasetVersionId', 'algorithmVersion', 'iouThreshold', 'inputHash', 'metricsHash', 'precision', 'recall', 'f1', 'meanIoU', 'truePositives', 'falsePositives', 'falseNegatives', 'predictionCount', 'groundTruthCount', 'assetCount', 'evaluatedAt']; + const requiredFields = [ + 'id', + 'jobId', + 'datasetVersionId', + 'algorithmVersion', + 'iouThreshold', + 'inputHash', + 'metricsHash', + 'precision', + 'recall', + 'f1', + 'meanIoU', + 'truePositives', + 'falsePositives', + 'falseNegatives', + 'predictionCount', + 'groundTruthCount', + 'assetCount', + 'evaluatedAt', + ]; const latestMetrics = latestRows[0].metricsJson; - const missing = requiredFields.filter((f) => !(f in latestMetrics) || latestMetrics[f] === null); + const missing = requiredFields.filter( + (f) => !(f in latestMetrics) || latestMetrics[f] === null + ); const hashRegex = /^[a-f0-9]{16}$/; - const inputHashOk = typeof latestMetrics.inputHash === 'string' && hashRegex.test(latestMetrics.inputHash as string); - const metricsHashOk = typeof latestMetrics.metricsHash === 'string' && hashRegex.test(latestMetrics.metricsHash as string); + const inputHashOk = + typeof latestMetrics.inputHash === 'string' && + hashRegex.test(latestMetrics.inputHash as string); + const metricsHashOk = + typeof latestMetrics.metricsHash === 'string' && + hashRegex.test(latestMetrics.metricsHash as string); const passed = missing.length === 0 && inputHashOk && metricsHashOk; results.push({ diff --git a/scripts/harness/phase20f-migration-chain-check.ts b/scripts/harness/phase20f-migration-chain-check.ts index 38245901..460fb319 100644 --- a/scripts/harness/phase20f-migration-chain-check.ts +++ b/scripts/harness/phase20f-migration-chain-check.ts @@ -96,9 +96,9 @@ async function main() { // ── Check 1: _prisma_migrations table exists ────────────────────────────── { - const tableExists = await prisma.$queryRawUnsafe( + const tableExists = (await prisma.$queryRawUnsafe( "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '_prisma_migrations') AS exists" - ) as Array<{ exists: boolean }>; + )) as Array<{ exists: boolean }>; const passed = tableExists[0]?.exists === true; results.push({ @@ -113,11 +113,20 @@ async function main() { // ── Check 2: Baseline migration applied ────────────────────────────────── { - const baseline = await prisma.$queryRawUnsafe( + const baseline = (await prisma.$queryRawUnsafe( "SELECT migration_name, finished_at, rolled_back_at, started_at, applied_steps_count FROM _prisma_migrations WHERE migration_name = '00000000000000_init' ORDER BY finished_at DESC LIMIT 1" - ) as Array<{ migration_name: string; finished_at: string | null; rolled_back_at: string | null; started_at: string; applied_steps_count: number }>; - - const passed = baseline.length > 0 && baseline[0].finished_at !== null && baseline[0].rolled_back_at === null; + )) as Array<{ + migration_name: string; + finished_at: string | null; + rolled_back_at: string | null; + started_at: string; + applied_steps_count: number; + }>; + + const passed = + baseline.length > 0 && + baseline[0].finished_at !== null && + baseline[0].rolled_back_at === null; results.push({ name: 'Baseline migration 00000000000000_init is applied', passed, @@ -139,11 +148,18 @@ async function main() { // ── Check 3: Phase 20E migration applied ───────────────────────────────── { - const patch = await prisma.$queryRawUnsafe( + const patch = (await prisma.$queryRawUnsafe( "SELECT migration_name, finished_at, rolled_back_at, started_at, applied_steps_count FROM _prisma_migrations WHERE migration_name = '20260504_evaluation_report_integrity_columns' ORDER BY finished_at DESC LIMIT 1" - ) as Array<{ migration_name: string; finished_at: string | null; rolled_back_at: string | null; started_at: string; applied_steps_count: number }>; - - const passed = patch.length > 0 && patch[0].finished_at !== null && patch[0].rolled_back_at === null; + )) as Array<{ + migration_name: string; + finished_at: string | null; + rolled_back_at: string | null; + started_at: string; + applied_steps_count: number; + }>; + + const passed = + patch.length > 0 && patch[0].finished_at !== null && patch[0].rolled_back_at === null; results.push({ name: 'Phase 20E migration 20260504_evaluation_report_integrity_columns is applied', passed, @@ -156,8 +172,7 @@ async function main() { if (passed) logPass('Phase 20E migration applied: 20260504_evaluation_report_integrity_columns'); - else if (patch.length === 0) - logFail('Phase 20E migration NOT FOUND in _prisma_migrations'); + else if (patch.length === 0) logFail('Phase 20E migration NOT FOUND in _prisma_migrations'); else logFail( `Phase 20E migration status: finished=${patch[0].finished_at}, rolled_back=${patch[0].rolled_back_at}` @@ -166,9 +181,15 @@ async function main() { // ── Check 4: No failed migrations ───────────────────────────────────────── { - const failed = await prisma.$queryRawUnsafe( - "SELECT migration_name, finished_at, rolled_back_at, started_at, applied_steps_count FROM _prisma_migrations WHERE finished_at IS NULL AND rolled_back_at IS NULL ORDER BY started_at ASC" - ) as Array<{ migration_name: string; finished_at: string | null; rolled_back_at: string | null; started_at: string; applied_steps_count: number }>; + const failed = (await prisma.$queryRawUnsafe( + 'SELECT migration_name, finished_at, rolled_back_at, started_at, applied_steps_count FROM _prisma_migrations WHERE finished_at IS NULL AND rolled_back_at IS NULL ORDER BY started_at ASC' + )) as Array<{ + migration_name: string; + finished_at: string | null; + rolled_back_at: string | null; + started_at: string; + applied_steps_count: number; + }>; const passed = failed.length === 0; results.push({ @@ -188,10 +209,16 @@ async function main() { // ── Check 5: All expected tables exist ────────────────────────────────── { - const expectedTables = ['Project', 'DatasetVersion', 'EvaluationReport', 'InferenceJob', 'Prediction']; - const tables = await prisma.$queryRawUnsafe( + const expectedTables = [ + 'Project', + 'DatasetVersion', + 'EvaluationReport', + 'InferenceJob', + 'Prediction', + ]; + const tables = (await prisma.$queryRawUnsafe( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE'" - ) as Array<{ table_name: string }>; + )) as Array<{ table_name: string }>; const foundTables = new Set(tables.map((t) => t.table_name)); const missing = expectedTables.filter((t) => !foundTables.has(t)); @@ -209,14 +236,19 @@ async function main() { // ── Check 6: EvaluationReport integrity columns exist ────────────────────── { - const columns = await prisma.$queryRawUnsafe( + const columns = (await prisma.$queryRawUnsafe( "SELECT column_name FROM information_schema.columns WHERE table_name = 'EvaluationReport' AND column_name IN ('datasetVersionId', 'pipelineId', 'modelId', 'algorithmVersion', 'iouThreshold', 'inputHash', 'metricsHash')" - ) as Array<{ column_name: string }>; + )) as Array<{ column_name: string }>; const foundCols = new Set(columns.map((c) => c.column_name)); const requiredCols = [ - 'datasetVersionId', 'pipelineId', 'modelId', 'algorithmVersion', - 'iouThreshold', 'inputHash', 'metricsHash', + 'datasetVersionId', + 'pipelineId', + 'modelId', + 'algorithmVersion', + 'iouThreshold', + 'inputHash', + 'metricsHash', ]; const missing = requiredCols.filter((c) => !foundCols.has(c)); @@ -233,9 +265,9 @@ async function main() { // ── Check 7: Unique index for [inferenceJobId, inputHash] exists ────────── { - const indexes = await prisma.$queryRawUnsafe( + const indexes = (await prisma.$queryRawUnsafe( "SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'EvaluationReport' AND indexdef LIKE '%UNIQUE%'" - ) as Array<{ indexname: string; indexdef: string }>; + )) as Array<{ indexname: string; indexdef: string }>; const uniqueIndex = indexes.find( (i) => i.indexdef.includes('"inferenceJobId"') && i.indexdef.includes('"inputHash"') @@ -254,9 +286,9 @@ async function main() { // ── Check 8: At least one EvaluationReport row exists ──────────────────── { - const count = await prisma.$queryRawUnsafe( + const count = (await prisma.$queryRawUnsafe( 'SELECT COUNT(*)::bigint AS count FROM "EvaluationReport"' - ) as Array<{ count: bigint }>; + )) as Array<{ count: bigint }>; const rowCount = Number(count[0]?.count ?? 0); const passed = rowCount >= 1; @@ -275,25 +307,27 @@ async function main() { { const checks: { name: string; passed: boolean }[] = []; - const cols = await prisma.$queryRawUnsafe( + const cols = (await prisma.$queryRawUnsafe( "SELECT column_name FROM information_schema.columns WHERE table_name = 'EvaluationReport' AND column_name IN ('datasetVersionId', 'pipelineId', 'modelId', 'algorithmVersion', 'iouThreshold', 'inputHash', 'metricsHash')" - ) as Array<{ column_name: string }>; + )) as Array<{ column_name: string }>; checks.push({ name: 'All 7 integrity columns present', passed: cols.length >= 7 }); - const notNull = await prisma.$queryRawUnsafe( + const notNull = (await prisma.$queryRawUnsafe( "SELECT column_name FROM information_schema.columns WHERE table_name = 'EvaluationReport' AND column_name IN ('datasetVersionId', 'algorithmVersion', 'iouThreshold', 'inputHash', 'metricsHash') AND is_nullable = 'NO'" - ) as Array<{ column_name: string }>; + )) as Array<{ column_name: string }>; checks.push({ name: 'Required columns NOT NULL', passed: notNull.length >= 5 }); - const indexes = await prisma.$queryRawUnsafe( + const indexes = (await prisma.$queryRawUnsafe( "SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'EvaluationReport' AND indexdef LIKE '%UNIQUE%'" - ) as Array<{ indexname: string; indexdef: string }>; - const hasUnique = indexes.some((i) => i.indexdef.includes('"inferenceJobId"') && i.indexdef.includes('"inputHash"')); + )) as Array<{ indexname: string; indexdef: string }>; + const hasUnique = indexes.some( + (i) => i.indexdef.includes('"inferenceJobId"') && i.indexdef.includes('"inputHash"') + ); checks.push({ name: 'Unique index for [inferenceJobId, inputHash]', passed: hasUnique }); - const rows = await prisma.$queryRawUnsafe( + const rows = (await prisma.$queryRawUnsafe( 'SELECT "inputHash", "metricsHash", "metricsJson" FROM "EvaluationReport"' - ) as Array>; + )) as Array>; const allHashesValid = rows.every((r) => { const inputHash = r['inputHash'] as string | null; const metricsHash = r['metricsHash'] as string | null; @@ -308,12 +342,18 @@ async function main() { } return true; }); - checks.push({ name: 'All row data consistent with JSON', passed: rows.length === 0 || allHashesValid }); + checks.push({ + name: 'All row data consistent with JSON', + passed: rows.length === 0 || allHashesValid, + }); - const duplicates = await prisma.$queryRawUnsafe( + const duplicates = (await prisma.$queryRawUnsafe( 'SELECT "inferenceJobId", "inputHash", COUNT(*)::int AS cnt FROM "EvaluationReport" GROUP BY "inferenceJobId", "inputHash" HAVING COUNT(*) > 1' - ) as Array<{ inferenceJobId: string; inputHash: string; cnt: number }>; - checks.push({ name: 'No duplicate [inferenceJobId, inputHash] groups', passed: duplicates.length === 0 }); + )) as Array<{ inferenceJobId: string; inputHash: string; cnt: number }>; + checks.push({ + name: 'No duplicate [inferenceJobId, inputHash] groups', + passed: duplicates.length === 0, + }); const allPassed = checks.every((c) => c.passed); results.push({ @@ -321,7 +361,10 @@ async function main() { passed: allPassed, details: allPassed ? 'columns, NOT NULL, unique index, hash consistency, no duplicates' - : checks.filter((c) => !c.passed).map((c) => c.name).join('; '), + : checks + .filter((c) => !c.passed) + .map((c) => c.name) + .join('; '), }); if (allPassed) logPass('Phase 20E harness equivalence: all inline checks passed'); @@ -340,17 +383,33 @@ async function main() { const checks: { name: string; passed: boolean }[] = []; // Check 1: EvaluationReport row exists for demo job - const reportRows = await prisma.$queryRawUnsafe( + const reportRows = (await prisma.$queryRawUnsafe( 'SELECT "id", "datasetVersionId", "algorithmVersion", "iouThreshold", "inputHash", "metricsHash", "metricsJson" FROM "EvaluationReport" WHERE "inferenceJobId" = $1 ORDER BY "createdAt" DESC LIMIT 1', DEMO_JOB_ID - ) as Array<{ id: string; datasetVersionId: string; algorithmVersion: string; iouThreshold: number; inputHash: string; metricsHash: string; metricsJson: Record }>; - checks.push({ name: 'EvaluationReport row exists for demo job', passed: reportRows.length >= 1 }); + )) as Array<{ + id: string; + datasetVersionId: string; + algorithmVersion: string; + iouThreshold: number; + inputHash: string; + metricsHash: string; + metricsJson: Record; + }>; + checks.push({ + name: 'EvaluationReport row exists for demo job', + passed: reportRows.length >= 1, + }); if (reportRows.length >= 1) { const row = reportRows[0]; // Check 2: New DB columns are non-null - const nonNull = row.datasetVersionId !== null && row.algorithmVersion !== null && row.iouThreshold !== null && row.inputHash !== null && row.metricsHash !== null; + const nonNull = + row.datasetVersionId !== null && + row.algorithmVersion !== null && + row.iouThreshold !== null && + row.inputHash !== null && + row.metricsHash !== null; checks.push({ name: 'New DB columns non-null', passed: nonNull }); // Check 3: row.inputHash === metricsJson.inputHash @@ -368,17 +427,20 @@ async function main() { } // Check 6: Predictions exist - const predCount = await prisma.$queryRawUnsafe( + const predCount = (await prisma.$queryRawUnsafe( 'SELECT COUNT(*)::bigint AS cnt FROM "Prediction"' - ) as Array<{ cnt: bigint }>; + )) as Array<{ cnt: bigint }>; checks.push({ name: 'Predictions exist', passed: Number(predCount[0]?.cnt ?? 0) > 0 }); // Check 7: No stale QUEUED/RUNNING seeded jobs for demo project - const staleJobs = await prisma.$queryRawUnsafe( + const staleJobs = (await prisma.$queryRawUnsafe( 'SELECT "id" FROM "InferenceJob" WHERE "projectId" = $1 AND "status" IN (\'QUEUED\',\'RUNNING\') LIMIT 1', 'proj_parking_lot' - ) as Array<{ id: string }>; - checks.push({ name: 'No stale QUEUED/RUNNING jobs for demo project', passed: staleJobs.length === 0 }); + )) as Array<{ id: string }>; + checks.push({ + name: 'No stale QUEUED/RUNNING jobs for demo project', + passed: staleJobs.length === 0, + }); const allPassed = checks.every((c) => c.passed); results.push({ @@ -386,7 +448,10 @@ async function main() { passed: allPassed, details: allPassed ? 'report exists, all columns non-null, hashes valid, predictions exist, no stale jobs' - : checks.filter((c) => !c.passed).map((c) => c.name).join('; '), + : checks + .filter((c) => !c.passed) + .map((c) => c.name) + .join('; '), }); if (allPassed) logPass('Phase 20D harness equivalence: all inline checks passed'); @@ -404,28 +469,34 @@ async function main() { const checks: { name: string; passed: boolean }[] = []; // Check 1: Dataset version is LOCKED - const dvLocked = await prisma.$queryRawUnsafe( - "SELECT \"id\" FROM \"DatasetVersion\" WHERE \"status\" = 'LOCKED' LIMIT 1" - ) as Array<{ id: string }>; + const dvLocked = (await prisma.$queryRawUnsafe( + 'SELECT "id" FROM "DatasetVersion" WHERE "status" = \'LOCKED\' LIMIT 1' + )) as Array<{ id: string }>; checks.push({ name: 'Dataset version is LOCKED', passed: dvLocked.length >= 1 }); // Check 2: InferenceJob is SUCCEEDED - const jobSucc = await prisma.$queryRawUnsafe( - "SELECT \"id\" FROM \"InferenceJob\" WHERE \"status\" = 'SUCCEEDED' LIMIT 1" - ) as Array<{ id: string }>; - checks.push({ name: 'At least one SUCCEEDED InferenceJob exists', passed: jobSucc.length >= 1 }); + const jobSucc = (await prisma.$queryRawUnsafe( + 'SELECT "id" FROM "InferenceJob" WHERE "status" = \'SUCCEEDED\' LIMIT 1' + )) as Array<{ id: string }>; + checks.push({ + name: 'At least one SUCCEEDED InferenceJob exists', + passed: jobSucc.length >= 1, + }); // Check 3: Predictions found (>0) - const predCount = await prisma.$queryRawUnsafe( + const predCount = (await prisma.$queryRawUnsafe( 'SELECT COUNT(*)::bigint AS cnt FROM "Prediction"' - ) as Array<{ cnt: bigint }>; + )) as Array<{ cnt: bigint }>; checks.push({ name: 'Predictions found (>0)', passed: Number(predCount[0]?.cnt ?? 0) > 0 }); // Check 4: EvaluationReport found (>0) - const reportCount = await prisma.$queryRawUnsafe( + const reportCount = (await prisma.$queryRawUnsafe( 'SELECT COUNT(*)::bigint AS cnt FROM "EvaluationReport"' - ) as Array<{ cnt: bigint }>; - checks.push({ name: 'EvaluationReport found (>0)', passed: Number(reportCount[0]?.cnt ?? 0) > 0 }); + )) as Array<{ cnt: bigint }>; + checks.push({ + name: 'EvaluationReport found (>0)', + passed: Number(reportCount[0]?.cnt ?? 0) > 0, + }); const allPassed = checks.every((c) => c.passed); results.push({ @@ -433,7 +504,10 @@ async function main() { passed: allPassed, details: allPassed ? 'dataset locked, job succeeded, predictions found, report exists' - : checks.filter((c) => !c.passed).map((c) => c.name).join('; '), + : checks + .filter((c) => !c.passed) + .map((c) => c.name) + .join('; '), }); if (allPassed) logPass('Phase 20C harness equivalence: all inline checks passed'); diff --git a/scripts/harness/phase22a-fixture-infrastructure-check.ts b/scripts/harness/phase22a-fixture-infrastructure-check.ts index 2ea10161..d8a81652 100644 --- a/scripts/harness/phase22a-fixture-infrastructure-check.ts +++ b/scripts/harness/phase22a-fixture-infrastructure-check.ts @@ -81,12 +81,8 @@ async function main() { if (!process.env.DATABASE_URL) { if (strict) { - logFail( - 'DATABASE_URL not configured — STRICT mode requires database connection.', - ); - logFail( - 'Fix: set DATABASE_URL in .env or export DATABASE_URL=', - ); + logFail('DATABASE_URL not configured — STRICT mode requires database connection.'); + logFail('Fix: set DATABASE_URL in .env or export DATABASE_URL='); process.exit(1); } logSkip('DATABASE_URL not configured — DB checks skipped.'); @@ -108,7 +104,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT id, name FROM "Project" WHERE id = $1', - F.project.id, + F.project.id )) as Array<{ id: string; name: string }>; const passed = rows.length === 1 && rows[0].id === F.project.id; @@ -125,7 +121,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT id FROM "Dataset" WHERE id = $1', - F.dataset.id, + F.dataset.id )) as Array<{ id: string }>; const passed = rows.length === 1; @@ -142,7 +138,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT id, status FROM "DatasetVersion" WHERE id = $1', - F.datasetVersion.id, + F.datasetVersion.id )) as Array<{ id: string; status: string }>; const passed = rows.length === 1 && String(rows[0].status) === 'LOCKED'; @@ -155,8 +151,7 @@ async function main() { ? 'NOT FOUND' : `status=${rows[0].status} (expected LOCKED)`, }); - if (passed) - logPass(`Dataset version ${F.datasetVersion.id} is LOCKED`); + if (passed) logPass(`Dataset version ${F.datasetVersion.id} is LOCKED`); else logFail(`Dataset version status: ${rows[0]?.status ?? 'NOT FOUND'}`); } @@ -164,7 +159,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT COUNT(*)::int AS cnt FROM "DatasetVersionAsset" WHERE "datasetVersionId" = $1', - F.datasetVersion.id, + F.datasetVersion.id )) as Array<{ cnt: number }>; const passed = rows.length === 1 && rows[0].cnt >= 3; @@ -181,7 +176,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT id, width, height FROM "MediaAsset" WHERE id = $1', - F.annotationWorkspace.assetId, + F.annotationWorkspace.assetId )) as Array<{ id: string; width: number; height: number }>; const passed = rows.length === 1; @@ -192,8 +187,7 @@ async function main() { ? `${rows[0].width}x${rows[0].height}` : `${F.annotationWorkspace.assetId} NOT FOUND`, }); - if (passed) - logPass(`Annotation workspace asset ${F.annotationWorkspace.assetId} exists`); + if (passed) logPass(`Annotation workspace asset ${F.annotationWorkspace.assetId} exists`); else logFail(`Asset ${F.annotationWorkspace.assetId} NOT FOUND`); } @@ -201,7 +195,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT id FROM "AnnotationSet" WHERE id = $1', - F.annotationWorkspace.annotationSetId, + F.annotationWorkspace.annotationSetId )) as Array<{ id: string }>; const passed = rows.length === 1; @@ -220,7 +214,7 @@ async function main() { 'SELECT id, "labelClassId", source FROM "Annotation" WHERE "annotationSetId" = $1 AND "assetId" = $2 AND source::text = $3', F.annotationWorkspace.annotationSetId, F.annotationWorkspace.assetId, - 'MANUAL', + 'MANUAL' )) as Array<{ id: string; labelClassId: string; source: string }>; const passed = rows.length >= 1; @@ -238,7 +232,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT id, name, "definitionJson" FROM "Pipeline" WHERE id = $1', - F.pipeline.id, + F.pipeline.id )) as Array<{ id: string; name: string; @@ -259,7 +253,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT "definitionJson" FROM "Pipeline" WHERE id = $1', - F.pipeline.id, + F.pipeline.id )) as Array<{ definitionJson: Record }>; let passed = false; @@ -289,7 +283,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT id, name, runtime, "configJson" FROM "ModelArtifact" WHERE id = $1', - F.modelArtifact.id, + F.modelArtifact.id )) as Array<{ id: string; name: string; @@ -315,7 +309,7 @@ async function main() { const rows = (await prisma.$queryRawUnsafe( 'SELECT id, status FROM "InferenceJob" WHERE id = $1 AND status::text = $2', F.inferenceJob.id, - 'SUCCEEDED', + 'SUCCEEDED' )) as Array<{ id: string; status: string }>; const passed = rows.length === 1; @@ -332,7 +326,7 @@ async function main() { { const rows = (await prisma.$queryRawUnsafe( 'SELECT COUNT(*)::int AS cnt FROM "Prediction" WHERE "inferenceJobId" = $1', - F.inferenceJob.id, + F.inferenceJob.id )) as Array<{ cnt: number }>; const passed = rows.length === 1 && rows[0].cnt >= 3; @@ -341,8 +335,7 @@ async function main() { passed, details: passed ? `${rows[0].cnt} predictions` : `${rows[0]?.cnt ?? 0} predictions`, }); - if (passed) - logPass(`${rows[0].cnt} predictions exist for ${F.inferenceJob.id}`); + if (passed) logPass(`${rows[0].cnt} predictions exist for ${F.inferenceJob.id}`); else logFail(`${rows[0]?.cnt ?? 0} predictions (expected >= 3)`); } @@ -354,7 +347,7 @@ async function main() { FROM "EvaluationReport" WHERE "inferenceJobId" = $1 ORDER BY "createdAt" DESC LIMIT 1`, - F.inferenceJob.id, + F.inferenceJob.id )) as Array<{ id: string; datasetVersionId: string; @@ -387,19 +380,21 @@ async function main() { const rows = (await prisma.$queryRawUnsafe( `SELECT id, status FROM "InferenceJob" WHERE "projectId" = $1 AND status::text IN ('QUEUED','RUNNING')`, - F.project.id, + F.project.id )) as Array<{ id: string; status: string }>; const passed = rows.length === 0; results.push({ name: 'No stale QUEUED/RUNNING jobs for demo project', passed, - details: passed ? 'none found' : `${rows.length} stale: ${rows.map((j) => j.id).join(', ')}`, + details: passed + ? 'none found' + : `${rows.length} stale: ${rows.map((j) => j.id).join(', ')}`, }); if (passed) logPass('No stale QUEUED/RUNNING jobs'); else logFail( - `${rows.length} stale job(s): ${rows.map((j) => `${j.id}(${j.status})`).join(', ')}`, + `${rows.length} stale job(s): ${rows.map((j) => `${j.id}(${j.status})`).join(', ')}` ); } @@ -411,7 +406,7 @@ async function main() { FROM "EvaluationReport" WHERE "inferenceJobId" = $1 ORDER BY "createdAt" DESC LIMIT 1`, - F.inferenceJob.id, + F.inferenceJob.id )) as Array<{ inputHash: string; metricsHash: string; @@ -458,7 +453,7 @@ async function main() { "algorithmVersion", "iouThreshold", "inputHash", "metricsHash" FROM "EvaluationReport" WHERE "inferenceJobId" = $1 LIMIT 1`, - F.inferenceJob.id, + F.inferenceJob.id )) as Array<{ datasetVersionId: string | null; pipelineId: string | null; @@ -481,8 +476,7 @@ async function main() { passed, details: passed ? 'all required columns non-null' : 'some integrity columns are null', }); - if (passed) - logPass('Phase 20D equivalence: all integrity columns non-null'); + if (passed) logPass('Phase 20D equivalence: all integrity columns non-null'); else logFail('Phase 20D equivalence: some integrity columns are NULL'); } @@ -494,7 +488,7 @@ async function main() { AND column_name IN ( 'datasetVersionId', 'pipelineId', 'modelId', 'algorithmVersion', 'iouThreshold', 'inputHash', 'metricsHash' - )`, + )` )) as Array<{ column_name: string }>; const requiredCols = [ @@ -514,8 +508,7 @@ async function main() { passed, details: passed ? requiredCols.join(', ') : `missing: ${missing.join(', ')}`, }); - if (passed) - logPass('Phase 20E equivalence: all 7 migration columns present'); + if (passed) logPass('Phase 20E equivalence: all 7 migration columns present'); else logFail(`Phase 20E equivalence: missing columns: ${missing.join(', ')}`); } @@ -524,7 +517,7 @@ async function main() { const rows = (await prisma.$queryRawUnsafe( `SELECT migration_name, finished_at, rolled_back_at FROM _prisma_migrations - WHERE finished_at IS NULL AND rolled_back_at IS NULL`, + WHERE finished_at IS NULL AND rolled_back_at IS NULL` )) as Array<{ migration_name: string; finished_at: string | null; @@ -540,10 +533,7 @@ async function main() { : `${rows.length} unsettled: ${rows.map((m) => m.migration_name).join(', ')}`, }); if (passed) logPass('Phase 20F equivalence: no stale migrations'); - else - logFail( - `Phase 20F equivalence: ${rows.length} unsettled migration(s)`, - ); + else logFail(`Phase 20F equivalence: ${rows.length} unsettled migration(s)`); } printResults(prisma, results); diff --git a/scripts/harness/phase22b-meta-harness.ts b/scripts/harness/phase22b-meta-harness.ts index 60ef2015..81337576 100644 --- a/scripts/harness/phase22b-meta-harness.ts +++ b/scripts/harness/phase22b-meta-harness.ts @@ -97,9 +97,7 @@ function createTimeoutSignal(ms: number): AbortSignal { async function isApiReachable(): Promise { // Harness uses API_BASE_URL (prefix-included). Frontend uses VITE_API_BASE_URL (host-only). // These are different conventions — do NOT fall back from one to the other. - const API_BASE_URL = - process.env.API_BASE_URL || - 'http://localhost:3000/api'; + const API_BASE_URL = process.env.API_BASE_URL || 'http://localhost:3000/api'; try { const res = await fetch(`${API_BASE_URL.replace(/\/$/, '')}/health`, { @@ -125,7 +123,8 @@ async function main() { if (shouldRunApiHarness) { logInfo(`API appears reachable — Phase 22B API harness will run.`); if (withApi) logInfo(`--with-api flag explicitly set.`); - if (apiReachable && !withApi) logInfo(`(auto-detected, override with --with-api to suppress warning)`); + if (apiReachable && !withApi) + logInfo(`(auto-detected, override with --with-api to suppress warning)`); } else { logInfo(`API not reachable — Phase 22B API harness will be skipped.`); logInfo(`Pass --with-api to attempt anyway, or start the stack first.`); @@ -154,7 +153,9 @@ async function main() { if (phase22aMeta.passed) { logPass(`phase22a-meta-harness PASSED (${phase22aMeta.durationMs}ms)`); } else { - logFail(`phase22a-meta-harness FAILED (${phase22aMeta.durationMs}ms) — ${phase22aMeta.error}`); + logFail( + `phase22a-meta-harness FAILED (${phase22aMeta.durationMs}ms) — ${phase22aMeta.error}` + ); } } } diff --git a/scripts/harness/phase22b-production-path-api-check.ts b/scripts/harness/phase22b-production-path-api-check.ts index 01e64018..43ee2845 100644 --- a/scripts/harness/phase22b-production-path-api-check.ts +++ b/scripts/harness/phase22b-production-path-api-check.ts @@ -65,9 +65,7 @@ function logInfo(msg: string) { // API_BASE_URL: harness scripts use /api-prefixed paths (e.g. /health, /projects/...). // This differs from the frontend convention where paths include /api/ and BASE_URL is host-only. // The harness therefore uses a dedicated API_BASE_URL env var (not VITE_API_BASE_URL). -const API_BASE_URL = - process.env.API_BASE_URL || - 'http://localhost:3000/api'; +const API_BASE_URL = process.env.API_BASE_URL || 'http://localhost:3000/api'; interface CheckResult { name: string; @@ -83,7 +81,9 @@ function createTimeoutSignal(ms: number): AbortSignal { return controller.signal; } -async function apiGet(path: string): Promise<{ ok: boolean; status: number; data?: T; error?: string }> { +async function apiGet( + path: string +): Promise<{ ok: boolean; status: number; data?: T; error?: string }> { try { const url = `${API_BASE_URL.replace(/\/$/, '')}${path}`; const res = await fetch(url, { @@ -93,7 +93,11 @@ async function apiGet(path: string): Promise<{ ok: boolean; status: let data: T | undefined; const contentType = res.headers.get('content-type') || ''; if (contentType.includes('application/json')) { - try { data = await res.json() as T; } catch { /* ignore */ } + try { + data = (await res.json()) as T; + } catch { + /* ignore */ + } } return { ok: res.ok, status: res.status, data, error: undefined }; } catch (err) { @@ -113,15 +117,28 @@ async function checkHealth(results: CheckResult[]) { } const d = r.data; const ok = d?.ok === true && d?.service === 'visionflow-api'; - results.push({ name: 'GET /api/health', passed: ok, details: ok ? `${d?.service} at ${d?.time}` : JSON.stringify(d) }); + results.push({ + name: 'GET /api/health', + passed: ok, + details: ok ? `${d?.service} at ${d?.time}` : JSON.stringify(d), + }); if (ok) logPass(`ok=${d.ok}, service=${d.service}`); else logFail(`Expected ok=true, service=visionflow-api — got: ${JSON.stringify(d)}`); } async function checkRuntimeStatus(results: CheckResult[]) { - const r = await apiGet<{ api: { ok: boolean; mode: string }; database: { ok: boolean | null; status: string }; queue: { ok: boolean | null; mode: string; status: string }; cvWorker: { ok: boolean; configured: boolean; activeDetectorMode: string | null } }>('/health/runtime/status'); + const r = await apiGet<{ + api: { ok: boolean; mode: string }; + database: { ok: boolean | null; status: string }; + queue: { ok: boolean | null; mode: string; status: string }; + cvWorker: { ok: boolean; configured: boolean; activeDetectorMode: string | null }; + }>('/health/runtime/status'); if (!r.ok) { - results.push({ name: 'GET /api/health/runtime/status', passed: false, details: `HTTP ${r.status}` }); + results.push({ + name: 'GET /api/health/runtime/status', + passed: false, + details: `HTTP ${r.status}`, + }); logFail(`HTTP ${r.status}`); return; } @@ -132,7 +149,9 @@ async function checkRuntimeStatus(results: CheckResult[]) { results.push({ name: 'GET /api/health/runtime/status', passed: ok, - details: ok ? `api=${d.api.mode}, db=${d.database.status}, queue=${d.queue.status}` : JSON.stringify(d), + details: ok + ? `api=${d.api.mode}, db=${d.database.status}, queue=${d.queue.status}` + : JSON.stringify(d), }); if (ok) logPass(`api=${d.api.mode}, db=${d.database.status}, queue=${d.queue.status}`); else logFail(JSON.stringify(d)); @@ -140,9 +159,15 @@ async function checkRuntimeStatus(results: CheckResult[]) { async function checkDatasetList(results: CheckResult[]) { const projectId = F.project.id; - const r = await apiGet<{ datasets: Array<{ id: string; name: string; versionCount: number }> }>(`/projects/${projectId}/datasets`); + const r = await apiGet<{ datasets: Array<{ id: string; name: string; versionCount: number }> }>( + `/projects/${projectId}/datasets` + ); if (!r.ok) { - results.push({ name: 'GET /api/projects/:projectId/datasets', passed: false, details: `HTTP ${r.status}` }); + results.push({ + name: 'GET /api/projects/:projectId/datasets', + passed: false, + details: `HTTP ${r.status}`, + }); logFail(`HTTP ${r.status}`); return; } @@ -152,10 +177,15 @@ async function checkDatasetList(results: CheckResult[]) { results.push({ name: 'GET /api/projects/:projectId/datasets', passed: ok, - details: ok ? `found dataset ${F.dataset.id}` : `canonical dataset NOT FOUND — got: ${JSON.stringify(datasets.map((d) => d.id))}`, + details: ok + ? `found dataset ${F.dataset.id}` + : `canonical dataset NOT FOUND — got: ${JSON.stringify(datasets.map((d) => d.id))}`, }); if (ok) logPass(`canonical dataset ${F.dataset.id} (${canonical.name}) found`); - else logFail(`canonical dataset ${F.dataset.id} not in list: ${JSON.stringify(datasets.map((d) => d.id))}`); + else + logFail( + `canonical dataset ${F.dataset.id} not in list: ${JSON.stringify(datasets.map((d) => d.id))}` + ); } async function checkAnnotationWorkspace(results: CheckResult[]) { @@ -169,7 +199,11 @@ async function checkAnnotationWorkspace(results: CheckResult[]) { }>(url); if (!r.ok) { - results.push({ name: 'GET /api/.../annotation-workspace', passed: false, details: `HTTP ${r.status}` }); + results.push({ + name: 'GET /api/.../annotation-workspace', + passed: false, + details: `HTTP ${r.status}`, + }); logFail(`HTTP ${r.status}`); return; } @@ -186,7 +220,10 @@ async function checkAnnotationWorkspace(results: CheckResult[]) { : `annotationSet=${d.annotationSet?.id ?? 'null'}, MANUAL annotations=${manualAnnotations.length}`, }); if (ok) logPass(`${manualAnnotations.length} MANUAL annotation(s) in workspace`); - else logFail(`annotationSet=${d.annotationSet?.id ?? 'null'}, MANUAL annotations=${manualAnnotations.length}`); + else + logFail( + `annotationSet=${d.annotationSet?.id ?? 'null'}, MANUAL annotations=${manualAnnotations.length}` + ); } async function checkCocoExport(results: CheckResult[]) { @@ -195,8 +232,12 @@ async function checkCocoExport(results: CheckResult[]) { // Call twice to verify determinism const [r1, r2] = await Promise.all([ - apiGet>(`/projects/${projectId}/dataset-versions/${versionId}/export/coco`), - apiGet>(`/projects/${projectId}/dataset-versions/${versionId}/export/coco`), + apiGet>( + `/projects/${projectId}/dataset-versions/${versionId}/export/coco` + ), + apiGet>( + `/projects/${projectId}/dataset-versions/${versionId}/export/coco` + ), ]); if (!r1.ok || !r2.ok) { @@ -237,15 +278,23 @@ async function checkCocoExport(results: CheckResult[]) { else { logFail(`status=${status} (expected LOCKED)`); logFail(`hash1=${hash1}, hash2=${hash2} (expected equal and non-empty)`); - logFail(`images=${images?.length} (expected >= 3), categories=${categories?.length} (expected >= 3)`); + logFail( + `images=${images?.length} (expected >= 3), categories=${categories?.length} (expected >= 3)` + ); } } async function checkInferenceJobs(results: CheckResult[]) { const projectId = F.project.id; - const r = await apiGet<{ jobs: Array<{ id: string; status: string }> }>(`/projects/${projectId}/inference-jobs`); + const r = await apiGet<{ jobs: Array<{ id: string; status: string }> }>( + `/projects/${projectId}/inference-jobs` + ); if (!r.ok) { - results.push({ name: 'GET /api/.../inference-jobs', passed: false, details: `HTTP ${r.status}` }); + results.push({ + name: 'GET /api/.../inference-jobs', + passed: false, + details: `HTTP ${r.status}`, + }); logFail(`HTTP ${r.status}`); return; } @@ -266,7 +315,9 @@ async function checkInferenceJobs(results: CheckResult[]) { async function checkPredictions(results: CheckResult[]) { const projectId = F.project.id; const jobId = F.inferenceJob.id; - const r = await apiGet<{ predictions: Array<{ id: string }> }>(`/projects/${projectId}/inference-jobs/${jobId}/predictions`); + const r = await apiGet<{ predictions: Array<{ id: string }> }>( + `/projects/${projectId}/inference-jobs/${jobId}/predictions` + ); if (!r.ok) { results.push({ name: 'GET /api/.../predictions', passed: false, details: `HTTP ${r.status}` }); logFail(`HTTP ${r.status}`); @@ -277,7 +328,9 @@ async function checkPredictions(results: CheckResult[]) { results.push({ name: 'GET /api/.../predictions', passed: ok, - details: ok ? `${predictions.length} predictions` : `only ${predictions.length} predictions (expected >= 3)`, + details: ok + ? `${predictions.length} predictions` + : `only ${predictions.length} predictions (expected >= 3)`, }); if (ok) logPass(`${predictions.length} predictions found`); else logFail(`expected >= 3 predictions, got ${predictions.length}`); @@ -286,9 +339,9 @@ async function checkPredictions(results: CheckResult[]) { async function checkEvaluationReport(results: CheckResult[]) { const projectId = F.project.id; const jobId = F.inferenceJob.id; - const r = await apiGet<{ report: { inputHash: string; metricsHash: string; jobId: string } | null }>( - `/projects/${projectId}/inference-jobs/${jobId}/evaluation` - ); + const r = await apiGet<{ + report: { inputHash: string; metricsHash: string; jobId: string } | null; + }>(`/projects/${projectId}/inference-jobs/${jobId}/evaluation`); if (!r.ok) { results.push({ name: 'GET /api/.../evaluation', passed: false, details: `HTTP ${r.status}` }); logFail(`HTTP ${r.status}`); diff --git a/scripts/harness/phase23-full-e2e-check.ts b/scripts/harness/phase23-full-e2e-check.ts index 3918e494..27d11058 100644 --- a/scripts/harness/phase23-full-e2e-check.ts +++ b/scripts/harness/phase23-full-e2e-check.ts @@ -60,11 +60,7 @@ interface HarnessResult { error?: string; } -function runHarness( - cmd: string, - label: string, - cwd?: string, -): HarnessResult { +function runHarness(cmd: string, label: string, cwd?: string): HarnessResult { const start = Date.now(); log(`Running: ${cmd}`); try { @@ -96,8 +92,7 @@ function createTimeoutSignal(ms: number): AbortSignal { } async function isApiReachable(): Promise { - const API_BASE_URL = - process.env.API_BASE_URL || 'http://localhost:3000/api'; + const API_BASE_URL = process.env.API_BASE_URL || 'http://localhost:3000/api'; try { const res = await fetch(`${API_BASE_URL.replace(/\/$/, '')}/health`, { signal: createTimeoutSignal(5_000), @@ -109,8 +104,7 @@ async function isApiReachable(): Promise { } async function isWebReachable(): Promise { - const WEB_BASE_URL = - process.env.VITE_WEB_BASE_URL || 'http://localhost:5173'; + const WEB_BASE_URL = process.env.VITE_WEB_BASE_URL || 'http://localhost:5173'; try { const res = await fetch(WEB_BASE_URL, { signal: createTimeoutSignal(5_000), @@ -151,10 +145,7 @@ async function main() { // ── Preflight: check stack reachability ──────────────────────────────────── console.log(''); - const [apiReachable, webReachable] = await Promise.all([ - isApiReachable(), - isWebReachable(), - ]); + const [apiReachable, webReachable] = await Promise.all([isApiReachable(), isWebReachable()]); if (!apiReachable || !webReachable) { if (strict) { @@ -181,7 +172,7 @@ async function main() { const phase22bResult = runHarness( 'pnpm meta:harness:phase22b -- --strict --with-api', - 'phase22b-meta-harness', + 'phase22b-meta-harness' ); allResults.push(phase22bResult); @@ -189,7 +180,7 @@ async function main() { logPass(`phase22b-meta-harness PASSED (${phase22bResult.durationMs}ms)`); } else { logFail( - `phase22b-meta-harness FAILED (${phase22bResult.durationMs}ms) — ${phase22bResult.error}`, + `phase22b-meta-harness FAILED (${phase22bResult.durationMs}ms) — ${phase22bResult.error}` ); console.log(''); logFail('Phase 22B meta-harness must pass before Phase 23 Playwright tests run.'); @@ -206,7 +197,7 @@ async function main() { const playwrightResult = runHarness( 'pnpm exec playwright test e2e/full-vertical-slice.spec.ts', 'playwright-full-vertical-slice', - webDir, + webDir ); allResults.push(playwrightResult); @@ -214,7 +205,7 @@ async function main() { logPass(`playwright-full-vertical-slice PASSED (${playwrightResult.durationMs}ms)`); } else { logFail( - `playwright-full-vertical-slice FAILED (${playwrightResult.durationMs}ms) — ${playwrightResult.error}`, + `playwright-full-vertical-slice FAILED (${playwrightResult.durationMs}ms) — ${playwrightResult.error}` ); } @@ -243,9 +234,7 @@ async function main() { .map((r) => r.name) .join(', '); console.log(''); - logFail( - `Phase 23 meta harness FAILED — ${failed} harness(es) failed: ${failedNames}`, - ); + logFail(`Phase 23 meta harness FAILED — ${failed} harness(es) failed: ${failedNames}`); process.exit(1); } diff --git a/scripts/reset-schema.sql.ts b/scripts/reset-schema.sql.ts index 42edc4e0..6ca79491 100644 --- a/scripts/reset-schema.sql.ts +++ b/scripts/reset-schema.sql.ts @@ -6,4 +6,7 @@ async function reset() { console.log('Schema reset complete'); await prisma.$disconnect(); } -reset().catch(e => { console.error(e); process.exit(1); }); +reset().catch((e) => { + console.error(e); + process.exit(1); +});