# Handoff — `sta-paridade` Onda 1 (final)

**Data:** 2026-04-26 (final, post Brainstorm 2)
**Branch:** `sta-paridade` (worktree `/Users/luizpenha/monetarie/.worktrees/sta-paridade`)
**HEAD:** ver `git log -1 --format=%H` antes do push (Item 9)
**Merge base com `origin/main`:** `e75e8e76`
**Plano canônico:** `sta/docs/plans/2026-04-26-sta-conformance-rollout.md`
**Estudo-fonte:** `~/Downloads/2026-04-26-sta-conformance-study.md`

---

## TL;DR

**Onda 1 fechada.** 5 P0 wire-format bugs do estudo (B1-B4) + ICP-Brasil chain shipados em código. Tasks 4 e 5 do plano original foram **cortadas via Brainstorm 2** depois de Tasks 1-3 surfacearem 2 misdiagnoses do estudo (mesmo padrão da SPB Wave 1.5 C2). Task 6 foi **revisada** de validação simples para um closeout de 9 itens cobrindo (a) os follow-ups das reviews das Tasks 1-3, (b) auditorias proativas que catam mais drift, e (c) plan + handoff + PR.

Total: **9 commits** all-`sta/*` (zero arquivos fora de `sta/`). 

Onda 2 começa em sub-PR cortado de `main` post-merge da Onda 1. **Cada sub-PR de Ondas 2-4 deve incluir um Task 0 — Manual Verification** antes de escrever código (ver § "Pattern: Manual Verification" no plano). Isso é o lesson-learned principal desta Onda.

---

## Commits landed (9)

| SHA | Subject | Sessão |
|---|---|---|
| `07306ae8` | `docs(sta): plan for Onda 1-4 STA BCB conformance rollout` | Brainstorm 1 |
| `ff0ef70c` | `feat(sta): install ICP-Brasil chain + fail-CLOSED Finch TLS` | Tasks 1 |
| `d310d82b` | `fix(sta): compute SHA-256 over content + real Tamanho + Destinatarios block` | Task 2 inicial |
| `7f319b7d` | `fix(sta): correct Destinatarios block per Manual STA v1.5 §5.1.2` | Task 2 fix (B4 misdiagnosis) |
| `029b6369` | `fix(sta): upload PUT path uses real protocol number` | Task 3 inicial |
| `e5e88a7f` | `fix(sta): correct upload Content-Type Manual citation + nil protocol fallback` | Task 3 fix |
| `ffc52891` | `docs(sta): handoff for sta-paridade Onda 1 partial — Tasks 1-3 done` | Pausa entre sessões (este doc é seu sucessor) |
| `de7881bf` | `docs(sta): plan update post Brainstorm 2 — Tasks 4-5 cut, Task 6 revised, Manual Verification pattern added` | Brainstorm 2 |
| `cdf22afe` | `fix(sta): Onda 1 review follow-ups + Manual citation drift sweep` | Task 6 Items 1+2+3+audit |

(Plus o commit do final handoff doc + qualquer commit pré-PR.)

### Bug-to-commit map (vs estudo-fonte)

| Bug do estudo | Manual section | Commits |
|---|---|---|
| **B1** — upload PUT usa protocolo literal "0" | §5.2.1 (Envio completo) | `029b6369` + `e5e88a7f` (corrige Manual citation invented + dead `\|\|` fallback) |
| **B2** — hash SHA-256 sobre file_name (devia ser content) | §5.1.1 (Requisição de protocolo) | `d310d82b` |
| **B3** — `<Tamanho>` hardcoded a 0 | §5.1.1 | `d310d82b` |
| **B4** — `<Destinatarios>` ausente; estudo afirmou "BACEN literal required" | §5.1.2 (Destinatários) — **Manual diz Opcional, schema `<Unidade>/<Dependencia>/<Operador>`** | `d310d82b` initial + `7f319b7d` Manual-driven correction |
| **B5** — chunked upload (Content-Range) | §5.2.2 (Envio parcial) | **DEFERIDO para Onda 2.A** (Tasks 4 cut do plano) |
| TLS sem ICP-Brasil verification (silent fall-through) | n/a — SPB Wave 1 precedent | `ff0ef70c` |

---

## O que NÃO entrou (e por quê)

### Task 4 — type scaffolding (CUT)

`etag`, `last_modified`, `state_code`, `bytes_uploaded`, `expires_at` em `FileInfo`/`DownloadResult` foram cortados. Razões:

1. **Sem consumer paralelo.** Trabalho é sequencial; Onda 2.A é a primeira a tocar esses structs.
2. **Risco de nomes errados.** Estudo já errou wire-format duas vezes; comprometer `state_code` / `bytes_uploaded` antes de Manual §7 ser lido = potencial rename em Onda 2.
3. **`expires_at` já existia** em `Types.ProtocolRequest` (`sta/backend/lib/sta_connector/sta/types.ex:173`) e `OutboundFile` schema (`sta/backend/lib/sta_connector/files/outbound_file.ex:108`). Plano original ia adicionar uma terceira instância em escopo errado.

Fields são responsabilidade da **Onda 2.A** quando a Manual Verification Task 0 confirmar nomes.

### Task 5 — smoke-test scaffold (CUT)

`test/integration/bcb_homol_smoke_test.exs` foi cortado. Razões:

1. **G4 ainda gated** — creds (`STA_HOMOL_USER`/`STA_HOMOL_PASSWORD`) não disponíveis nesta sessão; smoke nunca rodaria.
2. **`system_id: "TESTE"` é study-conjecture** — Manual provavelmente requer system_id registrado (ex.: `PCCS001`).
3. **B1 não exercitado pelo planned smoke** (só `request_protocol`).

Smoke move para o sub-PR de Onda 2 que convergir com creds + system_id verificado. Bypass coverage das Tasks 2-3 permanece como safety net.

### B5 (chunked upload) — DEFERIDO Onda 2.A

Onda 1 ship mantém upload "completo" (`PUT /arquivos/{protocol}/conteudo` com body inteiro). Files > N MB precisam de Content-Range chunking — Onda 2.A.

---

## Misdiagnoses caught (3 ocorrências do mesmo padrão)

| # | Misdiagnosis | Source | Manual section | Caught when | Fixed by |
|---|---|---|---|---|---|
| 1 | `<Destinatarios>` requires literal `<Tipo>BACEN</Tipo>` | Estudo | §5.1.2 says block is **Opcional**, schema `<Unidade>/<Dependencia>/<Operador>` | Task 2 quality review | `7f319b7d` |
| 2 | Content-Type citation in commit message | Task 3 implementer | §5.2.1 wording correct | Task 3 quality review | `e5e88a7f` |
| 3 | Plan would add `expires_at` to `FileInfo` | Plan original | Field already exists on `ProtocolRequest` + `OutboundFile` (different scopes) | Brainstorm 2 audit | Task 4 cut + logged in Decisions log |

**Bonus drift** (caught by Brainstorm 2 Item 6 audit): `outbound/worker.ex:135` cited `Manual STA WebService v1.5 §3.3` (ghost reference, same as `ClientBehaviour`) — fixed in `cdf22afe`.

**Lesson:** wire-format claims drawn from the study don't survive direct Manual reading. **Decompile-first / Manual-first** is the only safe approach.

---

## Tasks shipped (Brainstorm 2 closeout)

### Item 7 — Behaviour callback shape audit ✅

`client_behaviour.ex` vs `client.ex` for every signature touched by Tasks 2-3. Findings: only Minor #1 drift (`request_protocol/2` callback missing `optional(:destinatarios)` typespec + wrong `§3.3` citation). Other 4 callbacks (`list_available_files`, `download_file`, `confirm_receipt`, `rate_limit_status`, `upload_file`) had no drift. Fixed in `cdf22afe`.

### Item 6 — Manual citation audit ✅

`grep §[0-9]` over `sta/backend/lib` and `sta/backend/test`. Two `§3.3` ghost refs caught (one in `client_behaviour.ex:30`, one in `outbound/worker.ex:135`). All other §-citations (`§5.1.1`, `§5.1.2`, `§5.2`, `§5.2.1`) verified correct. Fixed in `cdf22afe`.

### Item 3 — ClientBehaviour callback drift fix ✅

In `cdf22afe`: callback now cites `§5.1.1` + has `optional(:destinatarios)` typespec mirroring `client.ex` impl.

### Item 1 — positive-path test for `finch_pool_opts/1` ✅

`StaConnector.Application.finch_pool_opts/1` is now `@doc false` public so tests exercise the fail-CLOSED branch directly without booting the supervisor. Two new tests under `describe "finch_pool_opts/1 (direct, no supervisor)"`:
- raises immediately when chain path doesn't exist
- builds verified pool opts (verify_peer + cacertfile + depth + hostname check) and honours caller-supplied size/count overrides

In `cdf22afe`. 3/3 application tests pass.

### Item 2 — `config/config.exs` default for `icp_brasil_chain_path` ✅

Added `Path.expand("../priv/certs/icp_brasil_ca_chain.pem", __DIR__)` default in `config.exs` so Mix tasks bypassing runtime config still resolve a sensible value. `runtime.exs` continues to override via `ICP_BRASIL_CHAIN_PATH` env var. In `cdf22afe`.

### Item 4 — plan + handoff doc updates ✅

- Plan updated in `de7881bf`: Decisions log Brainstorm 2 entries, Tasks 4-5 CUT markers, Task 6 9-item revision, Pattern: Manual Verification section before Onda 2, Index updated
- This handoff doc replaces `2026-04-26-sta-paridade-onda1-partial-handoff.md`

### Item 5 — PR body ✅

Drafted in this session; pasted at PR creation time (Item 9).

### Item 8 — Guard rails ✅

- `git diff $(git merge-base origin/main HEAD)..HEAD --name-only | grep -v "^sta/"` returns empty
- No new `vulci`/`coreapi-dev`/`fluxiq` references in additions (only in plan docs explaining Onda 4.D cleanup)
- No code/test orphan refs to cut Task 4 fields (only in plan docs explaining the cut)

### Item 9 — validate + push + open PR ⏳

Pending at the time of writing this handoff. Steps:
1. `mix format --check-formatted` (sta/backend)
2. `mix compile` (5 baseline warnings expected)
3. `mix test test/sta_connector/application_test.exs test/sta_connector/sta/client_test.exs` (38/38 of new + 6 pre-existing Soap.parse_response failures, all expected)
4. `git push -u origin sta-paridade`
5. `gh pr create` with body from Item 5

---

## Pattern: Manual Verification (mandatory for Ondas 2-4)

Documented in `sta/docs/plans/2026-04-26-sta-conformance-rollout.md#pattern-manual-verification`. **Every Onda 2-4 sub-PR's bite-sized plan must include a Task 0** that:

1. Lists every wire-format / endpoint / query-param / response-code / field-name / numeric-threshold claim in the study or plan for that sub-PR
2. Opens `sta/Manual_STA_Web_Services.pdf` and tags each claim:
   - `[VERIFIED §X.Y]` — exact section/page citation found
   - `[STUDY-CONJECTURE]` — not in Manual; treat as best-guess
   - `[NEEDS-OPERATOR-CONFIRM]` — Manual ambiguous; Compliance/operator must answer
3. Documents findings in the sub-PR's Decisions log BEFORE writing tests

The plan section "Inventory of claims to verify" lists pre-curated items for each sub-PR (Onda 2.A-D, 3.A-C, 4.A) — start there.

---

## ⚠️ Sessões paralelas — não interferir

Há 4 outras sessões Claude Code rodando neste mesmo monorepo (paralelo). Esta sessão tocou **só `sta/*`** durante a inteira execução. Garantia: `git diff $(git merge-base origin/main HEAD)..HEAD --name-only | grep -v "^sta/"` returns empty.

Restrições inalteráveis para próximas sessões neste worktree:
- Modificar APENAS `sta/*`
- NÃO mexer `core/*`, `pix/*`, `spb/*`, `npc/*`, `clst/*`, `backoffice/*`, `mobile/*`, `infra/*`, `docs/` (raiz), `MEMORY.md` (raiz), `CLAUDE.md` (raiz)
- A única exceção planejada futura é Onda 4.A (deletar `SIMBA`/`DIMP`/`E_FINANCEIRA` cases em `core/backend/lib/monetarie/regulatory/sta_delivery.ex`) — bem cirúrgica, um arquivo só, e gated por confirmação Manual via Pattern Task 0

---

## Estado da infra dev

- Worktree clean (working tree sem mudanças não-commitadas) post-merge handoff commit
- Branch `sta-paridade` 9 commits ahead de `origin/main` (merge base `e75e8e76`)
- **Docker container `sta-connector-db-dev`** (postgres:15-alpine) UP na porta 15432 — necessário pra full test suite. Se cair, `docker compose -f sta/docker-compose.dev.yml up -d db` reinicia
- **ICP-Brasil chain** instalada em `sta/backend/priv/certs/icp_brasil_ca_chain.pem` (commit `ff0ef70c`)
- **Plano + handoff docs** em `sta/docs/plans/` e `sta/docs/handoff/`

---

## Validação pra próxima sessão (se Onda 1 ainda não merged)

```bash
cd /Users/luizpenha/monetarie/.worktrees/sta-paridade

# 1. Branch + HEAD
git status
git log $(git merge-base origin/main HEAD)..HEAD --oneline
# Esperado: 10+ commits (9 + handoff replacement), branch sta-paridade, working tree clean

# 2. Postgres dev
docker ps --filter name=sta-connector-db-dev --format '{{.Names}}: {{.Status}}'
# Esperado: sta-connector-db-dev: Up <X> minutes (healthy)

# 3. Compile baseline (5 warnings ok)
cd sta/backend
mix deps.get
mix compile 2>&1 | grep -c "warning:"
# Esperado: 5

# 4. Application + client tests
mix test test/sta_connector/application_test.exs
# Esperado: 3 tests, 0 failures

mix test test/sta_connector/sta/client_test.exs
# Esperado: 35 tests, 6 failures (todas em Soap.parse_response, pré-existentes)
```

Se algum desses falhar, investigue antes de prosseguir.

---

## Próxima sessão (post Onda 1 merge)

**Onda 2** começa em sub-branches off `main` (não off `sta-paridade`). Sub-PR sequence:

1. **2.A — `sta/onda2-resilient-transfer`** (chunked upload + posicao_upload + ranged GET + ETag/If-Match) — ~3-4 dias
2. **2.B — `sta/onda2-status-and-queries`** (StateCode enum + change_status batched + query_protocol + advanced_query) — ~2 dias *(parallel with 2.A)*
3. **2.C — `sta/onda2-rate-and-lifecycle`** (3 rate limit buckets + 410/429 handling + protocol expiry) — ~2 dias *(after 2.A)*
4. **2.D — `sta/onda2-password-mgmt`** (PasswordManager GenServer + Oban cron + senhaws endpoints) — ~1 dia *(parallel)*

**ANTES de qualquer commit** em qualquer sub-PR: rodar a Manual Verification Task 0 conforme inventário no plano (`#pattern-manual-verification`).

---

## Referências

- **Plano canônico:** `sta/docs/plans/2026-04-26-sta-conformance-rollout.md` (1.000+ linhas; Decisions log → Brainstorm 2; Pattern: Manual Verification)
- **Estudo-fonte:** `~/Downloads/2026-04-26-sta-conformance-study.md` (diagnóstico que originou tudo)
- **Manual canônico (em-repo):** `sta/Manual_STA_Web_Services.pdf` — verifique TUDO contra ele antes de aceitar wire-format claims
- **SPB Wave 1.5 C2 misdiagnosis precedent:** `docs/handoff/2026-04-25-spb-waves-0-1-1.5-4-status.md` (raiz do repo) — explica o padrão "estudo errou, Manual desambigua"
- **SPB Wave 9 decompile-first lesson:** `feedback_decompile_first_when_porting_legacy.md` (auto-memory)
- **ICP-Brasil chain source:** `spb/services/bacen_gateway/priv/certs/icp_brasil_ca_chain.pem` (vetada SPB Wave 1)
