diff --git a/docs/GUARDRAILS.md b/docs/GUARDRAILS.md index c0d5cb95..8b59b953 100644 --- a/docs/GUARDRAILS.md +++ b/docs/GUARDRAILS.md @@ -4,41 +4,44 @@ Ledger dos guardrails determinísticos colhidos de `kind:agent-miss` (fluxo `pnp **Classes (escada do Pass 3 D6 / skill engineering-audit passo 4b):** 1 tipo (estado ruim irrepresentável) · 2 ESLint · 3 spec de convenção · 4 análise estática em CI (knip/madge) · 5 pin comportamental · 6 doc/convenção (judgment-only declarado — não fingir que doc é guarda). +**Provenance (Pass 5, 2026-08-02):** o reopen público remapeou Issues do archive — `#52→#48`, `#53→#49`, `#54→#50`, `#73→#54`. As guardas abaixo citam os **números públicos**; PRs do Pass 4 (#91–#95) seguem como origem histórica do código. + ## Ativos -| Guarda | Origem | Classe | Mecanismo | Status | -| ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | -| `agent:ship` exige stamp de /simplify casado com HEAD; PR Ready + auto-merge + watch até MERGED | [#83](https://github.com/fsolla/teqo/issues/83) | 3 (script + hooks) | `scripts/agent-ship.mjs`, `.cursor/hooks/guard-pr-create.mjs` (bloqueia `gh pr create` manual), `.cursor/hooks/pr-merge-watchdog.mjs` (re-engata com PR aberto) | vivo desde 2026-07-31 (PR #89); miss fechada no Pass 4 | -| Alocador de municípios em specs — sem slug fixo + mutação; sem `municipio=` em e2e; regex de nome de catálogo ancorada | [#73](https://github.com/fsolla/teqo/issues/73) | 3 | `tests/unit/testMunicipalityAllocatorConventions.unit.spec.ts` (3 regras; mutações = assign/touch/create\*/`payload.update` municipality) | PR [#93](https://github.com/fsolla/teqo/pull/93) (Pass 4) | -| Sheet compartilhada por lista — chip cells exigem `CampaignListSheetProvider`; invariante dev no overlay | [#52](https://github.com/fsolla/teqo/issues/52) | 3 + 5 | `tests/unit/sharedSheetHostConventions.unit.spec.ts`; `console.error` development-only em `CampaignCellEditOverlay` | PR [#94](https://github.com/fsolla/teqo/pull/94) (Pass 4) | -| Navegação e2e assentada — goto→goto sem settle falha o build | [#54](https://github.com/fsolla/teqo/issues/54) | 3 | `tests/unit/e2eNavigationConventions.unit.spec.ts` (settle = await expect/waitForURL/click/reload/login/catch) | PR [#95](https://github.com/fsolla/teqo/pull/95) (Pass 4) | -| Readiness de autenticador virtual antes da cerimônia WebAuthn | [#53](https://github.com/fsolla/teqo/issues/53) | 3 | mesma spec (spec com `WebAuthn.addVirtualAuthenticator` deve chamar `expectCampaignBiometricsReady(`) | PR [#95](https://github.com/fsolla/teqo/pull/95) (Pass 4) | -| Convenção de navegação e2e (goto = cold load/contrato; in-shell = continuidade) | [#54](https://github.com/fsolla/teqo/issues/54) | 6 (**judgment-only**) | parágrafo em `docs/TESTING.md` | PR [#95](https://github.com/fsolla/teqo/pull/95) (Pass 4) | -| Update de globals públicos nunca "qualquer autenticado" | P0 do Pass 4 (sem issue) | 3 | `tests/unit/globalAccessConventions.unit.spec.ts` ban `Boolean(user)` em `src/globals` | PR [#91](https://github.com/fsolla/teqo/pull/91) (Pass 4) | -| Loaders de notificação tipados pelo ator (recipientID arbitrário irrepresentável) | P0 adjacente do Pass 4 | 1 | assinatura `(payload, user: CampaignUser)` + `overrideAccess: false` sob `canReadOwnNotifications` | PR [#91](https://github.com/fsolla/teqo/pull/91) (Pass 4) | -| Die-helpers da CLI importados onde usados; `DAY_MS` single-source | P1 do Pass 4 (sem issue) | 3 | `tests/unit/scriptCliConventions.unit.spec.ts` | PR [#92](https://github.com/fsolla/teqo/pull/92) (Pass 4) | -| `src/lib` não type-importa `@/utilities/**` (direção única também para tipos) | dodge do Pass 3 (suggestionCatalog) | 2 | ESLint `no-restricted-imports` `allowTypeImports: false` na zona `src/lib` | PR [#92](https://github.com/fsolla/teqo/pull/92) (Pass 4) | -| Local API com `user` sempre declara `overrideAccess`; import dinâmico de módulos server banido em utilities | guarda ausente (medida baseline 59/0) | 3 | `tests/unit/localApiOverrideAccessConventions.unit.spec.ts` | PR [#92](https://github.com/fsolla/teqo/pull/92) (Pass 4) | +| Guarda | Origem | Classe | Mecanismo | Status | +| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------- | +| `agent:ship` exige stamp de /simplify casado com HEAD; PR Ready + auto-merge + watch até MERGED | [#83](https://github.com/fsolla/teqo/issues/83) | 3 (script + hooks) | `scripts/agent-ship.mjs`, `.cursor/hooks/guard-pr-create.mjs`, `.cursor/hooks/pr-merge-watchdog.mjs` | vivo desde 2026-07-31 (PR #89) | +| Alocador de municípios em specs — sem slug fixo + mutação; sem `municipio=` em e2e; regex de nome ancorada | [#54](https://github.com/fsolla/teqo/issues/54) (archive #73) | 1 + 3 | `getMunicipality()` sem parâmetro de slug (Pass 5); `tests/unit/testMunicipalityAllocatorConventions.unit.spec.ts` | vivo Pass 4; **endurecido Pass 5** (tipo) | +| Sheet compartilhada — `variant="sheet"` exige provider ou leaf allowlist | [#48](https://github.com/fsolla/teqo/issues/48) (archive #52) | 3 + 5 | `tests/unit/sharedSheetHostConventions.unit.spec.ts`; invariante dev em `CampaignCellEditOverlay` | vivo Pass 4; **endurecido Pass 5** (sheet variant + allowlist) | +| Navegação e2e assentada — goto→goto sem settle falha o build | [#50](https://github.com/fsolla/teqo/issues/50) (archive #54) | 3 | `tests/unit/e2eNavigationConventions.unit.spec.ts` | vivo Pass 4; provenance Pass 5 | +| Readiness de autenticador virtual — `expectCampaignBiometricsReady` **depois** de `addVirtualAuthenticator` | [#49](https://github.com/fsolla/teqo/issues/49) (archive #53) | 3 | mesma spec (ordem das _calls_, Pass 5) | vivo Pass 4; **endurecido Pass 5** (ordem) | +| Convenção de navegação e2e (goto = cold load; in-shell = continuidade) | [#50](https://github.com/fsolla/teqo/issues/50) | 6 (**judgment-only**) | parágrafo em `docs/TESTING.md` | vivo | +| Update de globals públicos nunca "qualquer autenticado" | P0 do Pass 4 | 3 | `tests/unit/globalAccessConventions.unit.spec.ts` | vivo (PR #91) | +| Loaders de notificação tipados pelo ator | P0 adjacente do Pass 4 | 1 | assinatura `(payload, user: CampaignUser)` + `overrideAccess: false` | vivo (PR #91) | +| Die-helpers da CLI importados onde usados; `DAY_MS` single-source | P1 do Pass 4 | 3 | `tests/unit/scriptCliConventions.unit.spec.ts` | vivo (PR #92) | +| `src/lib` não type-importa `@/utilities/**` | dodge do Pass 3 | 2 | ESLint `allowTypeImports: false` na zona `src/lib` | vivo (PR #92) | +| Local API com `user` sempre declara `overrideAccess`; import dinâmico server banido em utilities | Pass 4 | 3 | `tests/unit/localApiOverrideAccessConventions.unit.spec.ts` | vivo (PR #92) | +| Ledger `docs/GUARDRAILS.md` + harvest no engineering-audit | [#41](https://github.com/fsolla/teqo/issues/41) OPS2 | 6 → 3 | este arquivo + skill `engineering-audit` passo 0b/4b | **fechado Pass 5** (pipeline vivo desde Pass 4) | ## Precedentes vivos (anteriores ao primeiro harvest) -| Guarda | Origem | Classe | Mecanismo | -| ------------------------------------------------------------------------ | ------------------------------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------- | -| Vocabulário banido (Praça/Núcleo/Plano de Ação, accent-tolerant) | C13 / W4f / P3-K | 3 | `codebaseConventions.unit.spec.ts` | -| `server-only` em utilities acopladas (sweep payload/next/\*) | Pass 2 W2 / P3-K | 3 | `codebaseConventions.unit.spec.ts` | -| Escadas de formActions nos wrappers (`runCampaignFormAction`/`Redirect`) | W4d / C8 F4b | 3 | `codebaseConventions.unit.spec.ts` (filename `*FormActions.ts` — dodge `actions/*.ts` ledgerado) | -| Ratchet de bypass admin não documentado | P3-E | 3 | `codebaseConventions.unit.spec.ts` (por arquivo, só diminui) | -| Mensagens de recusa como constantes + correspondência throw↔safelist | P3-A | 3 | `codebaseConventions.unit.spec.ts:216-263` | -| `as never` banido | Pass 1 | 2 | ESLint `no-restricted-syntax` | -| `src/lib` não importa `utilities/` (valores) | Pass 2 W2 | 2 | ESLint `no-restricted-imports` | -| 0 ciclos de import | Pass 2 | 4 | madge (`pnpm check:cycles`) | -| Dead code (arquivos/deps/exports em erro) | Pass 2 W4b | 4 | knip em CI | -| `migration-lock` (≤1 PR aberto tocando schema) | agentes paralelos | 4 | job em `ci-pr.yml` | -| PR só `docs/plans/` sem `Closes`/`Fixes`/`Resolves` | [#116](https://github.com/fsolla/teqo/issues/116) OPS12 | 4 | `scripts/lib/plansOnlyClosesGuard.mjs` + `scripts/check-plans-only-pr-closes.mjs` + job `plans-only-closes` em `ci-pr.yml` | -| Seed mínimo obrigatório com migration (contrato manifest) | OPS fluxo PR | 3 + 5 | `tests/unit/seedMinimalManifest.unit.spec.ts` + job CI migrate→seed→int | -| Regex de template ancorada em e2e | P3-C | 3 | `codebaseConventions.unit.spec.ts` (ampliada para literais no Pass 4) | -| Consent fail-closed por chave estável | D3/Onda 0 | 5 | pins int `submitWhatsapp`/liderança/apoiador | +| Guarda | Origem | Classe | Mecanismo | +| ------------------------------------------------------------------------ | ------------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | +| Vocabulário banido (Praça/Núcleo/Plano de Ação, accent-tolerant) | C13 / W4f / P3-K | 3 | `codebaseConventions.unit.spec.ts` | +| `server-only` em utilities acopladas (sweep payload/next/\*) | Pass 2 W2 / P3-K | 3 | `codebaseConventions.unit.spec.ts` | +| Escadas de formActions nos wrappers (`runCampaignFormAction`/`Redirect`) | W4d / C8 F4b | 3 | `codebaseConventions.unit.spec.ts` (filename `*FormActions.ts` — dodge `actions/*.ts` ledgerado) | +| Ratchet de bypass admin não documentado | P3-E | 3 | `codebaseConventions.unit.spec.ts` (por arquivo, só diminui) | +| Mensagens de recusa como constantes + correspondência throw↔safelist | P3-A | 3 | `codebaseConventions.unit.spec.ts:216-263` | +| `as never` banido | Pass 1 | 2 | ESLint `no-restricted-syntax` | +| `src/lib` não importa `utilities/` (valores) | Pass 2 W2 | 2 | ESLint `no-restricted-imports` | +| 0 ciclos de import | Pass 2 | 4 | madge (`pnpm check:cycles`) | +| Dead code (arquivos/deps/exports em erro) | Pass 2 W4b | 4 | knip em CI | +| `migration-lock` (≤1 PR aberto tocando schema) | agentes paralelos | 4 | job em `ci-pr.yml` | +| PR só `docs/plans/` sem `Closes`/`Fixes`/`Resolves` | [#116](https://github.com/fsolla/teqo/issues/116) OPS12 | 4 | `scripts/lib/plansOnlyClosesGuard.mjs` + job `plans-only-closes` em `ci-pr.yml` | +| Seed mínimo obrigatório com migration (contrato manifest) | OPS fluxo PR | 3 + 5 | `tests/unit/seedMinimalManifest.unit.spec.ts` + job CI migrate→seed→int | +| Regex de template ancorada em e2e | P3-C | 3 | `codebaseConventions.unit.spec.ts` (ampliada para literais no Pass 4) | +| Consent fail-closed por chave estável | D3/Onda 0 | 5 | pins int `submitWhatsapp`/liderança/apoiador | ## Misses colhidas aguardando guarda (fila do harvest) -(nenhuma — todas as 5 abertas em 2026-07-31 foram classificadas: 4 com guarda shippada + 1 com guarda já viva. Novas `kind:agent-miss` entram aqui até o próximo audit.) +(nenhuma — Pass 5 fechou a fila remapeada #48/#49/#50/#54 e OPS2 #41.) diff --git a/tests/helpers/campaignFixtures.ts b/tests/helpers/campaignFixtures.ts index ddb04b80..38dda782 100644 --- a/tests/helpers/campaignFixtures.ts +++ b/tests/helpers/campaignFixtures.ts @@ -466,16 +466,10 @@ export class CampaignFixtures { * left behind by a previously crashed run are purged on claim (allocation * uniqueness makes this safe: nothing live can reference this municipality). */ - async getMunicipality(slug?: string): Promise { - let requestedSlug = slug - if (!requestedSlug) { - const index = await nextAllocatedMunicipalityIndex( - this.rootPayload, - municipalityCatalog.length, - ) - requestedSlug = municipalityCatalog[index]!.slug - this.municipalityCursor += 1 - } + async getMunicipality(): Promise { + const index = await nextAllocatedMunicipalityIndex(this.rootPayload, municipalityCatalog.length) + const requestedSlug = municipalityCatalog[index]!.slug + this.municipalityCursor += 1 const result = await this.rootPayload.find({ collection: 'municipality', @@ -490,7 +484,7 @@ export class CampaignFixtures { `Seeded municipality "${requestedSlug}" not found — run migrations on the test database.`, ) } - if (!slug) await purgeMunicipalityResidue(this.rootPayload, municipality.id) + await purgeMunicipalityResidue(this.rootPayload, municipality.id) this.touchedMunicipalities.add(municipality.id) return municipality } diff --git a/tests/unit/e2eNavigationConventions.unit.spec.ts b/tests/unit/e2eNavigationConventions.unit.spec.ts index 07182184..1c485460 100644 --- a/tests/unit/e2eNavigationConventions.unit.spec.ts +++ b/tests/unit/e2eNavigationConventions.unit.spec.ts @@ -2,18 +2,17 @@ import { readdirSync, readFileSync } from 'node:fs' import { relative, resolve } from 'node:path' import { describe, expect, it } from 'vitest' -// Miss #54 (2026-07-30): a `page.goto` fired while the previous heavy RSC -// navigation was still in flight aborted with `net::ERR_ABORTED` -// (campaignSavedFilters, prod build). `goto` stays legal for cold loads and -// URL contracts — the anti-pattern is two gotos with NOTHING between them -// that settles the first navigation. A settle is any awaited interaction -// with the landed page (assertion, fill, click, reload, login…): it proves -// the previous route rendered before the next one starts. +// Miss #50 (public reopen of archive #54, 2026-07-30): a `page.goto` fired while +// the previous heavy RSC navigation was still in flight aborted with +// `net::ERR_ABORTED` (campaignSavedFilters, prod build). `goto` stays legal for +// cold loads and URL contracts — the anti-pattern is two gotos with NOTHING +// between them that settles the first navigation. // -// Miss #53 (2026-07-30): the biometrics probe is one-shot per island mount, -// so a ceremony that starts before the CDP virtual authenticator answers -// never sees the enrollment UI. Specs registering a virtual authenticator -// must gate on `expectCampaignBiometricsReady` first. +// Miss #49 (public reopen of archive #53, 2026-07-30): the biometrics probe is +// one-shot per island mount, so a ceremony that starts before the CDP virtual +// authenticator answers never sees the enrollment UI. Specs must +// `await addVirtualAuthenticator` *then* `await expectCampaignBiometricsReady` +// before the enrollment surface (Pass 5 hardening: call-site order). const e2eRoot = resolve(process.cwd(), 'tests/e2e') @@ -38,7 +37,7 @@ const SETTLE_TOKENS = [ 'expectCampaignBiometricsReady(', ] as const -describe('e2e navigation discipline (miss #54)', () => { +describe('e2e navigation discipline (miss #50)', () => { it('never fires two page.goto without settling the first navigation', () => { const offenders: string[] = [] @@ -62,25 +61,34 @@ describe('e2e navigation discipline (miss #54)', () => { expect( offenders, - 'settle the first navigation (await expect/waitForURL/click…) before the next page.goto, or navigate in-shell (miss #54)', + 'settle the first navigation (await expect/waitForURL/click…) before the next page.goto, or navigate in-shell (miss #50)', ).toEqual([]) }) }) -describe('e2e WebAuthn virtual authenticator (miss #53)', () => { - it('gates every virtual-authenticator spec on expectCampaignBiometricsReady', () => { +describe('e2e WebAuthn virtual authenticator (miss #49)', () => { + it('registers the virtual authenticator before expectCampaignBiometricsReady', () => { const offenders: string[] = [] for (const file of specFiles) { const source = readFileSync(file, 'utf8') - if (!source.includes('WebAuthn.addVirtualAuthenticator')) continue - if (source.includes('expectCampaignBiometricsReady(')) continue - offenders.push(relative(process.cwd(), file)) + // Call sites only — ignore the helper definition and doc comments. + const addCall = source.search(/await\s+addVirtualAuthenticator\s*\(/) + if (addCall < 0 && !source.includes('WebAuthn.addVirtualAuthenticator')) continue + const effectiveAdd = + addCall >= 0 + ? addCall + : source.search(/\.send\(\s*['"]WebAuthn\.addVirtualAuthenticator['"]/) + if (effectiveAdd < 0) continue + const readyCall = source.search(/await\s+expectCampaignBiometricsReady\s*\(/) + if (readyCall < 0 || readyCall < effectiveAdd) { + offenders.push(relative(process.cwd(), file)) + } } expect( offenders, - 'call expectCampaignBiometricsReady(page) before the surface whose island probes the authenticator', + 'await addVirtualAuthenticator(…) then await expectCampaignBiometricsReady(page) before the enrollment UI', ).toEqual([]) }) }) diff --git a/tests/unit/sharedSheetHostConventions.unit.spec.ts b/tests/unit/sharedSheetHostConventions.unit.spec.ts index de42e059..58b855f4 100644 --- a/tests/unit/sharedSheetHostConventions.unit.spec.ts +++ b/tests/unit/sharedSheetHostConventions.unit.spec.ts @@ -2,19 +2,24 @@ import { readdirSync, readFileSync } from 'node:fs' import { relative, resolve } from 'node:path' import { describe, expect, it } from 'vitest' -// Miss #52 (2026-07-30): the municipalities list hydrated ~125 idle Drawer -// roots (25 rows × 5 sheet controls) and prod tripped React #130 — CSS -// `display:none` does not remove hydration cost. The fix pattern is ONE -// shared Drawer per list surface via `CampaignListSheetProvider`, with cell -// bodies portaled into it. The provider reached the municípios mobile cards -// and this pass (2026-07-31) the three chip-relation lists (lideranças, -// dobradinhas, assessores) — this guard keeps the next chip-cell table from -// mounting sheet overlays providerless. -describe('shared sheet host for chip-relation cells (miss #52)', () => { - const componentRoots = ['src/components', 'src/app'] as const - const chipCellUsage = / { +describe('shared sheet host for chip-relation cells (miss #48)', () => { + const componentRoots = ['src/components', 'src/app'] as const + const sheetVariant = /variant\s*=\s*["']sheet["']/ + /** Leaves that open sheets but are always composed under a provider parent. */ + const sheetLeafAllowlist = new Set([ + 'src/components/campaign/municipality/MunicipalityListMobileCards.tsx', + 'src/components/campaign/shared/RelationChipCell.tsx', + 'src/components/campaign/shared/CampaignCellEditOverlay.tsx', + 'src/components/campaign/shared/MunicipalityPortfolioCell.tsx', + ]) + + it('wraps every sheet-variant surface in CampaignListSheetProvider (or allowlists the leaf)', () => { const offenders: string[] = [] for (const root of componentRoots) { @@ -26,16 +31,18 @@ describe('shared sheet host for chip-relation cells (miss #52)', () => { .map((entry) => resolve(entry.parentPath, entry.name)) for (const file of files) { + const rel = relative(process.cwd(), file) const source = readFileSync(file, 'utf8') - if (!chipCellUsage.test(source)) continue + if (!sheetVariant.test(source)) continue if (source.includes('CampaignListSheetProvider')) continue - offenders.push(relative(process.cwd(), file)) + if (sheetLeafAllowlist.has(rel)) continue + offenders.push(rel) } } expect( offenders, - 'chip-relation cells open sheet overlays on coarse pointers — wrap the table in CampaignListSheetProvider (one shared Drawer per list)', + 'sheet overlays need CampaignListSheetProvider (one shared Drawer) — add the provider or extend the leaf allowlist with a parent that already wraps', ).toEqual([]) }) }) diff --git a/tests/unit/testMunicipalityAllocatorConventions.unit.spec.ts b/tests/unit/testMunicipalityAllocatorConventions.unit.spec.ts index e267f3e7..1b93b957 100644 --- a/tests/unit/testMunicipalityAllocatorConventions.unit.spec.ts +++ b/tests/unit/testMunicipalityAllocatorConventions.unit.spec.ts @@ -4,16 +4,13 @@ import { describe, expect, it } from 'vitest' import { municipalityCatalog } from '@/lib/municipalityCatalog' -// Miss #73 (2026-07-31): int specs pinning seeded municipality slugs -// (`getMunicipality('cairu')` et al.) and mutating them deadlocked -// `municipality_rels` under the parallel suite (Postgres 40P01), and e2e specs -// deep-linking `?municipio=cairu` raced the same row from two workers. The -// allocator (`getMunicipality()` / `claimMunicipality()`, Postgres sequence) +// Miss #54 (public reopen of archive #73, 2026-07-31): int specs pinning seeded +// municipality slugs (`getMunicipality('cairu')` et al.) and mutating them +// deadlocked `municipality_rels` under the parallel suite (Postgres 40P01), and +// e2e specs deep-linking `?municipio=cairu` raced the same row from two workers. +// The allocator (`getMunicipality()` / `claimMunicipality()`, Postgres sequence) // hands out a unique row per claim; pinning is what breaks the contract. -// -// Rule 3 is the literal-regex sibling of the anchored-template guard (P3-C): -// `new RegExp(\`…\`)` was hardened there, but `/Cairu/i` literals dodged it — -// and catalog names are not prefix-unique (Conde/Condeúba, Barra ×4, Laje ×3). +// Pass 5: `getMunicipality()` no longer accepts a slug argument (type-level). const repoRoot = process.cwd() const repoPath = (absolute: string) => relative(repoRoot, absolute) @@ -38,7 +35,7 @@ const MUTATION_PATTERN = new RegExp( ].join('|'), ) -describe('municipality allocator discipline (miss #73)', () => { +describe('municipality allocator discipline (miss #54)', () => { it('never pins a fixed-slug municipality in a spec that mutates municipalities', () => { const offenders: string[] = []