Bring B15/B16-style URL sort/filter to /campanha/liderancas on the B33 mold, with shared CampaignTableHead filter slot and B18 exhaustive enum canonicalize from /simplify.
The Drawer half of MunicipalityPortfolioCell now goes through
CampaignCellEditOverlay: the container switches on a `variant` prop, not on
viewport, so the pointer policy stays in CSS while the cell inherits
`initialFocus` (the hand-rolled sheet focused the first chip, a link out of the
row being edited) and the ARIA trigger attributes every other cell has.
The optimistic baseline bug was back in a shape that reads as correct. Applying
the delta functionally is not enough when the fallback is not: `current ??
municipalityIds` still read the render that created the closure, which is the
branch an undo always takes, since the server reconcile clears the optimistic
value first. Undo after a later add rebuilt the row from a set that predated it,
permanently. The baseline is a ref now, advanced synchronously in the draft
branch, and pinned by a spec verified red against the old code.
Also: revert the Drawer body gate (its saving measured as zero, and it animated
an empty box out of view), collapse the word-start matcher to two string tests
now that both sides are normalized, copy the memoized território ids before
handing them to a caller, and revalidate every changed município of an advisor
batch instead of only the last.
The rebase on main brought B33+ into view: it registers the same static Bahia
catalog reaching /campanha/municipios' client bundle. Same class, opposite
cause — there a predicate drags the module in by accident, here the cell needs
the data — so the fixes differ, but the First Load JS bench is shared.
The "Municípios" column was dead text; it is now chips that navigate to the
município, with a territory chip when a leadership covers a whole TI, and it is
editable in place. What picks inline vs. Drawer is the `pointer:` media query,
not viewport width: on a fine pointer the editor is always mounted (the "×" sits
at the chip's corner, revealed on hover/focus) and on a coarse pointer a tap
anywhere in the cell opens a Drawer with 44 px targets.
`AdvisorMunicipalityCell` is promoted to `shared/MunicipalityPortfolioCell` and
/campanha/assessores migrates onto it in the same change, so the second call site
is born with the first. One batch action only; the single-id advisor twin is
deleted with its int tests migrated. The anti-goal on always-mounted list inputs
is amended for chip-based relations on fine pointers, not reopened.
Also fixes a latent bug: `CampaignTableHead`'s `description` seam broke any RSC
caller, because its two helpers lived in a 'use client' module.
Three debts, no new ID. The fifth JSON control and route arrived without
touching F1 — the level movement is an explicit submit, not a debounce — which
is exactly the escape clause F2/F3 were parked behind, so they stop being
conditional. F2 also changes character: the same-origin check that
`isSameOriginRequest` documents itself as owning is copied into five routes, so
the one that forgets the line fails open. That is not boilerplate and is not
cuttable by appetite.
F5 is B42's own deferred trigger firing: it parked the footer slot on "a second
control needing explicit submit in a Drawer", and this is that control. What the
deferral could not know is that the shell pins "Fechar" while "Registrar
movimento" sits below the fold, so the action that discards a typed rationale is
the reachable one.
Discarded with reasons in the triage: `new Date()` during render (the server
re-runs the rules and a 409 is a designed state), and `levelNote` in the 435-row
select, already written down in E14's own plan next to `politicalTrend.note`,
which has the same shape and must be fixed with it.
B42 landed on main during this session and extracted `CampaignCellEditOverlay`
— Popover on `md+`, Drawer below it, where a popover fights the virtual
keyboard. The rebase auto-merged E14's "Nível" block into what had become the
Drawer, which compiles and would have opened a popover inside a sheet, so the
control now takes `variant` like its three siblings. The container's Popover
branch is point for point what E14 had hand-written, so the desktop is
unchanged; on touch, where there is no hover to carry it, the trigger now
spells the level out instead of showing the bare numeral.
`municipality.engagementLevel` (staff-only, no default) records what the
campaign decided to invest in a município, next to the E8/E10 metrics that
describe what it knows. Moving it is a reallocation decision, so only
unrestricted staff may, every move carries a rationale plus the signals that
would reverse it, and the write files an `allocationDecision` in the same
transaction under an advisory lock taken before the current level is read —
otherwise the snapshot's `from` is a guess. The enum gains `movimento`: a level
move is neither `aceita` nor `descarta`.
No backfill. Null is "Sem nível", and filtering by it is the triage queue.
That is also why the list sorts `nivel` in memory rather than in the query:
Postgres puts NULLs first on DESC, so a native sort would open "N4 primeiro"
on a page of municípios nobody has decided about yet. The filter stays native.
The hysteresis rules from research §6.8 are pure and client-safe, so the
Popover explains a block before submitting and the server re-runs them anyway;
a blocked move answers 409 with typed violations and the override is recorded
with exactly the rules it contradicted.
The one finding the /simplify skipped for the wrong reason becomes a fill-in:
the tour composer signals a território change only on the control, and the
pending pieces it dismissed as list-coupled are a Provider, a div and a hook
with a local fallback. The batched goal-account loader stays a trigger on the
E13 plan — the planner and the list diverge on missing data on purpose.
Five conditions per município (volume, headroom, rede, janela, encaixe) with
their reason always visible, plus a staff-only composer at
/campanha/atividades/giros that turns an âncora + satélites + semente into draft
activities in one transaction. No `visita` kind and no `tour` entity:
`deputyPresent` already marks the candidate's own agenda.
The aria-live region that unmounts with the overlay becomes B32+ F4, and the
catalog bundle debt in B33+ stops being conditional now that B41 and B42 both
shipped on that route without paying it.
Tendência, Assessores and Votos estimados now share one container
(CampaignCellEditOverlay: Popover on md+, bottom Drawer below), the card drops
to the table's density, and the whole card navigates through a stretched link
instead of a second "Abrir município" button.
capture-review-debts do fechamento do B32: MunicipalityListExpectedVotesControl
(B27), MunicipalityListTrendControl (B24) e LeadershipListSupportStatusControl
(B32) são o 3º call site do mesmo scaffold de auto-save por debounce, gatilho
já registrado nos três planos. Fill-in de engenharia com auditoria antes de
extrair (precedente B33+): docs/plans/escala-dry-pos-b32.md.
Outros achados do /simplify (flush-on-close, comentário/summary morto em
SupportStatusBadge) já foram corrigidos no commit do B32; null→a_abordar e o
findByID extra em updateLeadershipInternal são decisões já documentadas,
descartadas desta triage.
- Popover + NativeSelect sempre montado na coluna Status de
/campanha/liderancas, sem toggle de modo de edição
- Auto-save (~150ms) via POST /campanha/liderancas/support-status,
reusando isSameOriginRequest/campaignJsonMutationRoute (B24/B27),
sem revalidatePath
- Extrai leadershipStaffEditSafeMessages (adotado também em
liderancas/formActions.ts e nova/formActions.ts) e
utilities/leadershipLabels.ts (3º call site de supportStatusLabels,
agora fonte única também para SupportStatusBadge)
- Novo e2e tests/e2e/campaignLeaderships.e2e.spec.ts; setup.e2e.spec.ts
prewarma as rotas novas
- Fecha o Adiado com gatilho do B29; docs/plans, notebook e roadmap
atualizados
Gate: tsc/lint/format/knip(P3 pré-existente)/check:cycles/unit+int/e2e
verdes; two /simplify passes (labels/estado duplicado/isSupportStatus;
flush-on-close ao fechar o popover, comentário órfão de summary/
campos summary mortos removidos de SupportStatusBadge).
Follows the URL when the committed query changes with no debounce pending, so
Back/Forward and the empty state's clear anchor update the search box without
overwriting text the user is still typing. That removed the last reason for
/campanha/municipios to remount its filters, so the key= (and its now orphaned
buildMunicipalityFiltersKey) is gone and the three lists share one mounting
policy — the dedup guard was dead code on municípios while it remounted.
Reuse: setSearch + scheduleSearch were always called as a pair, so they collapse
into onSearchChange (hook surface 8 -> 6 names); MunicipalityFilters reuses the
buildMunicipalityFilterHref it was reimplementing inline; dobradinhas gains the
sibling buildStateDeputyFilterHref for the four sites pinning page 1 by hand;
municípios gains the active-filter summary its mobile block was missing.
Also drops an export with no consumer that was failing knip in CI (seo.ts).
Extract the debounce/dedup/transition scaffold that StateDeputyFilters,
TerritoryFilters and MunicipalityFilters each reimplemented into
useCampaignListFilterNavigation, and unify the two behaviors that had
silently diverged: touching a filter mid-typing used to discard the
pending search on dobradinhas and territorios, and the debounce timer
captured a stale state, so a sort clicked within its window was reverted
a second later. Also folds the six copies of the pending-transition
fallback into useCampaignListTransition and drops a redundant aria-live
that made the municipality summary the third live region on its page.
Dos 20 achados do /simplify, 12 entraram na entrega e 3 ja estavam
cobertos (o modo `territory` pertence ao E12 por rabbit hole do plano, a
shoelace duplicada e descarte declarado, e o B5 F2 ja contava os 5 call
sites dos helpers de CLI). Sobraram dois fatos sem registro.
O revisor de perf mediu que `quantize` aplica um unico numero de digitos
aos dois eixos: a grade de ~103 m e exata em longitude e a latitude segue
o aspect ratio do bbox (102,8x109,2 m no estado, 102,9x80,1 m em
Salvador). Corrigir exige `{scale, translate}` explicito e reescrever os
tres artefatos, perdendo a prova de byte-identidade da malha estadual por
um erro de ~9% num eixo num mapa que para em maxZoom 10 — entao vira
gatilho no plano-pai, nao item de roadmap.
E o B8+ respondeu por precedente uma pergunta em aberto do B5 F2: com
`scripts/lib/topology.mjs`, o helper de cache da F2 pousa em
`scripts/lib/` em vez de abrir um segundo endereco. A recomendacao antiga
(`src/lib/cliCachedDownload.ts`) fica rejeitada: `src/lib/` e client-safe
por contrato e nao e lugar de codigo que faz mkdir/fetch/writeFile.
Sem novos IDs de roadmap.
F1 — a tolerancia de simplificacao e os digitos de quantizacao viraram
politica em unidades de solo em scripts/lib/topology.mjs, consumida pelos
dois scripts de geometria. Os quantis 0.35 copiados cortavam as 19 ZE de
Salvador a ~0.6 m2 e os 417 municipios a ~1.78 km2; com tolerancia
absoluta e a grade de ~103 m do estado, a malha das zonas caiu de 480 para
30.2 pontos/feature. bahia-municipalities segue byte-identico e o tripwire
de bytes deu lugar a pontos/feature.
F2 — featureMapKey passou a ser asserido sobre features reais das tres
malhas comprometidas (417 codarea, 27 code, 19 slug), e o comentario de
MAP_KEY_PROPERTIES agora diz o que o codigo faz: as propriedades sao
mutuamente exclusivas, nao ordenadas por especificidade.
F3 — a malha das zonas e um detalhe sobre o mapa, nao o mapa: se o chunk
falha, Salvador cai no poligono municipal que ja esta desenhado embaixo e
o resto da Bahia continua funcionando, com o motivo logado. A ressalva de
aproximacao saiu do gate de comparacao e passou a depender de
bundle.hasZoneMunicipalities, derivado no servidor de municipality.kind.
F4 — orfaos deletados: os dois acessores sem chamador, isZoneMapKey (o
servidor ja sabe a regra), o wrapper simplifyTopology e o helper
polygonCount com um branch inalcancavel. MunicipalityMapNavigation
colapsou em string | undefined e MunicipalitiesByMapKey em
Record<string, string>.
After B8 F2 polygons, the textual zone breakdown under the dashboard map is redundant; register the removal in the roadmap and align B8+/B8 plan notes.
The three /simplify reviewers reported after the merge, so their findings
became a fill-in instead of a fix. The lot is anchored on a measurement that
contradicts "small mesh, small artifact": the 19 Salvador zones carry 9,120 arc
points against 9,139 for ALL 417 Bahia municipalities, because both simplify
constants are relative to the file's own bbox and were copied verbatim from the
sibling script -- the same "1e4 grid" is ~103 m statewide and ~3.9 m in a city
26x narrower, on a map that stops at maxZoom 10.
That measurement inverts one reviewer's recommendation, which is why it is
written down rather than left to be re-derived: extracting the shared constants
as they stand would cement the defect and give it the authority of a policy, so
what gets shared between the two build scripts is the ground scale.
The other three: nothing runs featureMapKey over a real feature outside the
e2e, so the three spellings of the map key can drift and paint grey with no
error anywhere; Promise.all over both meshes plus the memoized rejection turned
a 19-polygon chunk into a single point of failure for the whole map, where the
municipal mesh alone used to suffice; and the "approximate, not the official TSE
boundary" caveat hangs off the zone LIST's render condition, so it vanishes in
comparison mode while the approximate mesh is still painted.
Also records what this delivery orphaned (getTerritoryFeature lost its last
production caller when fitMapToHighlights stopped consulting geometry modules,
and knip cannot see it because specs are entry points), and bumps B5 F2's
call-site counter to five.
Records the Salvador zone delivery where the next agent will look for it —
roadmap, plan as-built, notebook and the geometry/map sections of AGENTS.md —
including the two measurements that are easy to re-derive wrongly (the bay
water in Salvador's municipal polygon, and ZE 16 wrapping ZE 14, which is why
neither an area ratio nor a centroid check is a valid overlap test).
Simplify fixes: the build script re-indexes simplified geometries by a unique
id instead of neighbourhood name, so a repeated name in a future mesh cannot
silently collapse two polygons inside a committed artifact; a stale comment
claiming zone polygons do not exist; and two int assertions that the Fase 0
catalog hydration turned tautological.
Ledgers the Aikido outage: the scanner returns Opengrep exit 2 for any input,
so the mandatory per-change scan was skipped, not passed.
Espelha a aresta leadership.stateDeputies do B31 do lado do deputado, com célula compartilhada bidirecional, loadLeadershipOptions e casca própria de formActions.
Staff gera convite de autopreenchimento na coluna de ações da lista, reutilizando createCampaignInvite e alinhando validação de celular ao link de contato do B28.
CampaignCopyableCell is a Client Component; passing formatDisplay as a
function from the leaderships RSC page broke serialization in production.
Use a preformatted displayValue string at the call sites instead.
Coluna "Dobradinhas" em /campanha/liderancas com chips clicáveis
para /campanha/dobradinhas/<slug> e edição via Popover+Command
(padrão B27, escrita via server action delta + lock, como B19).
- LeadershipRowViewModel.stateDeputies (StateDeputySummary[]) via
loadStateDeputySummaries, substituindo stateDeputyNames.
- setLeadershipStateDeputyMembership(Record): delta com
withPayloadTransaction + acquireTextAdvisoryLocks + revalidatePath.
- nextStateDeputyIdsAfterMembership (lib/leadershipStateDeputyMembership.ts),
espelha nextAdvisorIdsAfterMembership.
- loadStateDeputyOptions estendido com plainName/party/slug.
- Catálogo entregue uma vez por tabela via leadershipColumns(options)
(columns factory, mesmo precedente de municipalityListColumns).
/simplify (1ª rodada): corrige revert otimista por delta (não pelo
snapshot inteiro), remove fallback silencioso na adição, extrai
sameIdSet compartilhado com MunicipalityListAdvisorsControl (B27), e
evita leitura+revalidação supérfluas no caminho no-op da action.
/simplify (2ª rodada, pós-rebase): troca o StateDeputyOptionsProvider
(Context) inicial pela columns factory acima — a 1ª rodada tinha
validado o Context por falta da evidência de que MunicipalityList.tsx
já resolve o mesmo problema sem Context; corrige revalidatePath para
o id concreto em vez do template dinâmico '/campanha/liderancas/[id]'
(que invalidava toda ficha a cada toggle); remove non-null assertion
movendo a guarda para dentro do setCurrent updater.
Gate verde: tsc, lint --max-warnings=0, format:check, unit 530/530,
int 406/406 (incl. os 6 de campaignLeadershipStateDeputyMembership),
build. Aikido: 0 achados nos arquivos novos/editados.
Conflito unico em docs/roadmap.md, nas cinco superficies em que B14 aparece
(linha "Atualizado em", bullet do item, no do grafo, Paralelizaveis/Janela 1 e
Cortes seguros): main tinha B14 pendente mais os registros de hoje (B38 e o
fill-in de limitar o mapa a Bahia), a feature tinha B14 entregue sem eles.
Resolvido preservando os dois lados em todas elas.
Registro de roadmap-item de dois pedidos de produto de 2026-07-26, commitado
como estava na arvore de trabalho do checkout principal:
- B38 sidebar recolhido em tablet (`collapsible="offcanvas"`, trigger em `md+`,
default por faixa de viewport com o cookie `sidebar_state` vencendo apos o
toggle) + entrada no grafo de dependencias.
- Fill-in: limitar pan/zoom do mapa da Bahia a `BAHIA_BOUNDS` (`maxBounds` com
folga de 10%, `maxBoundsViscosity: 1` e `minZoom` calculado no
`ResizeObserver` que ja existe), so em `BahiaMap.tsx`.
- Nota de dependencia soft do B18 para o B38: com o rail recolhido, o submenu
de filtros salvos precisa tratar collapsed como "abrir rail".
Terceira rodada de /simplify sobre o B14, com dois enunciados errados corrigidos:
- A propriedade da fronteira compartilhada NAO vem da ordem do `.find()`, e sim
da convencao meio-aberta do ray casting (`point.lng < crossingLng`): a aresta
pertence ao poligono cujo interior fica a leste (ao norte, se horizontal). Tres
comentarios diziam o contrario, e o do unit test dizia "oeste" enquanto
afirmava `east`.
- O plano dizia que o `Promise.all` esconde o decode da malha atras do fix de
GPS. Nao esconde: o decode roda no topo do modulo, quando o chunk executa. O
paralelo continua certo por outro motivo (decode ~2 ms; sequencial jogaria os
42 KB no caminho critico quando o fix vem do cache).
Simplificacoes: `unsupported` virou estado proprio, entao `failureCopy` deixa de
ser anulavel e caem duas leituras defensivas inalcancaveis; "Voce esta em " era
escrito duas vezes (frase sr-only + JSX), o que anulava justamente a invariante
que o comentario alegava; `zoneCityHrefs` virou `Partial` porque a busca falha
para os 416 municipios sem zona e o guard existia sem o tipo exigir;
`MunicipalityForIbgeIndex` era duplicata campo-a-campo de `AccessibleMunicipality`;
`kmFormatter` duplicava `oneDecimalFormatter`; `RecentlyVisitedCard` carregava
tres props que nenhum caller passa (dez condicionais mortas); e o bbox de feature
estava escrito em dois specs (agora `tests/helpers/featureBounds.ts`, compartilhado
por vitest e Playwright).
Copy: fora da Bahia sem nada por perto dizia a mesma coisa em duas frases e nunca
dizia que voce estava fora do estado. Agora o headline afirma o fato e o detalhe
reusa "Nenhum municipio da sua carteira por perto.".
Tambem limpa um achado de knip herdado do main (`MunicipalityPoliticalTrendViewModel`
exportado sem uso) e registra no plano o caminho afiado do debito de payload RSC
mais dois adiados com gatilho.
Card "Onde estou" no dashboard staff: point-in-polygon contra a malha
municipal que o painel do mapa ja carrega, sem artefato de centroides,
sem migration, sem collection, sem server action e sem Consent -- a
posicao e lida por navigator.geolocation e casada no browser, nunca sai
do aparelho.
- src/lib/municipalityProximity.ts: haversine, ray casting, centroide
ponderado por area e uniao discriminada
(inScope | zoneCity | outOfScope | outsideBahia)
- src/utilities/campaignGeolocation.ts: flag de sessao, leitura guardada
de permissao e requestCurrentPosition com falha tipada
- Salvador nao ganha ZE chutada: link para a lista filtrada, com href
serializado no servidor (importar o serializador canonico no cliente
custava 21 kB de First Load JS)
- fallback fora da carteira ordenado por centroide, teto de 150 km
- fix grosseiro (>10 km) mostra o resultado com ressalva de precisao
/campanha First Load JS: 265 -> 268 kB.
Fecha a entrega do B33 registrando o achado do /simplify que sobrou maior
que cleanup: StateDeputyFilters é o 3º call site do mesmo scaffold de
navegação/debounce de TerritoryFilters/MunicipalityFilters. Novo fill-in
B33+ (plano escala-dry-pos-b33.md) extrai useCampaignListFilterNavigation.
Agregado SQL do facet de partido formalizado como Adiado com gatilho no
plano-pai; referência cruzada obsoleta em escala-dry-pos-e10.md corrigida
(party é texto livre, não enum fechado — o gatilho ali não disparou).
- stateDeputyListUrl.ts / stateDeputyListFilters.ts: contrato de URL/filtro
próprio (sort/dir, filtro de Partido multi + sentinela "Sem partido"),
espelhando municipalityListUrl.ts (paginação/resolveListUrl) e
territoryListUrl.ts (sort keys/labels)
- stateDeputyData.ts: where/sort resolvidos no banco + facet de partido
(loadStateDeputyPartyFacet), select estreito na query principal
- StateDeputySortableHead / StateDeputyHeaderFilter / StateDeputyFilters:
wrappers finos sobre o chrome compartilhado (shared/CampaignSortableHead,
CampaignHeaderFilterPopover), paridade mobile incluída
- dobradinhas/page.tsx: redirect canônico em duas fases, CampaignTable
sempre montada com caption + empty state, resumo de ordenação aria-live
- Correção pós-entrega (design review): "Sem partido" no mobile + caption
da tabela + copy plural do empty state
- /simplify (1ª rodada): buildStateDeputyPartyOptions compartilhado, remove
discriminante filterParam redundante, dedupe/if mortos em
stateDeputyListUrl.ts
- /simplify (2ª rodada, pós-rebase): remove cast/type morto em
stateDeputyData.ts, stateDeputyColumns usa StateDeputyFilterOption em vez
de duplicar a forma, inlinea parsePartiesParam; extrai truncatedNamesLabel
compartilhado em campaignListUrl.ts (3º call site — municipalityListFilters
e territoryListFilters tinham a mesma função com nomes distintos)
Gate verde (tsc, lint, format, check:cycles, 396 testes, build); Aikido
0 achados nos 7 arquivos tocados nesta rodada. Docs:
docs/plans/ordenacao-filtros-lista-dobradinhas.md, docs/roadmap.md,
.cursor/rules/projects/nucleos-eleitorais.mdc.
- botão WhatsApp por linha duplicado (2 call sites) — gatilho: 3º site
- copyText vs copyMessage em SupporterShareKit — gatilho: 3º site de copy-to-clipboard