From bd8ca9833b8ea3afdfd788b8d97f02cc6f1e89a3 Mon Sep 17 00:00:00 2001 From: KayzenRoot <114633702+KayzenRoot@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:06:03 -0300 Subject: [PATCH 1/5] chore(wo-014): preparar release e runner de migrations hosted --- docs/V2_RELEASE_WO014.md | 64 +++++++++++++++++++++ docs/evidence/wo-014/tests.txt | 55 ++++++++++++++++++ package.json | 1 + scripts/apply-hosted-migrations.mjs | 89 +++++++++++++++++++++++++++++ 4 files changed, 209 insertions(+) create mode 100644 docs/V2_RELEASE_WO014.md create mode 100644 docs/evidence/wo-014/tests.txt create mode 100644 scripts/apply-hosted-migrations.mjs diff --git a/docs/V2_RELEASE_WO014.md b/docs/V2_RELEASE_WO014.md new file mode 100644 index 00000000..b463ca30 --- /dev/null +++ b/docs/V2_RELEASE_WO014.md @@ -0,0 +1,64 @@ +# DIF-V2-WO-014 — Release V2: regressão integral, auditoria e deploy validado + +**Issue:** #31 · **Branch:** `feat/dif-v2-wo-014` · **Base:** `main` `7c175e5` +**Status:** **BLOCKED** — código/testes/regressão prontos; o deploy validado não pode concluir sem migrations no Supabase hospedado. O Vercel já serve o código V2, mas o projeto hospedado ainda tem apenas o schema V1. + +## Pré-requisitos atendidos + +- WO-001–013 e WO-015–021 **PROMOTED**, com checkpoints reconciliados; OPS 015–021 **PROMOTED** (`c7490e8`). +- `main` `7c175e5` com CI docs-only PASS; code/test head V2 `f32cc97` com CI `44776291945` PASS; OPS `77d5626` com CI `44787029917` PASS. +- Unit **351 + 3 skipped**, PgTAP **247/247**, policy **36/41**, E2E **19/19**, Sonar/Socket PASS. +- Backup/restore local executado (41/41 contagens, SHA, join 768, QA 5/5). +- Worker/render local e ARM64 benchmark das WOs anteriores aprovados. +- Sem HIGH/CRITICAL conhecido; auditorias independentes finais de WO-021 e OPS **APPROVED WITH RESIDUALS**. + +## Bloqueio atual (produção) + +- `https://dif-studio.vercel.app/health` → 200; `/login` → 200; `/app`, `/app/series`, `/app/episodes` → 200 com owner real. +- `https://dif-studio.vercel.app/app/style` → **HTTP 500** para o owner; o projeto Supabase hospedado `zottgifcocnjguhmnezx` não tem as tabelas V2 (`GET /rest/v1/style_presets` → PGRST205). +- O workspace não tem Supabase PAT nem database password: + - `npx supabase projects list` → “Invalid access token”; + - não existe `C:\Users\csn19\.zcode\dif-secrets\supabase-pat.txt`; + - não há Vercel CLI autenticado (o deploy Vercel vem da integração Git). +- Sem credencial não é possível aplicar as **29 migrations V2** (`20261112170000`–`20261120132000`) nem executar o smoke de produção. Não há caminho DDL via PostgREST/anon. + +## Como desbloquear + +1. O owner fornece um PAT Supabase (`sbp_...`) em `C:\Users\csn19\.zcode\dif-secrets\supabase-pat.txt` **ou** roda `npx supabase login`/`link --project-ref zottgifcocnjguhmnezx` **ou** fornece a database password por arquivo privado. +2. Antes de aplicar, gerar backup do schema hospedado (Management API/`pg_dump`) e confirmar que o schema atual é V1. +3. Dry-run: + ```sh + SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx node scripts/apply-hosted-migrations.mjs + ``` +4. Executar: + ```sh + SUPABASE_ACCESS_TOKEN=... SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx \ + node scripts/apply-hosted-migrations.mjs --execute + ``` + O script recusa se detectar schema V2 já presente, aplica em ordem e exige 41 tabelas públicas. +5. Smoke: `/health`, `/login`, owner login, `/app/style`, `/app/timeline`, upload R2, download privado, render worker, MP4 1080×1920, backup/rollback. +6. Só depois promover o checkpoint final para **APROVADO**. + +## Script de migrations + +`scripts/apply-hosted-migrations.mjs`: + +- dry-run por padrão; `--execute` explícito; +- exige PAT `sbp_...` e project ref de 20 caracteres; +- recusa se `video_assets`, `video_edit_plans`, `render_jobs` ou `style_presets` já existirem; +- aplica somente migrations a partir de `--from` (default `20261112170000`), em ordem; +- não imprime token nem SQL; falha com HTTP/status e trecho sanitizado; +- confere 41 tabelas públicas ao final. + +## Pendências humanas/operacionais + +- Aceitação real do owner com episódio Flow 90–150 s, 15 clipes, narração, SFX/música, legendas, CTA/2 escolhas, MP4 revisado (QA humano de som/imagem). +- Configurar/validar envs R2 no Vercel Production e worker isolado autorizado. +- Backup hospedado antes das migrations e ensaio de rollback/roll-forward. +- Cloudinary secret rotation e smoke de mídia privada. + +## Riscos + +- V2 code em produção sem schema V2 deixa rotas novas em 500 (V1 core continua 200). Não declarar release completa. +- Migrations são aditivas, mas devem ser aplicadas com backup e em ordem; o script falha fechado. +- Sem Vercel CLI, rollback de alias depende do dashboard/integração Git. diff --git a/docs/evidence/wo-014/tests.txt b/docs/evidence/wo-014/tests.txt new file mode 100644 index 00000000..bc63c87e --- /dev/null +++ b/docs/evidence/wo-014/tests.txt @@ -0,0 +1,55 @@ +# DIF-V2-WO-014 — release evidence + +Date: 2026-11-20 (America/Sao_Paulo) +Branch: `feat/dif-v2-wo-014` (base `main` `7c175e5`) + +## Local/CI baseline + +- `main` code/test head V2 `f32cc97`: CI `44776291945` PASS — unit **351+3**, + PgTAP **247/247**, policy 35/41, E2E **19/19**, Sonar PASS. +- OPS head `77d5626`: CI `44787029917` PASS — unit **351+3**, PgTAP **247/247**, + policy **36/41**, E2E **19/19**, Sonar PASS. +- `main` docs checkpoints: `3950ccb` (WO-021) and `7c175e5` (OPS) CI PASS. +- Backup/restore local: 41/41 table counts, SHA verified, join 768, QA 5/5, + metadata/coverage OK; media fail-closed for 3 absent temp MP4s. + +## Production observations (2026-11-20) + +Authenticated owner session against `https://dif-studio.vercel.app`: + +| Route | Status | +| --- | --- | +| `/health` | 200 | +| `/login` | 200 | +| `/app` | 200 | +| `/app/series` | 200 | +| `/app/episodes` | 200 | +| `/timeline` | timed out / V2 data unavailable | +| `/app/style` | **500 Internal Error** | + +Hosted Supabase `zottgifcocnjguhmnezx`: + +- `GET /rest/v1/style_presets` → HTTP 404 `PGRST205` (table missing); +- same for `cover_revisions` and other V2 tables; +- V1 tables/services remain reachable through the app. + +## Credential preflight + +- `npx supabase projects list` → `Invalid access token`. +- No `supabase-pat.txt` in `C:\Users\csn19\.zcode\dif-secrets`. +- No Vercel CLI credentials; production deploys come from the Git integration. +- Therefore the 29 V2 migrations cannot be applied and the release is **BLOCKED**. + +## Migration runner dry-run + +`SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx node scripts/apply-hosted-migrations.mjs` +lists **29 migrations** from `20261112170000` and performs no network write in +dry-run. `--execute` requires an owner PAT `sbp_...` and refuses if V2 markers +already exist. + +## Not yet executed + +- Hosted migration apply/backup and production smoke. +- Worker isolated deployment/authorization. +- Real owner 90–150 s Flow acceptance and human AV QA. +- R2 lifecycle/GC, remote restore, Auth restore. diff --git a/package.json b/package.json index 8db5d3ba..87101822 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,7 @@ "test:e2e:local": "node scripts/test-local-e2e.mjs", "check:r2": "node scripts/check-r2.mjs", "backup:metadata": "node scripts/backup-metadata.mjs", + "db:apply-hosted": "node scripts/apply-hosted-migrations.mjs", "restore:metadata": "node scripts/restore-metadata.mjs", "retention": "node scripts/retention.mjs", "audit:policy": "node scripts/audit-policy.mjs", diff --git a/scripts/apply-hosted-migrations.mjs b/scripts/apply-hosted-migrations.mjs new file mode 100644 index 00000000..66fd7e06 --- /dev/null +++ b/scripts/apply-hosted-migrations.mjs @@ -0,0 +1,89 @@ +#!/usr/bin/env node +// Applies the additive V2 migrations to the hosted Supabase project through the +// Management API. Dry-run is the default. Requires an owner-provided PAT: +// SUPABASE_ACCESS_TOKEN=... SUPABASE_PROJECT_REF=... \ +// node scripts/apply-hosted-migrations.mjs --execute +// Never prints the token or full SQL responses. +import { readdir, readFile } from 'node:fs/promises'; +import process from 'node:process'; + +const MIGRATION_DIR = 'supabase/migrations'; +const DEFAULT_FROM = '20261112170000'; +const V2_MARKERS = ['video_assets', 'video_edit_plans', 'render_jobs', 'style_presets']; + +function option(name, fallback) { + const index = process.argv.indexOf(name); + return index >= 0 ? (process.argv[index + 1] ?? fallback) : fallback; +} + +const from = option('--from', DEFAULT_FROM); +const execute = process.argv.includes('--execute'); +const projectRef = process.env.SUPABASE_PROJECT_REF ?? ''; +const token = process.env.SUPABASE_ACCESS_TOKEN ?? ''; +const expectedTables = Number(option('--expect-tables', '41')); + +if (!/^\d{14}$/.test(from) || !/^[a-z0-9]{20}$/.test(projectRef)) + throw new Error('Use --from YYYYMMDDHHMMSS and SUPABASE_PROJECT_REF (20 lowercase chars).'); +if (!Number.isInteger(expectedTables) || expectedTables < 1 || expectedTables > 500) + throw new Error('Invalid --expect-tables.'); + +const files = (await readdir(MIGRATION_DIR)) + .filter((file) => file.endsWith('.sql') && file.slice(0, 14) >= from) + .sort((left, right) => left.localeCompare(right)); +if (files.length === 0) throw new Error('No migrations selected.'); +if (!execute) { + console.log(`Dry run: ${files.length} migrations from ${from} would be applied.`); + for (const file of files) console.log(`- ${file}`); + process.exit(0); +} +if (!/^sbp_[A-Za-z0-9]+$/.test(token)) + throw new Error('SUPABASE_ACCESS_TOKEN must be an owner PAT (sbp_...).'); + +async function query(sql) { + const response = await fetch( + `https://api.supabase.com/v1/projects/${projectRef}/database/query`, + { + method: 'POST', + headers: { + authorization: `Bearer ${token}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ query: sql }), + }, + ); + const text = await response.text(); + if (!response.ok) + throw new Error( + `Management API HTTP ${response.status}: ${text.slice(0, 300).replaceAll(/\s+/g, ' ')}`, + ); + try { + return JSON.parse(text); + } catch { + return text; + } +} + +const before = await query( + "select tablename from pg_tables where schemaname = 'public' order by tablename", +); +const present = new Set((Array.isArray(before) ? before : []).map((row) => row.tablename)); +const markers = V2_MARKERS.filter((table) => present.has(table)); +if (markers.length > 0) + throw new Error( + `V2 schema already present (${markers.join(', ')}); refusing to reapply. Inspect the project before using --from.`, + ); + +for (const file of files) { + const sql = await readFile(`${MIGRATION_DIR}/${file}`, 'utf8'); + console.log(`Applying ${file}...`); + await query(sql); + console.log(`OK ${file}`); +} + +const after = await query( + "select count(*)::int as count from pg_tables where schemaname = 'public'", +); +const count = Array.isArray(after) ? Number(after[0]?.count) : Number.NaN; +if (count !== expectedTables) + throw new Error(`Expected ${expectedTables} public tables after migrations, found ${count}.`); +console.log(`Applied ${files.length} migrations; ${count} public tables.`); From d02de8de2ff4c0ffcc64cfaea90a61ba63e93717 Mon Sep 17 00:00:00 2001 From: KayzenRoot <114633702+KayzenRoot@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:28:31 -0300 Subject: [PATCH 2/5] =?UTF-8?q?chore(wo-014):=20adicionar=20smoke=20read-o?= =?UTF-8?q?nly=20de=20produ=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/V2_RELEASE_WO014.md | 4 +- docs/evidence/wo-014/tests.txt | 9 +++++ package.json | 1 + scripts/release-smoke.mjs | 68 ++++++++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 scripts/release-smoke.mjs diff --git a/docs/V2_RELEASE_WO014.md b/docs/V2_RELEASE_WO014.md index b463ca30..09fcaa67 100644 --- a/docs/V2_RELEASE_WO014.md +++ b/docs/V2_RELEASE_WO014.md @@ -36,9 +36,11 @@ node scripts/apply-hosted-migrations.mjs --execute ``` O script recusa se detectar schema V2 já presente, aplica em ordem e exige 41 tabelas públicas. -5. Smoke: `/health`, `/login`, owner login, `/app/style`, `/app/timeline`, upload R2, download privado, render worker, MP4 1080×1920, backup/rollback. +5. Smoke: `npm run release:smoke` (V1 público/boundaries + marcadores V2 no schema), depois owner login, `/app/style`, `/app/timeline`, upload R2, download privado, render worker, MP4 1080×1920, backup/rollback. 6. Só depois promover o checkpoint final para **APROVADO**. +Saída atual de `npm run release:smoke` (2026-11-20): health/login/boundaries PASS; **7 tabelas V2 ausentes** (`video_assets`, `video_edit_plans`, `render_jobs`, `cover_revisions`, `choice_end_cards`, `published_posts`, `style_presets`), exit não-zero. O script é read-only e impede declarar release completa com schema V1. + ## Script de migrations `scripts/apply-hosted-migrations.mjs`: diff --git a/docs/evidence/wo-014/tests.txt b/docs/evidence/wo-014/tests.txt index bc63c87e..5e4f803e 100644 --- a/docs/evidence/wo-014/tests.txt +++ b/docs/evidence/wo-014/tests.txt @@ -40,6 +40,15 @@ Hosted Supabase `zottgifcocnjguhmnezx`: - No Vercel CLI credentials; production deploys come from the Git integration. - Therefore the 29 V2 migrations cannot be applied and the release is **BLOCKED**. +## Release smoke (2026-11-20) + +`npm run release:smoke` against production: + +- PASS: `/health`, `/login`, anonymous boundaries for media/video/health/style. +- FAIL: 7 V2 schema markers missing (`video_assets`, `video_edit_plans`, `render_jobs`, + `cover_revisions`, `choice_end_cards`, `published_posts`, `style_presets`). +- Exit non-zero; production must not be declared V2-complete. + ## Migration runner dry-run `SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx node scripts/apply-hosted-migrations.mjs` diff --git a/package.json b/package.json index 87101822..8b28dade 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ "check:r2": "node scripts/check-r2.mjs", "backup:metadata": "node scripts/backup-metadata.mjs", "db:apply-hosted": "node scripts/apply-hosted-migrations.mjs", + "release:smoke": "node scripts/release-smoke.mjs", "restore:metadata": "node scripts/restore-metadata.mjs", "retention": "node scripts/retention.mjs", "audit:policy": "node scripts/audit-policy.mjs", diff --git a/scripts/release-smoke.mjs b/scripts/release-smoke.mjs new file mode 100644 index 00000000..c4c0989d --- /dev/null +++ b/scripts/release-smoke.mjs @@ -0,0 +1,68 @@ +#!/usr/bin/env node +// Read-only production smoke: public surface, private boundaries and the V2 schema +// markers. Run after hosted migrations; exits non-zero while the schema is V1. +import process from 'node:process'; + +const baseUrl = (process.env.PROD_BASE_URL ?? 'https://dif-studio.vercel.app').replace(/\/$/, ''); +const supabaseUrl = (process.env.PUBLIC_SUPABASE_URL ?? '').replace(/\/$/, ''); +const supabaseKey = + process.env.PUBLIC_SUPABASE_PUBLISHABLE_KEY ?? process.env.PUBLIC_SUPABASE_ANON_KEY ?? ''; +const v2Tables = [ + 'video_assets', + 'video_edit_plans', + 'render_jobs', + 'cover_revisions', + 'choice_end_cards', + 'published_posts', + 'style_presets', +]; + +function fail(message) { + console.error(`FAIL ${message}`); + process.exitCode = 1; +} +function pass(message) { + console.log(`PASS ${message}`); +} + +async function get(url, options = {}) { + return fetch(url, { ...options, signal: AbortSignal.timeout(20_000), redirect: 'manual' }); +} + +const health = await get(`${baseUrl}/health`); +if (health.status === 200) { + const body = await health.json().catch(() => ({})); + if (body?.status === 'ok' && body?.configured?.supabase === true) pass('health'); + else fail(`health payload ${JSON.stringify(body)}`); +} else fail(`health HTTP ${health.status}`); + +const login = await get(`${baseUrl}/login`); +if (login.status === 200 && (await login.text()).includes('E-mail do proprietário')) pass('login'); +else fail(`login HTTP ${login.status}`); + +for (const path of [ + '/api/media/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + '/api/video/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + '/api/render-jobs/health', + '/api/style/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', +]) { + const response = await get(`${baseUrl}${path}`); + if ([401, 403, 404].includes(response.status)) pass(`anonymous boundary ${path}`); + else fail(`anonymous boundary ${path} HTTP ${response.status}`); +} + +if (!supabaseUrl || !supabaseKey) { + fail('PUBLIC_SUPABASE_URL and publishable/anon key are required for schema probe'); +} else { + for (const table of v2Tables) { + const response = await get(`${supabaseUrl}/rest/v1/${table}?select=id&limit=1`, { + headers: { apikey: supabaseKey }, + }); + if (response.status === 404) fail(`schema missing table ${table}`); + else if ([200, 401, 403].includes(response.status)) pass(`schema table ${table}`); + else fail(`schema probe ${table} HTTP ${response.status}`); + } +} + +if (process.exitCode) console.error('Smoke failed; do not declare the release complete.'); +else console.log('Smoke passed.'); From a7c7eee8904794ca40438a23f78730a3e055dcde Mon Sep 17 00:00:00 2001 From: KayzenRoot <114633702+KayzenRoot@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:00:40 -0300 Subject: [PATCH 3/5] fix(wo-014): fechar achados do smoke e do runner hosted --- docs/V2_RELEASE_WO014.md | 31 ++-- docs/evidence/wo-014/tests.txt | 10 +- package.json | 2 +- scripts/apply-hosted-migrations.mjs | 229 ++++++++++++++++++--------- scripts/release-smoke-lib.mjs | 23 +++ scripts/release-smoke.mjs | 40 ++++- src/lib/domain/release-smoke.test.ts | 26 +++ 7 files changed, 265 insertions(+), 96 deletions(-) create mode 100644 scripts/release-smoke-lib.mjs create mode 100644 src/lib/domain/release-smoke.test.ts diff --git a/docs/V2_RELEASE_WO014.md b/docs/V2_RELEASE_WO014.md index 09fcaa67..92b91c3f 100644 --- a/docs/V2_RELEASE_WO014.md +++ b/docs/V2_RELEASE_WO014.md @@ -1,12 +1,12 @@ # DIF-V2-WO-014 — Release V2: regressão integral, auditoria e deploy validado **Issue:** #31 · **Branch:** `feat/dif-v2-wo-014` · **Base:** `main` `7c175e5` -**Status:** **BLOCKED** — código/testes/regressão prontos; o deploy validado não pode concluir sem migrations no Supabase hospedado. O Vercel já serve o código V2, mas o projeto hospedado ainda tem apenas o schema V1. +**Status:** **BLOCKED** — código/testes/regressão prontos; o deploy validado não pode concluir sem migrations no Supabase hospedado. O Vercel já serve o código V2, mas o projeto hospedado ainda tem apenas o schema V1. O PR #70 mantém ferramentas/docs de release, sem merge/deploy. ## Pré-requisitos atendidos - WO-001–013 e WO-015–021 **PROMOTED**, com checkpoints reconciliados; OPS 015–021 **PROMOTED** (`c7490e8`). -- `main` `7c175e5` com CI docs-only PASS; code/test head V2 `f32cc97` com CI `44776291945` PASS; OPS `77d5626` com CI `44787029917` PASS. +- `main` `7c175e5` com quality workflow docs-only PASS; o gate SonarCloud separado falhou nesse commit de docs por duplicação pré-existente, sem código novo. Code/test head V2 `f32cc97` com CI `44776291945` PASS; OPS `77d5626` com CI `44787029917` PASS. - Unit **351 + 3 skipped**, PgTAP **247/247**, policy **36/41**, E2E **19/19**, Sonar/Socket PASS. - Backup/restore local executado (41/41 contagens, SHA, join 768, QA 5/5). - Worker/render local e ARM64 benchmark das WOs anteriores aprovados. @@ -26,31 +26,34 @@ 1. O owner fornece um PAT Supabase (`sbp_...`) em `C:\Users\csn19\.zcode\dif-secrets\supabase-pat.txt` **ou** roda `npx supabase login`/`link --project-ref zottgifcocnjguhmnezx` **ou** fornece a database password por arquivo privado. 2. Antes de aplicar, gerar backup do schema hospedado (Management API/`pg_dump`) e confirmar que o schema atual é V1. -3. Dry-run: +3. Dry-run (não lê o PAT): ```sh SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx node scripts/apply-hosted-migrations.mjs ``` -4. Executar: +4. Executar via arquivo de PAT (não coloque o segredo no histórico do shell): ```sh - SUPABASE_ACCESS_TOKEN=... SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx \ - node scripts/apply-hosted-migrations.mjs --execute + SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx \ + node scripts/apply-hosted-migrations.mjs --execute \ + --token-file "C:/Users/csn19/.zcode/dif-secrets/supabase-pat.txt" \ + --confirm-project zottgifcocnjguhmnezx ``` - O script recusa se detectar schema V2 já presente, aplica em ordem e exige 41 tabelas públicas. -5. Smoke: `npm run release:smoke` (V1 público/boundaries + marcadores V2 no schema), depois owner login, `/app/style`, `/app/timeline`, upload R2, download privado, render worker, MP4 1080×1920, backup/rollback. + O script recusa schema V2 já presente sem ledger, exige confirmação explícita do projeto, grava um ledger privado por migration aplicada, aceita `--resume` apenas com ledger correspondente e compara o conjunto exato de 41 tabelas (não apenas a contagem). `--from` anterior a `20261112170000` exige `--allow-v1` explícito. +5. Smoke: `npm run release:smoke` lê `.env` (`PUBLIC_SUPABASE_URL`, publishable/anon key) e valida `EXPECTED_SUPABASE_PROJECT_REF` (default `zottgifcocnjguhmnezx`), dono configurado, boundaries anônimos e marcadores V2; depois owner login, `/app/style`, `/app/timeline`, upload R2, download privado, render worker, MP4 1080×1920, backup/rollback. 6. Só depois promover o checkpoint final para **APROVADO**. -Saída atual de `npm run release:smoke` (2026-11-20): health/login/boundaries PASS; **7 tabelas V2 ausentes** (`video_assets`, `video_edit_plans`, `render_jobs`, `cover_revisions`, `choice_end_cards`, `published_posts`, `style_presets`), exit não-zero. O script é read-only e impede declarar release completa com schema V1. +Saída atual de `npm run release:smoke` (2026-11-20): health/login/boundaries PASS; **7 tabelas V2 ausentes** (`video_assets`, `video_edit_plans`, `render_jobs`, `cover_revisions`, `choice_end_cards`, `published_posts`, `style_presets`), exit 1. Chave inválida é FAIL explícito (não conta como tabela presente). O script é read-only e impede declarar release completa com schema V1. ## Script de migrations `scripts/apply-hosted-migrations.mjs`: - dry-run por padrão; `--execute` explícito; -- exige PAT `sbp_...` e project ref de 20 caracteres; -- recusa se `video_assets`, `video_edit_plans`, `render_jobs` ou `style_presets` já existirem; +- exige PAT `sbp_...` (env ou `--token-file`) e confirmação `--confirm-project` do ref; +- recusa schema V2 já presente sem ledger correspondente; aceita `--resume` com ledger por projeto; - aplica somente migrations a partir de `--from` (default `20261112170000`), em ordem; -- não imprime token nem SQL; falha com HTTP/status e trecho sanitizado; -- confere 41 tabelas públicas ao final. +- rejeita `--from` anterior ao V2 sem `--allow-v1`; +- não imprime token nem SQL; falha com HTTP/status e trecho normalizado; +- compara o conjunto exato de tabelas (14 V1 + 27 V2 = 41), reportando faltantes/extras. ## Pendências humanas/operacionais @@ -62,5 +65,5 @@ Saída atual de `npm run release:smoke` (2026-11-20): health/login/boundaries PA ## Riscos - V2 code em produção sem schema V2 deixa rotas novas em 500 (V1 core continua 200). Não declarar release completa. -- Migrations são aditivas, mas devem ser aplicadas com backup e em ordem; o script falha fechado. +- As migrations são majoritariamente aditivas (também incluem grants/constraints), mas devem ser aplicadas com backup, em ordem e com ledger; o script falha fechado. - Sem Vercel CLI, rollback de alias depende do dashboard/integração Git. diff --git a/docs/evidence/wo-014/tests.txt b/docs/evidence/wo-014/tests.txt index 5e4f803e..a5c37b73 100644 --- a/docs/evidence/wo-014/tests.txt +++ b/docs/evidence/wo-014/tests.txt @@ -6,7 +6,9 @@ Branch: `feat/dif-v2-wo-014` (base `main` `7c175e5`) ## Local/CI baseline - `main` code/test head V2 `f32cc97`: CI `44776291945` PASS — unit **351+3**, - PgTAP **247/247**, policy 35/41, E2E **19/19**, Sonar PASS. + PgTAP **247/247**, policy 35/41, E2E **19/19**. OPS `77d5626` has quality + Sonar PASS. + The docs-only `7c175e5` passed the quality workflow; the separate SonarCloud gate failed + on pre-existing duplication, not new application code. - OPS head `77d5626`: CI `44787029917` PASS — unit **351+3**, PgTAP **247/247**, policy **36/41**, E2E **19/19**, Sonar PASS. - `main` docs checkpoints: `3950ccb` (WO-021) and `7c175e5` (OPS) CI PASS. @@ -24,7 +26,7 @@ Authenticated owner session against `https://dif-studio.vercel.app`: | `/app` | 200 | | `/app/series` | 200 | | `/app/episodes` | 200 | -| `/timeline` | timed out / V2 data unavailable | +| `/app/timeline` | timed out / V2 data unavailable | | `/app/style` | **500 Internal Error** | Hosted Supabase `zottgifcocnjguhmnezx`: @@ -47,7 +49,9 @@ Hosted Supabase `zottgifcocnjguhmnezx`: - PASS: `/health`, `/login`, anonymous boundaries for media/video/health/style. - FAIL: 7 V2 schema markers missing (`video_assets`, `video_edit_plans`, `render_jobs`, `cover_revisions`, `choice_end_cards`, `published_posts`, `style_presets`). -- Exit non-zero; production must not be declared V2-complete. +- Exit 1. Invalid-key run also exits 1 with `Supabase publishable/anon key is invalid`; + regression tests cover invalid key, RLS-coded 401/403 and PGRST205. +- Production must not be declared V2-complete. ## Migration runner dry-run diff --git a/package.json b/package.json index 8b28dade..39dd2ab7 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,7 @@ "check:r2": "node scripts/check-r2.mjs", "backup:metadata": "node scripts/backup-metadata.mjs", "db:apply-hosted": "node scripts/apply-hosted-migrations.mjs", - "release:smoke": "node scripts/release-smoke.mjs", + "release:smoke": "node --env-file=.env scripts/release-smoke.mjs", "restore:metadata": "node scripts/restore-metadata.mjs", "retention": "node scripts/retention.mjs", "audit:policy": "node scripts/audit-policy.mjs", diff --git a/scripts/apply-hosted-migrations.mjs b/scripts/apply-hosted-migrations.mjs index 66fd7e06..8098c40e 100644 --- a/scripts/apply-hosted-migrations.mjs +++ b/scripts/apply-hosted-migrations.mjs @@ -1,89 +1,174 @@ #!/usr/bin/env node // Applies the additive V2 migrations to the hosted Supabase project through the -// Management API. Dry-run is the default. Requires an owner-provided PAT: -// SUPABASE_ACCESS_TOKEN=... SUPABASE_PROJECT_REF=... \ -// node scripts/apply-hosted-migrations.mjs --execute +// Management API. Dry-run is the default. For execution the owner supplies a PAT +// via env or --token-file and confirms the project ref: +// SUPABASE_ACCESS_TOKEN="$(cat /supabase-pat.txt)" \ +// SUPABASE_PROJECT_REF=... node scripts/apply-hosted-migrations.mjs \ +// --execute --confirm-project // Never prints the token or full SQL responses. -import { readdir, readFile } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { isAbsolute, join } from 'node:path'; import process from 'node:process'; -const MIGRATION_DIR = 'supabase/migrations'; -const DEFAULT_FROM = '20261112170000'; -const V2_MARKERS = ['video_assets', 'video_edit_plans', 'render_jobs', 'style_presets']; +async function main() { + const MIGRATION_DIR = 'supabase/migrations'; + const DEFAULT_FROM = '20261112170000'; + const V2_MARKERS = ['video_assets', 'video_edit_plans', 'render_jobs', 'style_presets']; -function option(name, fallback) { - const index = process.argv.indexOf(name); - return index >= 0 ? (process.argv[index + 1] ?? fallback) : fallback; -} + function option(name, fallback) { + const index = process.argv.indexOf(name); + return index >= 0 ? (process.argv[index + 1] ?? fallback) : fallback; + } -const from = option('--from', DEFAULT_FROM); -const execute = process.argv.includes('--execute'); -const projectRef = process.env.SUPABASE_PROJECT_REF ?? ''; -const token = process.env.SUPABASE_ACCESS_TOKEN ?? ''; -const expectedTables = Number(option('--expect-tables', '41')); + const from = option('--from', DEFAULT_FROM); + const execute = process.argv.includes('--execute'); + const resume = process.argv.includes('--resume'); + const allowV1 = process.argv.includes('--allow-v1'); + const projectRef = process.env.SUPABASE_PROJECT_REF ?? ''; + const tokenFile = option('--token-file', ''); + const ledgerPath = option( + '--ledger', + join(homedir(), '.dif-studio', `hosted-migrations-${projectRef || 'unknown'}.json`), + ); + const confirmProject = option('--confirm-project', ''); -if (!/^\d{14}$/.test(from) || !/^[a-z0-9]{20}$/.test(projectRef)) - throw new Error('Use --from YYYYMMDDHHMMSS and SUPABASE_PROJECT_REF (20 lowercase chars).'); -if (!Number.isInteger(expectedTables) || expectedTables < 1 || expectedTables > 500) - throw new Error('Invalid --expect-tables.'); + if (!/^\d{14}$/.test(from) || !/^[a-z0-9]{20}$/.test(projectRef)) + throw new Error('Use --from YYYYMMDDHHMMSS and SUPABASE_PROJECT_REF (20 lowercase chars).'); + if (from < DEFAULT_FROM && !allowV1) + throw new Error( + `--from before ${DEFAULT_FROM} requires --allow-v1 (V1 migrations are not idempotent).`, + ); + if (!isAbsolute(ledgerPath)) throw new Error('--ledger must be an absolute path.'); + if (tokenFile && !isAbsolute(tokenFile)) + throw new Error('--token-file must be an absolute path.'); -const files = (await readdir(MIGRATION_DIR)) - .filter((file) => file.endsWith('.sql') && file.slice(0, 14) >= from) - .sort((left, right) => left.localeCompare(right)); -if (files.length === 0) throw new Error('No migrations selected.'); -if (!execute) { - console.log(`Dry run: ${files.length} migrations from ${from} would be applied.`); - for (const file of files) console.log(`- ${file}`); - process.exit(0); -} -if (!/^sbp_[A-Za-z0-9]+$/.test(token)) - throw new Error('SUPABASE_ACCESS_TOKEN must be an owner PAT (sbp_...).'); + const allFiles = (await readdir(MIGRATION_DIR)) + .filter((file) => file.endsWith('.sql')) + .sort((left, right) => left.localeCompare(right)); + const files = allFiles.filter((file) => file.slice(0, 14) >= from); + if (files.length === 0) throw new Error('No migrations selected.'); -async function query(sql) { - const response = await fetch( - `https://api.supabase.com/v1/projects/${projectRef}/database/query`, - { - method: 'POST', - headers: { - authorization: `Bearer ${token}`, - 'content-type': 'application/json', - }, - body: JSON.stringify({ query: sql }), - }, - ); - const text = await response.text(); - if (!response.ok) - throw new Error( - `Management API HTTP ${response.status}: ${text.slice(0, 300).replaceAll(/\s+/g, ' ')}`, + async function expectedTableNames() { + const names = new Set(); + for (const file of allFiles) { + const sql = await readFile(`${MIGRATION_DIR}/${file}`, 'utf8'); + for (const match of sql.matchAll(/create table(?: if not exists)?\s+public\.(\w+)\s*\(/gi)) + names.add(match[1]); + } + return names; + } + + const expectedTables = await expectedTableNames(); + if (!execute) { + console.log( + `Dry run: ${files.length} migrations from ${from} would be applied to ${projectRef}; ${expectedTables.size} public tables expected.`, ); - try { - return JSON.parse(text); - } catch { - return text; + for (const file of files) console.log(`- ${file}`); + process.exit(0); } -} -const before = await query( - "select tablename from pg_tables where schemaname = 'public' order by tablename", -); -const present = new Set((Array.isArray(before) ? before : []).map((row) => row.tablename)); -const markers = V2_MARKERS.filter((table) => present.has(table)); -if (markers.length > 0) - throw new Error( - `V2 schema already present (${markers.join(', ')}); refusing to reapply. Inspect the project before using --from.`, + let token = process.env.SUPABASE_ACCESS_TOKEN ?? ''; + if (!token && tokenFile) token = (await readFile(tokenFile, 'utf8')).trim(); + if (!/^sbp_[A-Za-z0-9]+$/.test(token)) + throw new Error('SUPABASE_ACCESS_TOKEN or --token-file must contain an owner PAT (sbp_...).'); + if (confirmProject !== projectRef) + throw new Error(`Execution requires --confirm-project ${projectRef}.`); + + let ledger = { projectRef, applied: [] }; + if (existsSync(ledgerPath)) { + try { + const parsed = JSON.parse(await readFile(ledgerPath, 'utf8')); + if (parsed?.projectRef !== projectRef || !Array.isArray(parsed?.applied)) + throw new Error('ledger does not belong to this project'); + ledger = parsed; + } catch { + throw new Error(`Unreadable migration ledger at ${ledgerPath}; inspect before retrying.`); + } + } + console.log(`Target: ${projectRef}; ${files.length} migrations; ledger: ${ledgerPath}`); + + async function query(sql) { + let response; + try { + response = await fetch(`https://api.supabase.com/v1/projects/${projectRef}/database/query`, { + method: 'POST', + headers: { + authorization: `Bearer ${token}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ query: sql }), + signal: AbortSignal.timeout(120_000), + }); + } catch (cause) { + if (cause?.name === 'TimeoutError' || cause?.name === 'AbortError') + throw new Error('Management API timed out; inspect the project before retrying.', { + cause, + }); + throw cause; + } + const text = await response.text(); + if (!response.ok) + throw new Error( + `Management API HTTP ${response.status}: ${text.slice(0, 300).replaceAll(/\s+/g, ' ')}`, + ); + try { + return JSON.parse(text); + } catch { + return text; + } + } + + async function writeLedger() { + await mkdir(join(homedir(), '.dif-studio'), { recursive: true, mode: 0o700 }); + await writeFile(ledgerPath, JSON.stringify(ledger, null, 2), { mode: 0o600 }); + } + + const before = await query( + "select tablename from pg_tables where schemaname = 'public' order by tablename", ); + if (!Array.isArray(before)) + throw new Error('Management API returned an unexpected table list; refusing to proceed.'); + const present = new Set(before.map((row) => row.tablename)); + const markers = V2_MARKERS.filter((table) => present.has(table)); + if (markers.length > 0) { + if (!resume || ledger.applied.length === 0) + throw new Error( + `V2 schema already present (${markers.join(', ')}); use --resume only with a matching ledger, or inspect manually.`, + ); + console.log(`Resuming from ledger with ${ledger.applied.length} applied migrations.`); + } + + for (const file of files) { + if (ledger.applied.includes(file)) { + console.log(`SKIP ${file} (ledger)`); + continue; + } + const sql = await readFile(`${MIGRATION_DIR}/${file}`, 'utf8'); + console.log(`Applying ${file}...`); + await query(sql); + ledger.applied.push(file); + await writeLedger(); + console.log(`OK ${file}`); + } -for (const file of files) { - const sql = await readFile(`${MIGRATION_DIR}/${file}`, 'utf8'); - console.log(`Applying ${file}...`); - await query(sql); - console.log(`OK ${file}`); + const after = await query( + "select tablename from pg_tables where schemaname = 'public' order by tablename", + ); + if (!Array.isArray(after)) + throw new Error('Management API returned an unexpected post-apply table list.'); + const actualTables = new Set(after.map((row) => row.tablename)); + const missing = [...expectedTables].filter((table) => !actualTables.has(table)); + const extra = [...actualTables].filter((table) => !expectedTables.has(table)); + if (missing.length || extra.length) + throw new Error( + `Schema mismatch: missing=[${missing.join(', ')}], extra=[${extra.join(', ')}].`, + ); + console.log(`Applied ${files.length} migrations; ${actualTables.size} public tables match.`); } -const after = await query( - "select count(*)::int as count from pg_tables where schemaname = 'public'", -); -const count = Array.isArray(after) ? Number(after[0]?.count) : Number.NaN; -if (count !== expectedTables) - throw new Error(`Expected ${expectedTables} public tables after migrations, found ${count}.`); -console.log(`Applied ${files.length} migrations; ${count} public tables.`); +main().catch((cause) => { + console.error(`ERROR ${cause instanceof Error ? cause.message : String(cause)}`); + process.exitCode = 1; +}); diff --git a/scripts/release-smoke-lib.mjs b/scripts/release-smoke-lib.mjs new file mode 100644 index 00000000..8d3daa9b --- /dev/null +++ b/scripts/release-smoke-lib.mjs @@ -0,0 +1,23 @@ +/** Pure schema-probe classification shared by the release smoke and its tests. */ +/** @param {number} status @param {any} body */ +export function classifyKeyPreflight(status, body) { + if ( + status === 401 && + (!body?.code || + String(body?.message ?? '') + .toLowerCase() + .includes('api key')) + ) + return 'invalid'; + if (status === 200) return 'valid'; + if ([401, 403].includes(status) && body?.code) return 'valid'; + return 'unknown'; +} + +/** @param {number} status @param {any} body */ +export function classifyTableProbe(status, body) { + if (status === 200) return 'present'; + if (status === 404 && body?.code === 'PGRST205') return 'missing'; + if ([401, 403].includes(status) && body?.code && body.code !== 'PGRST205') return 'present'; + return 'unknown'; +} diff --git a/scripts/release-smoke.mjs b/scripts/release-smoke.mjs index c4c0989d..25bf7fe9 100644 --- a/scripts/release-smoke.mjs +++ b/scripts/release-smoke.mjs @@ -2,11 +2,13 @@ // Read-only production smoke: public surface, private boundaries and the V2 schema // markers. Run after hosted migrations; exits non-zero while the schema is V1. import process from 'node:process'; +import { classifyKeyPreflight, classifyTableProbe } from './release-smoke-lib.mjs'; const baseUrl = (process.env.PROD_BASE_URL ?? 'https://dif-studio.vercel.app').replace(/\/$/, ''); const supabaseUrl = (process.env.PUBLIC_SUPABASE_URL ?? '').replace(/\/$/, ''); const supabaseKey = process.env.PUBLIC_SUPABASE_PUBLISHABLE_KEY ?? process.env.PUBLIC_SUPABASE_ANON_KEY ?? ''; +const expectedProjectRef = process.env.EXPECTED_SUPABASE_PROJECT_REF ?? 'zottgifcocnjguhmnezx'; const v2Tables = [ 'video_assets', 'video_edit_plans', @@ -32,7 +34,12 @@ async function get(url, options = {}) { const health = await get(`${baseUrl}/health`); if (health.status === 200) { const body = await health.json().catch(() => ({})); - if (body?.status === 'ok' && body?.configured?.supabase === true) pass('health'); + if ( + body?.status === 'ok' && + body?.configured?.supabase === true && + body?.configured?.owner === true + ) + pass('health'); else fail(`health payload ${JSON.stringify(body)}`); } else fail(`health HTTP ${health.status}`); @@ -47,20 +54,41 @@ for (const path of [ '/api/style/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', ]) { const response = await get(`${baseUrl}${path}`); - if ([401, 403, 404].includes(response.status)) pass(`anonymous boundary ${path}`); + if ([401, 403].includes(response.status)) pass(`anonymous boundary ${path}`); else fail(`anonymous boundary ${path} HTTP ${response.status}`); } if (!supabaseUrl || !supabaseKey) { fail('PUBLIC_SUPABASE_URL and publishable/anon key are required for schema probe'); } else { - for (const table of v2Tables) { + const host = new URL(supabaseUrl).hostname; + const projectRef = host.split('.')[0]; + if (projectRef !== expectedProjectRef) + fail(`project ref mismatch: expected ${expectedProjectRef}, got ${projectRef}`); + + async function probe(table) { const response = await get(`${supabaseUrl}/rest/v1/${table}?select=id&limit=1`, { headers: { apikey: supabaseKey }, }); - if (response.status === 404) fail(`schema missing table ${table}`); - else if ([200, 401, 403].includes(response.status)) pass(`schema table ${table}`); - else fail(`schema probe ${table} HTTP ${response.status}`); + const body = await response.json().catch(() => null); + return { status: response.status, body }; + } + + const v1 = await probe('series'); + const keyStatus = classifyKeyPreflight(v1.status, v1.body); + if (keyStatus === 'invalid') { + fail('Supabase publishable/anon key is invalid'); + } else if (keyStatus !== 'valid') { + fail(`schema key preflight HTTP ${v1.status}`); + } else { + pass('schema key preflight'); + for (const table of v2Tables) { + const result = await probe(table); + const tableStatus = classifyTableProbe(result.status, result.body); + if (tableStatus === 'missing') fail(`schema missing table ${table}`); + else if (tableStatus === 'present') pass(`schema table ${table}`); + else fail(`schema probe ${table} HTTP ${result.status}`); + } } } diff --git a/src/lib/domain/release-smoke.test.ts b/src/lib/domain/release-smoke.test.ts new file mode 100644 index 00000000..9fff5805 --- /dev/null +++ b/src/lib/domain/release-smoke.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest'; +import { classifyKeyPreflight, classifyTableProbe } from '../../../scripts/release-smoke-lib.mjs'; + +describe('release smoke schema probe', () => { + it('rejects an invalid API key instead of treating 401 as a present table', () => { + expect(classifyKeyPreflight(401, { message: 'Invalid API key' })).toBe('invalid'); + expect(classifyKeyPreflight(401, {})).toBe('invalid'); + expect(classifyTableProbe(401, { message: 'Invalid API key' })).toBe('unknown'); + }); + + it('accepts a valid key with RLS denial but only a coded 401/403 as table-present', () => { + expect( + classifyKeyPreflight(401, { code: '42501', message: 'permission denied for table series' }), + ).toBe('valid'); + expect(classifyTableProbe(401, { code: '42501' })).toBe('present'); + expect(classifyTableProbe(403, { code: '42501' })).toBe('present'); + expect(classifyTableProbe(401, { message: 'Invalid API key' })).toBe('unknown'); + }); + + it('treats only PGRST205/404 as a missing V2 table', () => { + expect(classifyTableProbe(404, { code: 'PGRST205' })).toBe('missing'); + expect(classifyTableProbe(404, {})).toBe('unknown'); + expect(classifyTableProbe(500, {})).toBe('unknown'); + expect(classifyTableProbe(200, null)).toBe('present'); + }); +}); From 4f709d62ed354469830880f81503d8642a9e483a Mon Sep 17 00:00:00 2001 From: KayzenRoot <114633702+KayzenRoot@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:01:56 -0300 Subject: [PATCH 4/5] =?UTF-8?q?fix(wo-014):=20criar=20diret=C3=B3rio=20do?= =?UTF-8?q?=20ledger=20configurado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/apply-hosted-migrations.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/apply-hosted-migrations.mjs b/scripts/apply-hosted-migrations.mjs index 8098c40e..04502d75 100644 --- a/scripts/apply-hosted-migrations.mjs +++ b/scripts/apply-hosted-migrations.mjs @@ -9,7 +9,7 @@ import { existsSync } from 'node:fs'; import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'; import { homedir } from 'node:os'; -import { isAbsolute, join } from 'node:path'; +import { dirname, isAbsolute, join } from 'node:path'; import process from 'node:process'; async function main() { @@ -121,7 +121,7 @@ async function main() { } async function writeLedger() { - await mkdir(join(homedir(), '.dif-studio'), { recursive: true, mode: 0o700 }); + await mkdir(dirname(ledgerPath), { recursive: true, mode: 0o700 }); await writeFile(ledgerPath, JSON.stringify(ledger, null, 2), { mode: 0o600 }); } From 16a78e9a8916a6bf24ac5d723e3f9fe1f415a846 Mon Sep 17 00:00:00 2001 From: KayzenRoot <114633702+KayzenRoot@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:19:36 -0300 Subject: [PATCH 5/5] fix(wo-014): endurecer classificador e ledger do release --- docs/V2_RELEASE_WO014.md | 2 +- docs/evidence/wo-014/tests.txt | 9 ++++++--- package.json | 2 +- scripts/apply-hosted-migrations.mjs | 16 +++++++++++++--- scripts/release-smoke-lib.mjs | 4 ++-- scripts/release-smoke.mjs | 9 ++++----- src/lib/domain/release-smoke.test.ts | 8 ++++++++ 7 files changed, 35 insertions(+), 15 deletions(-) diff --git a/docs/V2_RELEASE_WO014.md b/docs/V2_RELEASE_WO014.md index 92b91c3f..4ce37f1d 100644 --- a/docs/V2_RELEASE_WO014.md +++ b/docs/V2_RELEASE_WO014.md @@ -38,7 +38,7 @@ --confirm-project zottgifcocnjguhmnezx ``` O script recusa schema V2 já presente sem ledger, exige confirmação explícita do projeto, grava um ledger privado por migration aplicada, aceita `--resume` apenas com ledger correspondente e compara o conjunto exato de 41 tabelas (não apenas a contagem). `--from` anterior a `20261112170000` exige `--allow-v1` explícito. -5. Smoke: `npm run release:smoke` lê `.env` (`PUBLIC_SUPABASE_URL`, publishable/anon key) e valida `EXPECTED_SUPABASE_PROJECT_REF` (default `zottgifcocnjguhmnezx`), dono configurado, boundaries anônimos e marcadores V2; depois owner login, `/app/style`, `/app/timeline`, upload R2, download privado, render worker, MP4 1080×1920, backup/rollback. +5. Smoke: crie `.env.smoke` (ignorado pelo Git) com `PUBLIC_SUPABASE_URL`, `PUBLIC_SUPABASE_PUBLISHABLE_KEY` e `EXPECTED_SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx`; `npm run release:smoke` usa `--env-file-if-exists=.env.smoke`, valida dono configurado, boundaries anônimos e marcadores V2; depois owner login, `/app/style`, `/app/timeline`, upload R2, download privado, render worker, MP4 1080×1920, backup/rollback. 6. Só depois promover o checkpoint final para **APROVADO**. Saída atual de `npm run release:smoke` (2026-11-20): health/login/boundaries PASS; **7 tabelas V2 ausentes** (`video_assets`, `video_edit_plans`, `render_jobs`, `cover_revisions`, `choice_end_cards`, `published_posts`, `style_presets`), exit 1. Chave inválida é FAIL explícito (não conta como tabela presente). O script é read-only e impede declarar release completa com schema V1. diff --git a/docs/evidence/wo-014/tests.txt b/docs/evidence/wo-014/tests.txt index a5c37b73..3727c076 100644 --- a/docs/evidence/wo-014/tests.txt +++ b/docs/evidence/wo-014/tests.txt @@ -11,7 +11,9 @@ Branch: `feat/dif-v2-wo-014` (base `main` `7c175e5`) on pre-existing duplication, not new application code. - OPS head `77d5626`: CI `44787029917` PASS — unit **351+3**, PgTAP **247/247**, policy **36/41**, E2E **19/19**, Sonar PASS. -- `main` docs checkpoints: `3950ccb` (WO-021) and `7c175e5` (OPS) CI PASS. +- `main` docs checkpoints: `3950ccb` (WO-021) and `7c175e5` (OPS) passed the quality + workflow; both are docs-only, and the separate SonarCloud gate failed on pre-existing + duplication rather than new application code. - Backup/restore local: 41/41 table counts, SHA verified, join 768, QA 5/5, metadata/coverage OK; media fail-closed for 3 absent temp MP4s. @@ -57,8 +59,9 @@ Hosted Supabase `zottgifcocnjguhmnezx`: `SUPABASE_PROJECT_REF=zottgifcocnjguhmnezx node scripts/apply-hosted-migrations.mjs` lists **29 migrations** from `20261112170000` and performs no network write in -dry-run. `--execute` requires an owner PAT `sbp_...` and refuses if V2 markers -already exist. +dry-run. `--execute` requires an owner PAT (`--token-file` or env) and `--confirm-project`, +writes an atomic ledger, refuses V2 markers without `--resume`, and compares the exact +41-table set. ## Not yet executed diff --git a/package.json b/package.json index 39dd2ab7..4dc17652 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,7 @@ "check:r2": "node scripts/check-r2.mjs", "backup:metadata": "node scripts/backup-metadata.mjs", "db:apply-hosted": "node scripts/apply-hosted-migrations.mjs", - "release:smoke": "node --env-file=.env scripts/release-smoke.mjs", + "release:smoke": "node --env-file-if-exists=.env.smoke scripts/release-smoke.mjs", "restore:metadata": "node scripts/restore-metadata.mjs", "retention": "node scripts/retention.mjs", "audit:policy": "node scripts/audit-policy.mjs", diff --git a/scripts/apply-hosted-migrations.mjs b/scripts/apply-hosted-migrations.mjs index 04502d75..6fb67e28 100644 --- a/scripts/apply-hosted-migrations.mjs +++ b/scripts/apply-hosted-migrations.mjs @@ -7,7 +7,7 @@ // --execute --confirm-project // Never prints the token or full SQL responses. import { existsSync } from 'node:fs'; -import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'; +import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises'; import { homedir } from 'node:os'; import { dirname, isAbsolute, join } from 'node:path'; import process from 'node:process'; @@ -122,9 +122,13 @@ async function main() { async function writeLedger() { await mkdir(dirname(ledgerPath), { recursive: true, mode: 0o700 }); - await writeFile(ledgerPath, JSON.stringify(ledger, null, 2), { mode: 0o600 }); + const temporary = `${ledgerPath}.tmp`; + await writeFile(temporary, JSON.stringify(ledger, null, 2), { mode: 0o600 }); + await rename(temporary, ledgerPath); } + await writeLedger(); + const before = await query( "select tablename from pg_tables where schemaname = 'public' order by tablename", ); @@ -140,9 +144,12 @@ async function main() { console.log(`Resuming from ledger with ${ledger.applied.length} applied migrations.`); } + let appliedNow = 0; + let skipped = 0; for (const file of files) { if (ledger.applied.includes(file)) { console.log(`SKIP ${file} (ledger)`); + skipped += 1; continue; } const sql = await readFile(`${MIGRATION_DIR}/${file}`, 'utf8'); @@ -150,6 +157,7 @@ async function main() { await query(sql); ledger.applied.push(file); await writeLedger(); + appliedNow += 1; console.log(`OK ${file}`); } @@ -165,7 +173,9 @@ async function main() { throw new Error( `Schema mismatch: missing=[${missing.join(', ')}], extra=[${extra.join(', ')}].`, ); - console.log(`Applied ${files.length} migrations; ${actualTables.size} public tables match.`); + console.log( + `Applied ${appliedNow} new migrations (${skipped} skipped); ${actualTables.size} public tables match.`, + ); } main().catch((cause) => { diff --git a/scripts/release-smoke-lib.mjs b/scripts/release-smoke-lib.mjs index 8d3daa9b..829cf685 100644 --- a/scripts/release-smoke-lib.mjs +++ b/scripts/release-smoke-lib.mjs @@ -10,7 +10,7 @@ export function classifyKeyPreflight(status, body) { ) return 'invalid'; if (status === 200) return 'valid'; - if ([401, 403].includes(status) && body?.code) return 'valid'; + if ([401, 403].includes(status) && body?.code === '42501') return 'valid'; return 'unknown'; } @@ -18,6 +18,6 @@ export function classifyKeyPreflight(status, body) { export function classifyTableProbe(status, body) { if (status === 200) return 'present'; if (status === 404 && body?.code === 'PGRST205') return 'missing'; - if ([401, 403].includes(status) && body?.code && body.code !== 'PGRST205') return 'present'; + if ([401, 403].includes(status) && body?.code === '42501') return 'present'; return 'unknown'; } diff --git a/scripts/release-smoke.mjs b/scripts/release-smoke.mjs index 25bf7fe9..c45f97d7 100644 --- a/scripts/release-smoke.mjs +++ b/scripts/release-smoke.mjs @@ -61,14 +61,13 @@ for (const path of [ if (!supabaseUrl || !supabaseKey) { fail('PUBLIC_SUPABASE_URL and publishable/anon key are required for schema probe'); } else { - const host = new URL(supabaseUrl).hostname; - const projectRef = host.split('.')[0]; - if (projectRef !== expectedProjectRef) - fail(`project ref mismatch: expected ${expectedProjectRef}, got ${projectRef}`); + const parsedUrl = new URL(supabaseUrl); + if (parsedUrl.protocol !== 'https:' || parsedUrl.hostname !== `${expectedProjectRef}.supabase.co`) + fail(`project host mismatch: expected https://${expectedProjectRef}.supabase.co`); async function probe(table) { const response = await get(`${supabaseUrl}/rest/v1/${table}?select=id&limit=1`, { - headers: { apikey: supabaseKey }, + headers: { apikey: supabaseKey, authorization: `Bearer ${supabaseKey}` }, }); const body = await response.json().catch(() => null); return { status: response.status, body }; diff --git a/src/lib/domain/release-smoke.test.ts b/src/lib/domain/release-smoke.test.ts index 9fff5805..d72393ac 100644 --- a/src/lib/domain/release-smoke.test.ts +++ b/src/lib/domain/release-smoke.test.ts @@ -17,6 +17,14 @@ describe('release smoke schema probe', () => { expect(classifyTableProbe(401, { message: 'Invalid API key' })).toBe('unknown'); }); + it('does not treat auth/JWT error codes as a valid key or present table', () => { + for (const code of ['PGRST301', 'PGRST302', 'PGRST305']) { + expect(classifyKeyPreflight(401, { code, message: 'auth error' })).toBe('unknown'); + expect(classifyTableProbe(401, { code, message: 'auth error' })).toBe('unknown'); + } + expect(classifyKeyPreflight(401, { code: '42501' })).toBe('valid'); + }); + it('treats only PGRST205/404 as a missing V2 table', () => { expect(classifyTableProbe(404, { code: 'PGRST205' })).toBe('missing'); expect(classifyTableProbe(404, {})).toBe('unknown');