Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion docs/OPERATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,24 @@ The Free project was backed up without relying on provider snapshots:

This procedure was executed against the hosted `dif` project and a local Supabase target on 2026-11-11; the restored counts matched the export, the owner login returned 200, anonymous REST returned 401, and the private Cloudinary image returned 235 bytes with a matching SHA-256. Auth passwords are intentionally re-provisioned, not copied from the backup.

### OPS 015–021 local metadata backup (2026-11-20)

`scripts/backup-metadata.mjs` and `scripts/restore-metadata.mjs` now cover **41/41 public tables**, including `episode_revisions` (the previous omission was an OPS gap). A local run restored into disposable `dif_restore_test` with:

- `countMismatches: []`, `episodeSceneJoinRows: 768`, `readyJobsWithMatchingQaHash: 5/5`;
- `metadataOk: true`, `coverageOk: true`, `shaVerified: true`;
- 2 local media blobs `verified_local`; 3 temporary E2E MP4s `missing` at verification time, so `mediaOk: false`/`ok: false` as designed (fail-closed, no false success).

Auth users, passwords, media bytes and signed URLs remain outside the dump. Remote restore and R2 lifecycle/GC remain manual.

## Bíblia audiovisual — retenção e cotas (WO-021)

- `style_presets` e `style_preset_revisions` são owner-read/service-write; revisões são imutáveis e nunca sobrescrevem um plano ou render antigo.
- Cada preset aceita até **200 revisões** (`style_revision_quota`). Ao atingir o limite, duplique o preset para continuar; não há poda automática de histórico aprovado.
- Overrides de episódio/cena são upserts pequenos, sem histórico próprio; `reducedMotion` aceita herdar/true/false. Enviar o formulário todo vazio chama `clear_*_style_override` e a camada volta a herdar.
- Planos novos congelam o estilo no primeiro save quando há preset/override configurado; sem estilo, nenhum snapshot é inventado. Planos existentes só recebem uma revisão nova quando o owner marca “Aplicar estilo atual” no timeline ou reconstrói; saves comuns preservam o snapshot. O render aplica cor, legenda, área segura e fonte ao snapshot; SFX/voz/capa/final continuam referências das telas especializadas.
- SFX referenciados são revalidados na resolução do snapshot. Assets removidos ou sem licença comercial/social são retirados do config efetivo com warning (`STYLE_SFX_UNAVAILABLE`/`STYLE_SFX_LICENSE`), sem alterar o preset aprovado.
- Backup/restore scripts incluem as quatro tabelas; a execução deste ciclo ficou pendente. Restaure presets antes das revisões e overrides depois de episódios/cenas para respeitar as FKs.
- Backup/restore scripts incluem as quatro tabelas e a execução local de 2026-11-20 está registrada na seção OPS acima. Restaure presets antes das revisões e overrides depois de episódios/cenas para respeitar as FKs.

## Temporary public access via Cloudflare Tunnel (owner-authorized)

Expand Down
6 changes: 3 additions & 3 deletions docs/V2_HARDENING_WO013.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# DIF-V2-WO-013 — Hardening operacional: quotas, backup, retenção e recuperação

**Status:** **PROMOTED (núcleo)**; unit **210+3**, PgTAP **155/155**, policy **29/25**, E2E **14/14**; CI `44410994788` e ARM64 `44410995020` em `fa236af` PASS; auditoria final **APPROVED WITH RESIDUALS**; squash-merged em `b1a1eaf` (PR #61); issue #30 fechada. Extensões OPS das WOs 015–021 permanecem obrigações posteriores. Sem deploy de worker/VPS.
**Status:** **PROMOTED (núcleo)**; unit **210+3**, PgTAP **155/155**, policy **29/25** no núcleo (após OPS 015–021: **36/41**), E2E **14/14**; CI `44410994788` e ARM64 `44410995020` em `fa236af` PASS; auditoria final **APPROVED WITH RESIDUALS**; squash-merged em `b1a1eaf` (PR #61); issue #30 fechada. **Extensões OPS 015–021 concluídas** em `docs/V2_OPS_015_021.md` (backup/restore das 41 tabelas, `episode_revisions` incluído, policy 36/41). Sem deploy de worker/VPS.
**Base:** `main` `7d15076` (checkpoint WO-012 promovido).
**Escopo:** WO-013 (#30) — núcleo operacional (quotas, limites de worker, saúde, backup/restore, retenção dry-run). As extensões OPS-2026-11-12 ligadas às WOs 015–021 ficam registradas como obrigações posteriores, sem infraestrutura duplicada.
**Escopo:** WO-013 (#30) — núcleo operacional (quotas, limites de worker, saúde, backup/restore, retenção dry-run). As extensões OPS-2026-11-12 ligadas às WOs 015–021 foram concluídas em `docs/V2_OPS_015_021.md`, sem infraestrutura duplicada.

## Entregue

Expand Down Expand Up @@ -74,7 +74,7 @@ A primeira auditoria independente retornou **CORRECTION REQUIRED** (F1–F11). A
- Quotas fixas podem precisar de ajuste após benchmark real de temporada.
- Limites de memória do FFmpeg não são impostos por cgroup; dependem de concorrência 1, timeout e monitoramento do host.
- Worker ainda usa service role ampla; escopo de menor privilégio continua aberto para WO-014.
- Extensões OPS das WOs 015–021 ainda pendentes.
- Extensões OPS das WOs 015–021 concluídas: backup/restore exercitado nas 41 tabelas; ver `docs/V2_OPS_015_021.md`.

## Gate

Expand Down
57 changes: 57 additions & 0 deletions docs/V2_OPS_015_021.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# DIF-V2-OPS-015-021 — extensões operacionais das WOs 015–021

**Status:** verificação e correções operacionais concluídas; CI `44782439445` PASS e auditoria independente **APPROVED WITH RESIDUALS**; merge/promoção pendentes. Sem deploy.
**Base:** `main` `3950ccb` (checkpoint WO-021 promovido).

## Escopo

Fechar as extensões OPS registradas na WO-013 para as features 015–021, sem duplicar infraestrutura:

- cobertura de backup/restore para **todas** as tabelas públicas, incluindo históricos V1 e as tabelas novas;
- guarda de política que impede a lista de backup/restore de divergir do schema;
- matriz de quotas/retenção por feature;
- execução real de backup e restore em stack local descartável, com contagens, joins e hashes;
- documentação de limites que permanecem manuais.

## Correções

1. `scripts/backup-metadata.mjs` e `scripts/restore-metadata.mjs` não incluíam `episode_revisions`; o dump continha os dados, mas a contagem/validação não cobria a tabela. Adicionada entre `episodes` e `scenes`.
2. `scripts/audit-policy.mjs` ganhou o invariante **“backup and restore cover every public table”**: as duas listas precisam ter exatamente as 41 tabelas públicas e cobrir cada uma. Policy passou de 35 para **36 invariantes / 41 tabelas**.
3. Backup/restore executados de ponta a ponta no stack local.

## Backup / restore executado (2026-11-20)

- Dump local `public` (schema + data-only via COPY), SHA-256 de ambos os arquivos, contagens por tabela e artefatos; diretório privado fora do repositório.
- **41/41 tabelas** com contagem restaurada idêntica (`countMismatches: []`), incluindo `episode_revisions` (173 registros).
- `shaVerified: true`; `metadataOk: true`; `coverageOk: true`; `artifactsWithoutQa: 0`.
- Join episódio → temporada → série → cenas: **768** linhas.
- QA: **5/5** jobs READY com `output_manifest.sha256` igual ao relatório de qualidade.
- Artefatos locais: 2 `verified_local`; 3 `missing` (ausentes no momento da verificação; eram MP4s temporários de E2E). O script falha fechado (`mediaOk: false`, `ok: false`) em vez de fingir sucesso — comportamento esperado.
- Nenhum segredo, usuário Auth, senha, mídia ou URL assinada entra no dump/summary.

## Matriz de quotas e retenção

| Feature | Tabela/histórico | Limite/retenção | Evidência |
| ------------ | -------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------- |
| Hook Lab | `hook_variants` | 3 chaves por versão de plano; histórico imutável; aplicação cria nova versão | migration WO-015 + PgTAP |
| Identidade | `character_identity_profiles`, versões | quota por perfil e prune service-only preservando decisões | migration WO-017 retention + PgTAP |
| Continuidade | `visual_continuity_reports` | quota de revisões + prune preservando as mais novas/decisões | migration WO-017 retention + PgTAP |
| Capas | `cover_revisions` | 500 revisões/episódio; prune preserva APPROVED | WO-018 + PgTAP |
| Final A/B | `choice_end_cards` | 200 drafts; prune preserva APPROVED | WO-019 + PgTAP |
| Retenção | `analytics_snapshots` | 5.000 revisões/post; histórico imutável | WO-020 + PgTAP |
| Estilo | `style_preset_revisions` | 200 revisões/preset; histórico imutável | WO-021 + PgTAP |
| Render | `render_jobs`/bytes | 20 jobs e 2 GiB/dia; 3 ativos/episódio; 100 na fila | WO-013 + PgTAP |

Quotas de posts/variantes/imports de retenção continuam limitadas apenas por validação dos contadores (0–5.000/import) e uso owner-only; não há quota dura nem poda automática de posts/variantes. R2 lifecycle/GC permanece manual.

## Limites conhecidos

- Backup cobre somente o schema `public`; Auth, senhas, bytes de mídia e URLs assinadas ficam fora por desenho. `chmod` POSIX não restringe ACL no Windows: os artefatos locais herdam ACL do sandbox e não são criptografados; tratar como dado de negócio e restringir/criptografar antes de compartilhar.
- Restore automatizado é restrito a banco local descartável; produção exige runbook/psql aprovado.
- `mediaOk` pode ser falso quando artefatos temporários de E2E estão ausentes; o exit code permanece fail-closed.
- Quotas fixas (20 jobs/2 GiB, 200/500/5.000 revisões) não substituem monitoramento do free tier.
- R2 lifecycle/GC manual; sem cgroup nativo de CPU/RAM; worker usa service role ampla até WO-014.

## Próximo

WO-014 (#31) — regressão integral, worker/deploy autorizado, smoke e checkpoint final.
43 changes: 43 additions & 0 deletions docs/evidence/ops-015-021/tests.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# DIF-V2-OPS-015-021 — evidence

Date: 2026-11-20 (America/Sao_Paulo)
Branch: `feat/dif-v2-ops-015-021` (base `main` `3950ccb`)

## Static

- `npm run audit:policy`: **36 invariants / 41 tables** PASS, including the new
“backup and restore cover every public table” invariant.
- Backup/restore table lists: **41/41** tables each (`episode_revisions` restored to
the lists after the audit gap).
- `npm run check`: 0 errors / 0 warnings.
- `npm run lint`: PASS.
- `npm test`: **351 passed + 3 skipped** (CI baseline).
- `npm run test:db`: **247/247** PgTAP PASS.
- CI quality `44782439445` PASS (10m59s), Sonar/Socket/Vercel PASS.
- Auditoria independente: **APPROVED WITH RESIDUALS**; findings textuais corrigidos antes do merge.

## Backup / restore (local disposable stack)

- Command: `npm run backup:metadata -- --out-dir <private dir outside repo>`.
- 41/41 table counts captured; `episode_revisions = 173`. `restore-metadata.mjs`
now requires the summary to contain exactly the 41 allowed table keys.
- SHA-256 of `schema.sql` and `data.sql` verified before restore (`shaVerified: true`).
- Restore target: `dif_restore_test` in `supabase_db_dif-studio-local` (disposable).
- Result:
- `countMismatches: []`
- `episodeSceneJoinRows: 768`
- `readyJobsWithMatchingQaHash: 5/5` (`expectedReadyJobsWithQa: 5`)
- `metadataOk: true`, `coverageOk: true`, `artifactsWithoutQa: 0`
- `mediaOk: false`, `ok: false` because 3 temporary E2E MP4 paths were absent at
verification time (`missing`); 2 local artifacts were `verified_local`.
- This is the intended fail-closed behavior: metadata counts and hashes are proven,
while missing media is reported instead of silently accepted. The `ok:false` is
expected and the command exits non-zero.
- No Auth users, passwords, media bytes, signed URLs or secrets were included.

## Not exercised

- Remote/hosted restore (requires separate approved runbook/target).
- R2 lifecycle/GC (manual; bucket token lacks lifecycle permission).
- Auth identity restore (manual step).
- Full media-byte backup (out of scope by design).
47 changes: 30 additions & 17 deletions scripts/audit-policy.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readFile } from 'node:fs/promises';
import { readdir, readFile } from 'node:fs/promises';
import process from 'node:process';

const migration = await readFile('supabase/migrations/20261109000100_initial_schema.sql', 'utf8');
Expand Down Expand Up @@ -99,6 +99,7 @@
'utf8',
);
const retentionScript = await readFile('scripts/retention.mjs', 'utf8');
const backupScript = await readFile('scripts/backup-metadata.mjs', 'utf8');
const restoreScript = await readFile('scripts/restore-metadata.mjs', 'utf8');
const hook = await readFile('src/hooks.server.ts', 'utf8');
const config = await readFile('src/lib/server/config.ts', 'utf8');
Expand All @@ -124,24 +125,36 @@
const timelineRoute = await readFile('src/routes/app/timeline/+page.server.ts', 'utf8');
const editPlans = await readFile('src/lib/server/video-edit-plans.ts', 'utf8');

const tables = [
...migration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...videoMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...editPlanMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...renderJobMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...narrationMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...captionMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...audioMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...qualityMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...hookMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...identityMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...coverMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...endCardMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...retentionLabMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
...styleBibleMigration.matchAll(/^create table public\.(\w+)\s*\(/gm),
].map((match) => match[1]);
const migrationDir = 'supabase/migrations';
const migrationFiles = (await readdir(migrationDir)).filter((file) => file.endsWith('.sql'));
const tableSet = new Set();
for (const file of migrationFiles.sort((left, right) => left.localeCompare(right))) {
const sql = await readFile(`${migrationDir}/${file}`, 'utf8');

Check warning on line 132 in scripts/audit-policy.mjs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=KayzenRoot_dep-instfinal&issues=AaH6EqBxLZenLiD-z73c&open=AaH6EqBxLZenLiD-z73c&pullRequest=69
for (const match of sql.matchAll(/create table(?: if not exists)?\s+public\.(\w+)\s*\(/gi))
tableSet.add(match[1]);
}
const tables = [...tableSet].sort((left, right) => left.localeCompare(right));
const checks = [
['41 owner-scoped public tables', tables.length === 41],
[
'backup and restore cover every public table',
(() => {
const backupBlock = backupScript.match(/const tableNames = \[([\s\S]*?)\];/)?.[1] ?? '';
const restoreBlock =
restoreScript.match(/const allowedTables = new Set\(\[([\s\S]*?)\]\);/)?.[1] ?? '';
const backupTables = [...backupBlock.matchAll(/'([a-z][a-z0-9_]*)'/g)].map(
(match) => match[1],
);
const restoreTables = [...restoreBlock.matchAll(/'([a-z][a-z0-9_]*)'/g)].map(
(match) => match[1],
);
return (
backupTables.length === tables.length &&
restoreTables.length === tables.length &&
tables.every((table) => backupTables.includes(table) && restoreTables.includes(table))
);
})(),
],
[
'every table has forced RLS',
migration.includes('enable row level security') &&
Expand Down
1 change: 1 addition & 0 deletions scripts/backup-metadata.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ const tableNames = [
'characters',
'lore_facts',
'episodes',
'episode_revisions',
'scenes',
'choices',
'polls',
Expand Down
9 changes: 7 additions & 2 deletions scripts/restore-metadata.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const allowedTables = new Set([
'characters',
'lore_facts',
'episodes',
'episode_revisions',
'scenes',
'choices',
'polls',
Expand Down Expand Up @@ -77,11 +78,15 @@ for (const table of Object.keys(summary.counts)) {
if (!allowedTables.has(table) || !/^[a-z][a-z0-9_]{0,63}$/.test(table))
throw new Error(`Unexpected backup table: ${table}`);
}
if (Object.keys(summary.counts).length !== allowedTables.size)
throw new Error('Backup summary must cover every allowed table.');
const schemaBytes = readFileSync(join(backupDir, 'schema.sql'));
const dataBytes = readFileSync(join(backupDir, 'data.sql'));
const schemaSha = createHash('sha256').update(schemaBytes).digest('hex');
const dataSha = createHash('sha256').update(dataBytes).digest('hex');
if (schemaSha !== summary.files?.schema?.sha256 || dataSha !== summary.files?.data?.sha256)
const shaVerified =
schemaSha === summary.files?.schema?.sha256 && dataSha === summary.files?.data?.sha256;
if (!shaVerified)
throw new Error('Backup SHA-256 mismatch; refusing to restore a corrupted or altered dump.');
const schemaSql = schemaBytes.toString('utf8');
const dataSql = dataBytes.toString('utf8');
Expand Down Expand Up @@ -207,7 +212,7 @@ const report = {
generatedAt: new Date().toISOString(),
backupDir,
database,
shaVerified: true,
shaVerified,
countMismatches,
episodeSceneJoinRows: Number(joinCheck),
expectedReadyJobsWithQa: expectedQa,
Expand Down