mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
docs: Pass 5 engineering audit artifacts
Ledger + plan for the 2026-08-02 audit (offline/hybrid delta since Pass 4): P0 logout wipe, P1 hybrid/CAS, remapped miss provenance, and P2 workstreams. Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
1b7caf7cf5
commit
88026fe1d3
4 changed files with 221 additions and 7 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# Improve Code Quality Plan
|
||||
|
||||
Four passes so far: **Pass 1** (2026-07-23/24, phases 0–6 below, all done), **Pass 2** (2026-07-25, see [Pass 2](#pass-2--engineering-consolidation-2026-07-25)), **Pass 3** (2026-07-28, audit + plan, see [Pass 3](#pass-3--engineering-audit--consolidation-2026-07-28)) and **Pass 4** (2026-07-31, audit + P0/P1 remediation + miss guardrails in-session, see [Pass 4](#pass-4--engineering-audit--remediation--guardrails-2026-07-31)).
|
||||
Five passes so far: **Pass 1** (2026-07-23/24, phases 0–6 below, all done), **Pass 2** (2026-07-25, see [Pass 2](#pass-2--engineering-consolidation-2026-07-25)), **Pass 3** (2026-07-28, audit + plan, see [Pass 3](#pass-3--engineering-audit--consolidation-2026-07-28)), **Pass 4** (2026-07-31, audit + P0/P1 remediation + miss guardrails in-session, see [Pass 4](#pass-4--engineering-audit--remediation--guardrails-2026-07-31)) and **Pass 5** (2026-08-02, audit + P0/P1 remediation + remapped-miss guardrail provenance, see [Pass 5](#pass-5--engineering-audit--offlinehybrid-remediation--guardrails-2026-08-02)).
|
||||
|
||||
## Context
|
||||
|
||||
|
|
@ -211,3 +211,51 @@ Statuses: pending · in-progress · awaiting-evidence · done · deferred: \<rea
|
|||
- [x] Artifacts PR = Ready + auto-merge (mesmo contrato `agent-pr-workflow`; sem exceção de merge humano); remediation PRs merge independently
|
||||
- [ ] P4-A → P4-L as independent deliveries ([entrega-engenharia-p4.md](plans/entrega-engenharia-p4.md)); oversized items → Issue rastreável via `plan-issue`
|
||||
- [ ] Leftovers → ledger via `capture-review-debts`
|
||||
|
||||
---
|
||||
|
||||
# Pass 5 — Engineering Audit + Offline/Hybrid Remediation + Guardrails (2026-08-02)
|
||||
|
||||
## Context
|
||||
|
||||
- **Started:** 2026-08-02 — second **autonomous (Cursor Cloud)** execution of `engineering-audit`.
|
||||
- **Precheck (fail-closed):** agent pool **desligado** (`pnpm agent:pool -- status`); solitary audit confirmed.
|
||||
- **Delta anchor:** Pass 4 (2026-07-31). **573 files / 442 commits** in ~2 days — dominant churn is the offline/hybrid ops surface (OH11–OH14, CL9 list unified, quick actions, B57 vote-summary snapshots): `src/lib` ×132 touches, `opsSync` ×65, `shell` ×53, **89 new `src/` modules**.
|
||||
- **Method:** canon loaded; hotspot map (delta + churn + static gates); **five parallel sweeps** (lib+scripts, utilities+access, components, app+collections+globals, tests/guards); consolidation hunt under anti-DRY; 4 remapped `kind:agent-miss` issues harvested (+ OPS2 #41); open ledger rows re-verified; P0/P1 + miss provenance remediations in-session.
|
||||
- **Baseline:** green — `tsc` 0, `lint` 0 warnings, `knip` 0 findings (known `payload.config.ts` loader noise, ledger P3), madge 0 cycles (**858 files**, +84 since Pass 4). Unit inventory **173 files / 1,383 tests**; e2e **20 specs / 61 cases** (was 17/48 at Pass 4).
|
||||
|
||||
## Audit headlines (all measured)
|
||||
|
||||
- **1 P0:** logout wipe for campaignOps outboxes/mirror is gated on in-memory singletons — after a cold reload (singleton null) IndexedDB/`teqo-ops-*` + mirror OPFS/IDB survive `clearCampaignOpsStorage`, so the next user on a shared device can hydrate another actor's queued writes / operational mirror. **Remediated in-session.**
|
||||
- **2 P1s:** (a) activity hybrid edit silently drops `tasks`/`demandsJson` while still rendering those fields, and omits `responsible`/`leadership` when cleared (null never sent); (b) `assertCampaignDocCas` is check-then-write TOCTOU without a document advisory lock — concurrent writers both pass CAS (**0 concurrent pins**). Push `queueMicrotask` before transaction commit remains a third P1 (ledgered + workstream — full transactional outbox is M).
|
||||
- **Rejected-by-product (not P0):** B57 option A intentionally shows advisors the **statewide** Δ while hero stays portfolio-scoped (`docs/plans/delta-7-dias-estimativa-inicio.md`); collection `read: isCampaignStaff` matches the plan. Optional REST absolute-history tightening → P2 workstream.
|
||||
- **Miss harvest:** open issues #48/#49/#50/#54 are **archive remaps** of Pass 4's #52/#53/#54/#73 — guards already ship, but `docs/GUARDRAILS.md` still cites old numbers and claims an empty harvest queue. **Hardening + provenance repair + `Closes`** in-session. OPS2 #41 functionally done (`GUARDRAILS.md` exists) — close with the same PR.
|
||||
- **Pass 4 carry-forward:** P4-A…P4-E, P4-G, P4-H, P4-D still open in code (verified); **P4-F closed by measurement** (mobile cards no longer value-import `municipalityListUrl`); LeadershipStateDeputy twin already closed by B37 (re-confirmed).
|
||||
- **Duplication for the plan:** ~1,850 LOC outbox runtimes ×3; ~300 LOC outbox UI lifecycle ×7; OpsListLocal 686 (5 lists); wizard action-id list ×3; homeSearch runners still twins; notification names-by-id ×7; Wizard info Drawer ×3.
|
||||
- **Guard dodges measured:** sharedSheetHost substring; e2e goto settle tokens; allocator optional slug still representable; Local API shorthand `user,`; bypass header comment; safeMessages local-array form; affected-e2e `mode:none` for unmapped `src/lib/campaignOps`.
|
||||
|
||||
## Remediation deliveries (in-session)
|
||||
|
||||
| WS | Content | Status |
|
||||
| ------ | --------------------------------------------------------------------------------------------------- | ------------- |
|
||||
| P5-P0 | Logout always clears persisted outbox+mirror adapters (singleton-independent) + pins | in-session PR |
|
||||
| P5-P1a | Activity hybrid: disable offline-unsupported fields; send null on cleared relations + pins | in-session PR |
|
||||
| P5-P1b | CAS: advisory lock around assert+mutate paths (document key) + concurrent int pin | in-session PR |
|
||||
| P5-M\* | GUARDRAILS provenance → public issue #s; harden dodgeable miss guards; `Closes #48 #49 #50 #54 #41` | in-session PR |
|
||||
|
||||
## Pass 5 Decisions
|
||||
|
||||
| ID | Decision | Rationale |
|
||||
| --- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||
| D1 | B57 advisor statewide Δ is **not** a security regression — product option A | Plan locked recommendation; hero remains actor-scoped |
|
||||
| D2 | Logout wipe must open adapters even when executor/store singletons are null | Shared-device PII / queued mutations survive reload otherwise |
|
||||
| D3 | Hybrid activity edit must not offer unsavable fields; clearing a relation is an explicit null write | UI that edits what the outbox cannot persist is a silent data-loss class |
|
||||
| D4 | CAS without a lock is incomplete — lock+re-read is the minimal honest implementation | Check-then-write alone cannot characterize conflict under concurrency |
|
||||
| D5 | Remapped miss issues close via guard hardening + provenance, not new feature work | Guards already exist; archive rewrite left Issues OPEN with new numbers |
|
||||
|
||||
## Next Actions
|
||||
|
||||
- [x] Artifacts PR Ready + auto-merge
|
||||
- [ ] P5-A → P5-L as independent deliveries ([entrega-engenharia-p5.md](plans/entrega-engenharia-p5.md)); oversized → `plan-issue`
|
||||
- [ ] Continue unfinished Pass 4 workstreams where not superseded
|
||||
- [ ] Leftovers → ledger via `capture-review-debts`
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ Ledger of known engineering debt. Items large enough to be scheduled work become
|
|||
| Any campaign user can enumerate staff names/roles (`canReadCampaignUsers`) | `src/utilities/access/campaignUsers.ts` | info disclosure | low | S | P2 | open | |
|
||||
| `removeSupporterData` deletes via `overrideAccess: true` while `canDeleteSupporter` is admin-only | `src/app/(campaign)/campanha/actions/supporter.ts` | access asymmetry (intentional LGPD path) | low | S | P3 | closed 2026-07-29 (P3-D): documented in-code — the delete is the staff-driven titular-removal flow, scope already proven by `assertCanManageSupporter` on the exact row; day-to-day deletes stay admin-only | |
|
||||
| Legacy public consent flows hardcode document IDs (`consent: 2`) | `src/app/(frontend)/actions/submitWhatsapp.ts` | correctness | medium | S | P1 | closed 2026-07-25 (Pass 2 D3): resolves `Consent.key = 'whatsapp-inscricao'` fail-closed; migration `20260725_170000` tags the live doc (id 2, key vazio) com a chave | AGENTS Known Gaps #2 |
|
||||
| E2E suite thin (**17 specs / 48 cases** measured 2026-07-31, Pass 4 — grew from 15/31 at Pass 3; most campaign CRUD still int-only, so the substance holds) | `tests/e2e/` | coverage | medium | L | P2 | open | |
|
||||
| E2E suite thin (**20 specs / 61 cases** measured 2026-08-02, Pass 5 — grew from 17/48 at Pass 4; most campaign CRUD still int-only, so the substance holds) | `tests/e2e/` | coverage | medium | L | P2 | open | |
|
||||
| CI runs on GitHub Actions only (no secondary pipeline) | `.github/workflows/ci.yml` | process | low | M | P3 | open | |
|
||||
| E2E campaign journeys flake with 2 workers — **root cause narrowed 2026-07-26 (B13)**, and it is not only latency: (a) `campaignMunicipalities`/`campaign-pwa` click the leader consent checkbox before hydration attaches the handler, and (b) the municipality fixture picks names by regex, so "Conde" also matches "Condeúba". Reproduced on a clean `main` tree, so it is not a B13 regression; both specs pass in isolation | `tests/e2e/campaignMunicipalities.e2e.spec.ts`, `tests/e2e/campaign-pwa.e2e.spec.ts` | test-infra | medium (masks real failures in the delivery gate) | S | P2 | open — mitigated 2026-07-31 (Pass 4): hydration helpers adopted (`checkRadixWhenHydrated`); the `/Cairu/i` substring literals are GONE and a catalog-keyed guard bans unanchored municipality-name regexes (miss #73, PR #93); prod full suite 48/48 green three times this session. What remains is the dev-mode `campaignLeaderships` chip failure — different class, own Pass 4 row below | |
|
||||
| Two e2e tests fail **deterministically at one worker on a clean `main` tree** (measured 2026-07-27 by stashing the whole B34 delivery and re-running): `campaignNearestMunicipality` "coordinator in Salvador is sent to the zone list" cannot find the `Salvador — ZE 1` link on `?q=Salvador`, and `campaignMunicipalities` "advisor opens a demand and decides it" cannot find its demand heading. These are **not** the 2-worker flake in the row above — retrying and lowering concurrency do not help — so the gate currently ships with two red specs whose failure nobody has diagnosed. **Widened 2026-07-28 (B17), same stash-and-compare method: it is not two tests but most of `campaignMunicipalities`** — five failed at one worker on the clean tree (`:56`, `:125`, `:292`, `:394`, `:446`) against four with the delivery applied, and the failing set is not stable between runs (`page.waitForURL` timeouts, a `getByLabel('Média')` strict-mode violation matching both the popover trigger and its input, a click whose target the bottom nav intercepts). Practical consequence for the next delivery: comparing the count of red tests against a stashed tree is the only way to read this spec — naming the two tests above is no longer enough. **2026-07-28 (Pass 3): root cause measured** — unanchored municipality-name regex at `campaignMunicipalities.e2e.spec.ts:263` (**23/435 prefix collisions** in the catalog: Conde/Condeúba, Catu/Caturama, Laje ×3, Barra ×4); the `getByLabel('Média')` strict-mode violation and the hydration-race consent checkbox are unchanged; fixture drift measured — the e2e cleanup lacks E14's `engagementLevel`/`levelNote`/catalog-name reset and owns+deletes the leased `apoiador-cadastro` row. Fix scheduled as **P3-C** ([entrega-engenharia-p3.md](plans/entrega-engenharia-p3.md)) | `tests/e2e/campaignNearestMunicipality.e2e.spec.ts:156`, `tests/e2e/campaignMunicipalities.e2e.spec.ts:56,125,292,394,446` | broken test (or real regression) | high — a permanently red gate trains everyone to ignore it, which is how a real failure ships | S | **P1** | closed 2026-07-29 (P3-C): full suite **31/31 green** at 2 workers. Root causes fixed — stale sort-summary copy (`déficit da meta`→`Cobertura`), `exact` trigger name vs appended status suffix (now anchored regex), option click not selecting (role=option + `toPass` hydration-retry loop, same class as `checkRadixWhenHydrated`), stretched-overlay click needing `force`, leader login using the advisor's password (each `createCampaignUser` mints its own), and 30 s test timeout → 60 s under cold-compile load. Guards: unanchored-template-regex ban in `codebaseConventions`, global `expect` 10 s | |
|
||||
|
|
@ -52,7 +52,7 @@ Ledger of known engineering debt. Items large enough to be scheduled work become
|
|||
| `notificationEvents` re-spells names-by-id ×7 instead of the P3-E wrappers | `src/utilities/notification/notificationEvents.ts` (`:41-57`, `:143-174`, `:212-236` — `findByID` + `select:{name}`/`{name,slug}`) | duplication | low | S | P2 | open — Pass 4 | P4-C |
|
||||
| Notification write path: `markAllCampaignNotificationsRead` updates up to 200 rows with no transaction; `subscribeCampaignPush` validates with `.trim()` only and always creates (re-subscribe → unique violation → generic error); `unsubscribeCampaignPush` deletes with `overrideAccess: true` while `canDeleteOwnPushSubscriptions` already scopes the owner | `src/app/(campaign)/campanha/actions/notifications.ts:69-91,100-143,172-176` | correctness | medium — partial mark-read on mid-batch failure; hostile re-subscribe UX; bypass surface | S | P2 | open — Pass 4 | P4-D |
|
||||
| Wizard info Drawer chrome spelled ×3 (button → bottom sheet with title+description+body); skip trailing spelled ×2 (13 lines each, both `{label, href}`) | `WizardSignalTypeStep.tsx:95-112`, `WizardTrendChoiceStep.tsx:115-132`, `WizardLeadershipStep.tsx:167-179`; `WizardSignalSkipTrailing.tsx` ↔ `WizardTrendSkipTrailing.tsx` | duplication | low | S | P2 | open — Pass 4 | P4-E |
|
||||
| `MunicipalityListMobileCards` (client) value-imports `municipalityColumnLabels` from `municipalityListUrl` — a ~19 KB URL module (pulls `isMunicipalitySlug` → `municipalityCatalog`) for a string map whose type already lives in `municipalityLabels` | `src/components/campaign/municipality/MunicipalityListMobileCards.tsx:26` | boundary (B14 class) | low | S | P2 | open — Pass 4 | P4-F |
|
||||
| `MunicipalityListMobileCards` (client) value-imports `municipalityColumnLabels` from `municipalityListUrl` — a ~19 KB URL module (pulls `isMunicipalitySlug` → `municipalityCatalog`) for a string map whose type already lives in `municipalityLabels` | `src/components/campaign/municipality/MunicipalityListMobileCards.tsx:26` | boundary (B14 class) | low | S | P2 | closed 2026-08-02 (Pass 5 verify): only server `MunicipalityList.tsx` imports `municipalityColumnLabels`; mobile cards no longer value-import `municipalityListUrl` | P4-F |
|
||||
| `HomeSearchProvider` wraps the whole chrome incl. `actions` + `summarySlot` non-consumers, and the provider value changes on every keystroke | `src/components/campaign/dashboard/CampaignHomeStaffChrome.tsx:41-56`, `useHomeSearchQuery.ts:63-74` | state placement | low — actions/summary re-render per keypress | S | P2 | open — Pass 4 | P4-G |
|
||||
| Unconditional `aria-live="polite"` per chip cell (~50 always-registered regions on lideranças); the overlay family already lazy-mounts its region from first open | `src/components/campaign/shared/RelationChipCell.tsx:821-823` vs `CampaignCellEditOverlay.tsx:114-120` | a11y scale | low | S | P2 | open — Pass 4 | P4-G |
|
||||
| Bypass ratchet dodge: one "bypass" comment in the first 40 lines documents **every** `overrideAccess: true` in the file — `notification/*` has 20, `campaignWebAuthnCeremony` 4, zero per-call justifications | `codebaseConventions.unit.spec.ts:541-623`; `src/utilities/notification/*`; `src/utilities/webauthn/campaignWebAuthnCeremony.ts` | guard dodge | medium — the P3-E "comment justifying" intent is satisfied in letter, not spirit | M | P2 | open — Pass 4 | P4-H |
|
||||
|
|
@ -86,6 +86,20 @@ Ledger of known engineering debt. Items large enough to be scheduled work become
|
|||
| ---------- | ---------------- | ----- |
|
||||
| (none yet) | | |
|
||||
|
||||
| Logout wipe for campaignOps outboxes/mirror is gated on in-memory singletons — after cold reload IndexedDB (`teqo-ops-*`) + mirror OPFS/IDB survive `clearCampaignOpsStorage` | `clearCampaignOpsStorage.ts`; `ops*Outbox.ts` `clear*ForLogout`; `opsMirrorClient.clearOpsMirrorPersistenceForLogout` | privacy / shared-device | high — next actor can hydrate prior queue/mirror | M | P0 | open — Pass 5 (remediation in-session) | P5-P0 |
|
||||
| Activity hybrid edit renders tasks/demands and omits cleared `responsible`/`leadership` (null never sent); outbox payload is a fork of the server FormData contract | `ActivityForm.tsx` hybrid submit (~599-616); message admits tasks need connection but fields stay editable | correctness | high — silent data loss on edit | M | P1 | open — Pass 5 (remediation in-session) | P5-P1a |
|
||||
| `assertCampaignDocCas` is check-then-write without document lock — concurrent writers both pass CAS (0 concurrent pins) | `assertCampaignDocCas.ts`; ≥4 call sites without advisory lock around assert+mutate | correctness (OH13 CAS) | high under concurrent/offline conflict | M | P1 | open — Pass 5 (remediation in-session) | P5-P1b |
|
||||
| Push dispatch `queueMicrotask` inside domain transaction — sender re-reads outside txn; can fire for rolled-back rows or miss uncommitted ones | `createCampaignNotification.ts:20-40`; `sendCampaignPush.ts:39-66`; hooks in Supporter/Activity/MunicipalityUpdate | correctness | medium — unreliable push; unhandled rejection | M | P1 | open — Pass 5 | P5-E |
|
||||
| Three offline outbox runtimes re-spell init/collapse/conflict/clear (~1 854 LOC) | `opsMunicipalityOutbox.ts` 711, `opsDomainOutbox.ts` 652, `opsEstimateOutbox.ts` 208 | duplication | medium — logout/CAS bugs copy three times | L | P2 | open — Pass 5 | P5-A |
|
||||
| Outbox UI lifecycle (pending/conflict toasts) copied ×7 (~300 LOC) | PledgeEstimateForm, DeclareVotesForm, MunicipalityListAdvisorsControl, DemandWorkflowCard, LeadershipListSupportStatusControl, LeadershipInternalForm, ActivityForm | duplication | low | M | P2 | open — Pass 5 | P5-B |
|
||||
| `OpsListLocal` hosts 5 degraded lists in one 686-line module | `OpsListLocal.tsx` | bloater | low | M | P2 | open — Pass 5 | P5-C |
|
||||
| Ops snapshot decode is cast-only (`parseOpsSnapshot` 0 prod callers); mirror validates 3 shallow facts; schema version any number accepted | `opsContract.ts`; `opsMirrorClient.ts:234-245`; `opsMirrorPersistence.ts` | type honesty / offline trust | medium — corrupt persistence can bootstrap bad state | M | P2 | open — Pass 5 | P5-D |
|
||||
| `src/lib` imports React/Lucide in 9 modules (~739 lines / 23 kB) — pure-layer violation | `campaignHomeActions.ts`, long-press/coarse-pointer hooks, quick-action icon metadata | layer boundary | low | M | P2 | open — Pass 5 | P5-I |
|
||||
| Wizard action-id list duplicated ×3; href builders 5–6 positional params with 7 `undefined` placeholders (Pass 4 trigger fired) | `activityQuickActions` / `campaignQuickActionDemands` / `campaignQuickActionLeadership`; `campaignActionRoutes.ts` | duplication / API shape | low | S | P2 | open — Pass 5 | P5-H |
|
||||
| Affected-e2e returns `mode: none` for unmapped `src/lib` — 53/72 delta lib files including all `campaignOps` | `scripts/lib/test-affected-core.mjs`; `e2e-affected.mjs` | CI blind spot | medium — offline/lib regressions skip Playwright | S | P2 | open — Pass 5 | P5-L |
|
||||
| B57 snapshot collection `read: isCampaignStaff` exposes absolute statewide history via `/api/*` (UI only shows Δ; product option A intentional for Δ) | `CampaignVoteSummarySnapshot.ts:25-29`; plan `delta-7-dias-estimativa-inicio.md` option A | privacy tightening | low — absolute REST beyond UI Δ | S | P2 | open — Pass 5 (optional lockdown) | P5-K |
|
||||
| `sharedSheetHost` / e2e navigation / allocator / Local API / bypass ratchet guards remain dodgeable (substring/token/header); GUARDRAILS.md still cites archive issue numbers | `sharedSheetHostConventions`, `e2eNavigationConventions`, `testMunicipalityAllocatorConventions`, `localApiOverrideAccessConventions`, `codebaseConventions`; `docs/GUARDRAILS.md` | guard dodge + provenance | medium | M | P2 | open — Pass 5 (hardening in-session for miss closes) | P5-J / P5-M |
|
||||
|
||||
## Adopted Conventions
|
||||
|
||||
- **Zero lint warnings.** `pnpm lint` runs with `--max-warnings=0`; deliberate placeholders use a `_` prefix (`argsIgnorePattern`).
|
||||
|
|
|
|||
|
|
@ -4,15 +4,15 @@
|
|||
|
||||
Three layers, all local-database-only (see `local-database` skill; tests refuse any database not ending in `_test`):
|
||||
|
||||
- **Unit** (`tests/unit/**/*.unit.spec.ts`, 117 specs as of 2026-07-31, Pass 4 — +6 convention guards land with the Pass 4 remediation PRs): pure logic; runs with a deliberately invalid `DATABASE_URL` so nothing can touch a database.
|
||||
- **Integration** (`tests/int/**/*.int.spec.ts`, 71 specs): real Payload + Postgres (`teqo_test`); campaign fixtures allocate seeded municipalities via a Postgres sequence so parallel spec files never share one, and purge residue on claim. Since the miss #73 guardrail (Pass 4), specs that mutate municipalities must use the allocator (no pinned slugs) — enforced by `testMunicipalityAllocatorConventions`. Shared consent rows with stable keys are leased (`tests/helpers/testDatabaseLease.ts`), never owned.
|
||||
- **E2E** (`tests/e2e`, Playwright, 17 specs / 48 cases): smoke-level; most campaign behavior is pinned at the int layer.
|
||||
- **Unit** (`tests/unit/**/*.unit.spec.ts`, **173 specs** as of 2026-08-02, Pass 5 — grew with offline/hybrid + convention guards): pure logic; runs with a deliberately invalid `DATABASE_URL` so nothing can touch a database.
|
||||
- **Integration** (`tests/int/**/*.int.spec.ts`, **78 specs**): real Payload + Postgres (`teqo_test`); campaign fixtures allocate seeded municipalities via a Postgres sequence so parallel spec files never share one, and purge residue on claim. Since the miss #73→#54 guardrail (Pass 4, provenance repaired Pass 5), specs that mutate municipalities must use the allocator (no pinned slugs) — enforced by `testMunicipalityAllocatorConventions`. Shared consent rows with stable keys are leased (`tests/helpers/testDatabaseLease.ts`), never owned.
|
||||
- **E2E** (`tests/e2e`, Playwright, **20 specs / 61 cases** as of 2026-08-02, Pass 5 — was 17/48 at Pass 4): smoke-level; most campaign behavior is pinned at the int layer. Offline/hybrid write coverage is still thin (estimate path only — ledger P5-TEST-6 / plan P5-A).
|
||||
|
||||
CI (`.github/workflows/ci-pr.yml`) runs parallel jobs — lint (zero warnings), format, typecheck, knip, cycles, unit/int (**affected by the PR diff**: `vitest --changed` against the PR base via `scripts/test-affected.mjs`, full-suite fallback on high-risk paths), e2e (manifest path→spec via `scripts/e2e-affected.mjs` + `scripts/lib/e2e-affected-manifest.mjs`, blocking; production build + `list`/`github` reporters in CI) and build — against a Postgres 17 service with **`db:seed:minimal`**. Push to `main` (`ci.yml`) always runs the full net including e2e.
|
||||
|
||||
**Local e2e before push (same blast radius as PR CI):** `pnpm test:e2e:affected` — runs `e2e-affected.mjs` against `origin/stage`, migrates/seeds, then `pnpm test:e2e` with the selected specs (or the full suite on high-risk diffs). Forward extra Playwright args after `--` for a narrowed repro. Opt into production mode (after fixing the known municipalities-list prod client bug) with `E2E_PROD=1 pnpm test:e2e:affected`.
|
||||
|
||||
**Navigation discipline in e2e (miss #54, 2026-07-30):** `page.goto` is for cold loads and URL contracts (deep links, redirects, legacy params); when the scenario is _continuity inside the authenticated shell_ — especially after a heavy list route — navigate in-shell instead (sidebar links, buttons, form submits), the way the user does. Never fire two `page.goto` back-to-back with nothing settling the first navigation (an `await expect(...)`, `waitForURL`, or interaction): the second aborts the first's in-flight RSC fetch (`net::ERR_ABORTED`, measured in `campaignSavedFilters`). The `e2eNavigationConventions` unit guard fails the build on unsettled goto pairs. Two sibling rules of the same family: wait for **interactive state** before clicking dynamic controls — `toBeVisible` proves SSR paint, not hydration (pre-hydration clicks no-op silently; `checkRadixWhenHydrated` is the precedent, P3-C class) — and gate WebAuthn ceremonies on `expectCampaignBiometricsReady` before the island's one-shot probe runs (miss #53). **Dev-mode caveat:** `campaignLeaderships`' chip-cell spec currently fails deterministically under `pnpm dev` (suggestion/commit step; prod build green — run it with `E2E_PROD=1` locally; ledgered in TECH-DEBT).
|
||||
**Navigation discipline in e2e (miss #50, was archive #54, 2026-07-30):** `page.goto` is for cold loads and URL contracts (deep links, redirects, legacy params); when the scenario is _continuity inside the authenticated shell_ — especially after a heavy list route — navigate in-shell instead (sidebar links, buttons, form submits), the way the user does. Never fire two `page.goto` back-to-back with nothing settling the first navigation (an `await expect(...)`, `waitForURL`, or interaction): the second aborts the first's in-flight RSC fetch (`net::ERR_ABORTED`, measured in `campaignSavedFilters`). The `e2eNavigationConventions` unit guard fails the build on unsettled goto pairs. Two sibling rules of the same family: wait for **interactive state** before clicking dynamic controls — `toBeVisible` proves SSR paint, not hydration (pre-hydration clicks no-op silently; `checkRadixWhenHydrated` is the precedent, P3-C class) — and gate WebAuthn ceremonies on `expectCampaignBiometricsReady` before the island's one-shot probe runs (miss #49, was archive #53). **Dev-mode caveat:** `campaignLeaderships`' chip-cell spec currently fails deterministically under `pnpm dev` (suggestion/commit step; prod build green — run it with `E2E_PROD=1` locally; ledgered in TECH-DEBT).
|
||||
|
||||
## Minimal test database (`pnpm db:seed:minimal`)
|
||||
|
||||
|
|
|
|||
152
docs/plans/entrega-engenharia-p5.md
Normal file
152
docs/plans/entrega-engenharia-p5.md
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
# Pass 5 — Auditoria de engenharia (offline/hybrid) + remediação P0/P1 + provenance das misses
|
||||
|
||||
## Contexto e manchetes
|
||||
|
||||
- **Executado em 2026-08-02, modo autônomo (Cursor Cloud)** da skill `engineering-audit`: precheck solitário verde (pool **desligado**), varredura completa com âncora de delta no Pass 4 (2026-07-31), remediações P0/P1 e fechamento das misses remapeadas na mesma sessão, cada um em PR próprio com gate completo. PR dos artefatos = Ready + auto-merge.
|
||||
- **Âncora de delta:** Pass 4. Em ~2 dias o paradigma tocou **573 arquivos / 442 commits** — OH11–OH14 (mirror + outbox + CAS + OfflineBoundary), CL9 (lista unificada sempre ligada), quick actions, B57 snapshots, 89 módulos novos em `src/`.
|
||||
- **Baseline verde:** `tsc` 0, `lint` 0 warnings, `knip` 0 findings (ruído `payload.config.ts`, ledger P3), madge 0 ciclos (**858 arquivos**, +84). Unit **173 / 1 383**; e2e **20 specs / 61 cases**.
|
||||
- **Manchetes (todas medidas):**
|
||||
- **1 P0:** wipe de logout de outbox/mirror depende de singletons em memória — após reload frio a persistência sobrevive.
|
||||
- **2 P1s remediados:** activity hybrid perde campos / não limpa relações; CAS check-then-write sem lock.
|
||||
- **1 P1 ledgerado (workstream):** push `queueMicrotask` antes do commit da transação.
|
||||
- **B57 “advisor vê Δ statewide” rejeitado como P0** — opção A do plano (`delta-7-dias-estimativa-inicio.md`).
|
||||
- **4 misses remapeadas** (#48←#52, #49←#53, #50←#54, #54←#73) + OPS2 #41: guards já vivos; provenance + endurecimento + `Closes`.
|
||||
- **Pass 4 carry-forward verificado:** A–E, G, H, D abertos; **F fechado** (boundary); twin LeadershipStateDeputy já B37.
|
||||
|
||||
## Protocolo de delta de comportamento
|
||||
|
||||
Consolidação pode mudar saídas pequenas desde que **cada delta seja listado**; pins atualizados deliberadamente; URL B18 / schema / Consent fora de alcance sem item nomeado.
|
||||
|
||||
## Ondas já executadas na sessão (P0/P1 + misses)
|
||||
|
||||
| Entrega | Conteúdo | Guarda (classe) |
|
||||
| ------- | ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
|
||||
| P5-P0 | Logout sempre abre adapters e limpa IDB/OPFS mesmo com singleton null | pin unit: cold-reload wipe; logout segue em `finally`/allSettled (5) |
|
||||
| P5-P1a | Activity hybrid: campos offline-unsupported desabilitados; null em clear | pin unit/int do payload híbrido (1 + 5) |
|
||||
| P5-P1b | CAS sob `pg_advisory_xact_lock` do doc + re-read | pin int concorrente 2 writers (5) |
|
||||
| P5-M\* | GUARDRAILS.md números públicos; endurecer dodges; fechar misses + OPS2 | guards existentes endurecidos (3); `Closes #48, closes #49, closes #50, closes #54, closes #41` |
|
||||
|
||||
## Ondas do plano (P2, ordenadas por risco × churn)
|
||||
|
||||
### Onda 1 — Superfície offline (delta dominante)
|
||||
|
||||
#### P5-A Runtime único de outbox
|
||||
|
||||
- **Meta:** núcleo tipado (init / collapse / replay / conflict / clear) + 3 wrappers de domínio.
|
||||
- **Evidência:** `opsMunicipalityOutbox.ts` 711 + `opsDomainOutbox.ts` 652 + `opsEstimateOutbox.ts` 208 ≈ **1 854 LOC**; `outboxMutationRow` ×3; clear logout ×3.
|
||||
- **Conhecimento duplicado:** “persistir, colapsar, reenviar, marcar conflito e limpar mutação offline”.
|
||||
- **Guarda:** pin por descriptor de mutação + clear logout cold (5); convenção banindo terceiro executor copy-paste (3).
|
||||
- **Effort:** L.
|
||||
|
||||
#### P5-B Hook `useOpsOutboxConflict`
|
||||
|
||||
- **Meta:** pending → refresh → toast “Manter o meu” / “Usar o novo” numa máquina.
|
||||
- **Evidência:** ~300 linhas ×7 (`PledgeEstimateForm`, `DeclareVotesForm`, `MunicipalityListAdvisorsControl`, `DemandWorkflowCard`, `LeadershipListSupportStatusControl`, `LeadershipInternalForm`, `ActivityForm`).
|
||||
- **Conhecimento:** “traduzir lifecycle de uma row do outbox em UI de conflito”.
|
||||
- **Guarda:** pin pending→synced / retry / discard (5).
|
||||
- **Effort:** M.
|
||||
|
||||
#### P5-C `OpsListLocal` → shell tipado + variante município
|
||||
|
||||
- **Evidência:** 686 linhas; 5 tabelas; 4 entidades repetem mirror→parse→filter→footer.
|
||||
- **Conhecimento:** “lista degradada read-only a partir do mirror com URL canônica”.
|
||||
- **Guarda:** judgment-only no split (6) + pins de URL/empty (5).
|
||||
- **Effort:** M.
|
||||
|
||||
#### P5-D Snapshot ops: parser runtime + budget
|
||||
|
||||
- **Evidência:** `parseOpsSnapshot` é cast (0 callers prod); mirror client valida 3 facts rasos; snapshot ~4 MiB JSON / ~2 MiB gzip (âncora, não teto); poll 3 min; `buildOpsSnapshot` 547 linhas com `municipalityUpdate` unbounded then truncate.
|
||||
- **Guarda:** pin corrupt/version mismatch (5); CI budget (4).
|
||||
- **Effort:** M.
|
||||
|
||||
#### P5-E Push transacional (P1 remanescente)
|
||||
|
||||
- **Meta:** outbox/job disparado **após** commit; nunca `queueMicrotask` dentro da transação do domínio.
|
||||
- **Evidência:** `createCampaignNotification.ts:20-40` + `sendCampaignPush.ts:39-66`; 3 hooks (supporter/activity/municipalityUpdate).
|
||||
- **Guarda:** int commit/rollback com Web Push mockado (5).
|
||||
- **Effort:** M.
|
||||
|
||||
### Onda 2 — Carry-forward Pass 4 (ainda aberto) + lib do delta
|
||||
|
||||
#### P5-F (=P4-A/B/C/D) homeSearch runner + grupos + notification names/writes
|
||||
|
||||
- Status verificado 2026-08-02: twins 88/100 linhas; 6 grupos; 7 `findByID`; mark-all sem transação / subscribe sem zod / unsubscribe com bypass. Executar o plano P4 original; não reescrever.
|
||||
- **Guarda:** as do P4.
|
||||
|
||||
#### P5-G (=P4-E/G) WizardInfoDrawer + HomeSearchProvider estreito + aria-live lazy
|
||||
|
||||
- Drawer ×3 e skip-trailing ×2 ainda no código; provider ainda envolve actions/summary; `RelationChipCell` ~50 regiões polite.
|
||||
- **Guarda:** as do P4.
|
||||
|
||||
#### P5-H Wizard action IDs single-source + href options object
|
||||
|
||||
- **Evidência:** lista de 5 IDs ×3 módulos; `wizardSignalHref`/`wizardTrendHref` com 5–6 posicionais e **7** calls com `undefined` (gatilho Pass 4 **disparou**).
|
||||
- **Guarda:** tipo (1) + snapshot de href (5).
|
||||
- **Effort:** S/M.
|
||||
|
||||
#### P5-I `src/lib` sem React/Lucide
|
||||
|
||||
- **Evidência:** 9 módulos lib importam `react` ou `lucide-react` (~739 linhas / 23 kB).
|
||||
- **Guarda:** ESLint ban na zona `src/lib` (2).
|
||||
- **Effort:** M.
|
||||
|
||||
### Onda 3 — Endurecimento de guardas + REST B57
|
||||
|
||||
#### P5-J Ratchet de bypass (P4-H) + Local API AST + safeMessages forms
|
||||
|
||||
- Header-comment dodge ainda vivo; shorthand `user,` invisível; `const safeMessages =` foge da guarda.
|
||||
- **Guarda:** endurecer specs (3).
|
||||
- **Effort:** M.
|
||||
|
||||
#### P5-K Snapshot vote-summary REST → unrestricted (+ keep Δ via loader bypass)
|
||||
|
||||
- **Não é P0** (B57 opção A). Opcional: collection `read` só unrestricted/admin; advisor continua a receber Δ via utility com `overrideAccess` justificado — sem enumerar absolutos em `/api/*`.
|
||||
- **Guarda:** int role matrix (5).
|
||||
- **Effort:** S.
|
||||
|
||||
#### P5-L Affected-E2E fail-closed para `src/lib/campaignOps`
|
||||
|
||||
- **Evidência:** 53/72 `src/lib` do delta sem match no manifesto → `mode: none`.
|
||||
- **Guarda:** convenção + manifesto (3).
|
||||
- **Effort:** S.
|
||||
|
||||
## Mapa de guardas
|
||||
|
||||
### Novas / endurecidas nesta sessão
|
||||
|
||||
| Guarda | Classe | Origem |
|
||||
| ------------------------------------------- | ------ | ---------------------- |
|
||||
| Logout wipe persistence-independent | 5 | P0 |
|
||||
| Hybrid activity payload contract | 1 + 5 | P1a |
|
||||
| CAS sob advisory lock + pin concorrente | 5 | P1b |
|
||||
| Provenance GUARDRAILS → issues públicos | 6→3 | harvest remap |
|
||||
| sharedSheetHost / e2eNav / allocator harden | 3 | misses #48/#49/#50/#54 |
|
||||
|
||||
### Resíduo judgment-only
|
||||
|
||||
- Split de `OpsListLocal` / `WizardLeadershipStep` / `RelationChipCell` — gatilho de produto.
|
||||
- B57 opção A (Δ statewide p/ assessor) — decisão de produto travada; não relitigar sem evidência nova.
|
||||
- AdvisorsTable edit mode — ledger pré-Pass 4, edit-in-place.
|
||||
|
||||
### Defer + gatilho (Pass 5)
|
||||
|
||||
| Par | Medida | Gatilho |
|
||||
| --------------------------------- | ----------------------------- | --------------------------------- |
|
||||
| Outbox runtime ×3 | 1 854 LOC | 4ª família de mutação offline |
|
||||
| `buildOpsSnapshot` pure mappers | ~206 LOC pure in utilities | mudança de schema do snapshot |
|
||||
| `vercel-production-alias.mjs` 740 | 10 fetch adapters | 2º consumidor do protocolo Vercel |
|
||||
| Online/offline list policy twins | demand filter/sort duplicated | 3º domínio com lista local |
|
||||
|
||||
## Look-alikes rejeitados
|
||||
|
||||
- Ops snapshot mappers × page view models — contratos de redação diferentes.
|
||||
- Leader-safe pledge view × staff estimate DTO — assimetria de segurança.
|
||||
- Strict server FormData × optimistic client parsers — trust boundary distinta (nomear política, não unificar às cegas).
|
||||
- B57 statewide Δ × “advisor vê só carteira” — produto escolheu A.
|
||||
|
||||
## Regras de execução
|
||||
|
||||
- Uma consolidação por entrega; gate bare completo + Aikido quando disponível.
|
||||
- Estrutura ≠ comportamento no mesmo commit; vermelho no meio = revert.
|
||||
- Frozen: URL B18, schema, Consent fail-closed.
|
||||
- Guarda na mesma entrega do fix; misses fecham com `Closes #N` (keyword por número).
|
||||
Loading…
Reference in a new issue