ai-test-loop 1.1.3__tar.gz → 1.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,520 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-test-loop
3
+ Version: 1.2.4
4
+ Summary: Deterministic critic for AI agents: runs weighted checks for real, scores 0-100 and blocks the delivery when it should.
5
+ Author: Samuel Medeiros
6
+ License: MIT
7
+ Project-URL: Homepage, https://skills.seu.pet/p/ai-test-loop?utm_source=pypi&utm_medium=readme&utm_campaign=ai-test-loop
8
+ Project-URL: Repository, https://github.com/Samuelfmedeiros/ai-test-loop
9
+ Project-URL: Changelog, https://github.com/Samuelfmedeiros/ai-test-loop/releases
10
+ Keywords: mcp,ai-agent,ai-agents,llm,testing,test-loop,quality-gate,delivery-gate,critic,claude-code,cursor,code-review
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Topic :: Software Development :: Quality Assurance
16
+ Classifier: Topic :: Software Development :: Testing
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Dynamic: license-file
21
+
22
+ # ai-test-loop
23
+
24
+ **Your agent grades its own homework.** This makes that impossible: a critic script runs real checks,
25
+ scores the artifact 0–100, and a fail-closed gate blocks delivery below the threshold.
26
+
27
+ ```bash
28
+ npx ai-test-loop --config loop.json # zero install, no Python needed
29
+ ```
30
+
31
+ **Using Claude Code?** Install it as a plugin — the skill loads automatically
32
+ when the agent is about to declare work done:
33
+
34
+ ```
35
+ /plugin install ai-test-loop --marketplace Samuelfmedeiros/ai-test-loop
36
+ ```
37
+
38
+ **Just want a score for your project?** Paste the path or the GitHub URL — no config file:
39
+
40
+ ```bash
41
+ npx ai-test-loop --repo https://github.com/you/your-project
42
+ ```
43
+
44
+ Real output from a project that had no config at all:
45
+
46
+ ```
47
+ PASS testes automáticos (npm) w=40.0 3.93s 8 passed
48
+ FAIL padrão do código w=10.0 0.07s 7 fixable with --fix
49
+
50
+ Resultado de ai-test-loop
51
+ ----------------------------
52
+ Nenhuma falha grave, mas a nota ficou abaixo do corte por causa dos avisos.
53
+
54
+ Nota (parcial): 80 de 100 — precisa de 85 para passar.
55
+
56
+ Não deu para checar (e por isso não conta como falha):
57
+ - testes automáticos (Python): o projeto precisa de 'pytest' (pip install pytest)
58
+
59
+ SCORE=80.0
60
+ GATE=failed (round 1/1)
61
+ ```
62
+
63
+ Quick mode obeys three rules, and they are why its score can be trusted:
64
+
65
+ - **It never invents a check.** A missing tool is reported as "could not check" — it never becomes
66
+ a failure, and never becomes a pass either.
67
+ - **It never writes inside your project.** All state lives in `~/.cache/ai-test-loop/<hash>/`.
68
+ - **Nothing ran means no verdict.** If the environment is incomplete, you get exit code **2**
69
+ ("could not judge") instead of a fake green. Exit codes: `0` passed, `1` failed, `2` inconclusive.
70
+
71
+ Real output, not a mockup:
72
+
73
+ ```
74
+ PASS unit tests w=40 12.4s 41 passed in 12.31s
75
+ FAIL build w=20 3.1s error TS2307: Cannot find module './api'
76
+ PASS no secrets w=15 0.8s no leaks found
77
+ SCORE=75.0
78
+ GATE=failed (round 1/8)
79
+ GAPS=["build: exit code 2, expected 0"]
80
+ ```
81
+
82
+ > **Want this wired into your repo, with the visual-diff gate and the delivery report?**
83
+ > The ready-made packs are at **https://skills.seu.pet/en/p/pack-completo?utm_source=pypi&utm_medium=readme&utm_campaign=ai-test-loop**
84
+ > — or grab the free runner first and see if the loop earns its place.
85
+
86
+ No API keys, no dependencies, no model calls. The runner is deliberately dumb: exit codes and
87
+ optional output patterns decide pass/fail. The model never gets to *say* the work is good — it has
88
+ to *show* it.
89
+
90
+ ---
91
+
92
+ ## Install
93
+
94
+ Same package name everywhere. Both registries, same name:
95
+
96
+ ```bash
97
+ npx ai-test-loop --help # Node 18+ — nothing to install
98
+ pip install ai-test-loop # Python 3.9+ — same engine (PyPI)
99
+ ```
100
+
101
+ `npx` is the fastest path: it downloads and runs in about five seconds, no virtualenv, no Python.
102
+ The npm package carries a Node port of the runner; the PyPI package carries the Python one. Both
103
+ print the same `SCORE=` / `GAPS=` / `EVIDENCE=` contract, so the gate you run locally is the gate CI
104
+ runs.
105
+
106
+ Verify with a dry run — it lists the checks and weights without executing anything:
107
+
108
+ ```bash
109
+ npx ai-test-loop --config templates/loop.example.json --dry-run
110
+ ```
111
+
112
+ > Older docs and articles mention `pip install agent-test-loop`. That is the previous PyPI name and
113
+ > still works — it is the same engine, kept as a mirror so existing installs do not break. New code
114
+ > should use `ai-test-loop`.
115
+
116
+ ## The problem
117
+
118
+ Ask an agent "is this done?" and it answers about its own reasoning. The same context that produced
119
+ the artifact also decides it is correct, so real defects survive to delivery:
120
+
121
+ - a handler that is never called (tests pass, feature dead)
122
+ - a test that passes because it asserts nothing
123
+ - a page that breaks only at mobile width
124
+ - a migration that works on the author's data and nowhere else
125
+ - a "fix" that reverted a config someone changed on purpose
126
+
127
+ Running "one more review pass" does not help, because the reviewer and the builder are the same
128
+ process. Separating them is the whole trick.
129
+
130
+ ## Quickstart
131
+
132
+ ```bash
133
+ npx ai-test-loop --config loop.json
134
+ ```
135
+
136
+ Describe your checks once — name, command, weight:
137
+
138
+ ```json
139
+ {
140
+ "name": "my-project",
141
+ "threshold": 85,
142
+ "max_rounds": 8,
143
+ "checks": [
144
+ {"name": "unit tests", "cmd": "pytest -q", "weight": 35, "timeout_s": 900},
145
+ {"name": "type check", "cmd": "mypy src", "weight": 10},
146
+ {"name": "build", "cmd": "npm run build", "weight": 20},
147
+ {"name": "api up", "cmd": "curl -sS 127.0.0.1:8000/health", "weight": 15,
148
+ "must_match": "\"status\"\\s*:\\s*\"ok\""},
149
+ {"name": "no secrets", "cmd": "gitleaks detect --no-banner", "weight": 20,
150
+ "fail_if_output_matches": "leaks found: [1-9]", "severity": "block"}
151
+ ]
152
+ }
153
+ ```
154
+
155
+ A check that sets `required: true` without `severity` is **rejected at load**:
156
+ `required` alone never blocked anything (it only removed the check from the
157
+ "non-blocking" list), so the config author believed to have a wall and had a
158
+ discount. Declare `"block"` or `"score"` — the ambiguity is a config error.
159
+
160
+ `severity` decides what a failing check does:
161
+
162
+ - `"score"` (default) — the check costs its weight; the gate is the number.
163
+ - `"block"` — the check vetoes the run regardless of the total. A failing
164
+ `block` check prints `GATE=blocked` and exits **3** (distinct from 1, "score
165
+ too low"), so CI can tell "quality is short" from "wall". Use it for the
166
+ checks where a high score must never buy a pass: secrets, SAST, auth.
167
+ An absent `severity` keeps the previous behaviour, so existing configs are
168
+ unaffected.
169
+
170
+ Output is machine-readable, so the *agent* can act on it and a CI job can gate on it:
171
+
172
+ ```
173
+ SCORE=75.0
174
+ THRESHOLD=85
175
+ GATE=failed (round 1/8)
176
+ GAPS=["build: exit code 2, expected 0"]
177
+ EVIDENCE=loop-report-r1.json
178
+ ```
179
+
180
+ Exit code is `0` when the gate passes and `1` when it fails — so `npx ai-test-loop --config
181
+ loop.json` is a valid CI step on its own, with no parsing.
182
+
183
+ Fix the **single largest** gap, run `--round 2`, repeat. Cap the rounds (8 is plenty): if the score
184
+ never converges, the check set is wrong, not the code.
185
+
186
+ `--round` cannot be used to buy extra attempts. The round number always advances
187
+ from the state file: `--round 1` on a run that already did three rounds becomes
188
+ round 4 and aborts with `exceeded max_rounds`. The flag can move the counter
189
+ forward, never back — an abort only happens once per run either way.
190
+
191
+ The first round fingerprints the config (`config_sha256`) and every later round
192
+ compares. Rewriting the config between rounds — deleting the check that failed,
193
+ lowering a weight, dropping the threshold — sets `config_drift: true` in the
194
+ report with `expected`/`actual` **and invalidates the gate** (`GATE=blocked`,
195
+ exit `3`). Detection alone was not enough: the config is written by the same
196
+ agent being graded, so recording the attack while keeping the verdict is
197
+ accepting the attack. Re-run with `--approve <approval_id>` to re-baseline; the
198
+ id and timestamp land in the state file as `approval_id`/`approval_ts`.
199
+ Changing only `name` is not drift; the fingerprint covers `threshold`,
200
+ `max_rounds`, `strict_tests` and the per-check `cmd`, `weight`, `severity`,
201
+ `required`, `expect_exit`, `must_match`, `fail_if_output_matches`, `timeout_s`,
202
+ `min_passed` and `allow_skipped`.
203
+
204
+ ## Config reference
205
+
206
+ | Key | Meaning |
207
+ |---|---|
208
+ | `cmd` | (required) shell command, run with `bash -o pipefail -c` |
209
+ | `weight` | (required) points; weights are normalised, they need not sum to 100 |
210
+ | `timeout_s` | default 900 — a timeout is a **FAIL**, never a skip |
211
+ | `min_passed` | minimum tests reported as passed; an unrecognised summary is **NOT VERIFIABLE**, never a pass |
212
+ | `allow_skipped` | `false` fails the check on any skipped/xfail/todo count; omit to stay unpoliced |
213
+ | `strict_tests` | (top level) `true` sets `allow_skipped: false` on every check |
214
+ | `expect_exit` | default 0 |
215
+ | `must_match` | regex that must appear in the combined stdout+stderr |
216
+ | `fail_if_output_matches` | regex that fails the check when it appears |
217
+ | `required` | default `true`; `false` scores 0 but reports as a non-blocking gap |
218
+ | `cwd` | working directory for that check |
219
+
220
+ `bash -o pipefail` is not decoration: without it `pytest | tail` returns tail's exit code (0), so a
221
+ failing suite scores as passing. That is the most common false green in runners like this one.
222
+
223
+ ## The four roles (never merge them)
224
+
225
+ | Role | Who | Job |
226
+ |---|---|---|
227
+ | Orchestrator | the agent running the task | picks checks, runs rounds, owns the report |
228
+ | Builder | the agent/model that wrote the artifact | fixes one class of gap per pass |
229
+ | Critic | this script + your checks | runs real commands, returns score + gaps |
230
+ | Reviewer | a **separate** context/model | audits critic and builder, can reopen the loop |
231
+
232
+ Rule zero: builder ≠ critic ≠ reviewer. If one context does all three, the loop is theatre.
233
+
234
+ ## Three rules that make it honest
235
+
236
+ 1. **Every point is earned by a command that actually ran.** No points for "read the code". The
237
+ report stores the raw output next to each score.
238
+ 2. **A skipped test is not a passing test.** `strict_tests: true` (or
239
+ `allow_skipped: false` per check) rejects any `skipped`/`xfailed`/`todo`
240
+ count and requires a recognisable test count; a summary the runner cannot
241
+ parse becomes `NOT VERIFIABLE`, never a pass. Note that `pytest -q` with
242
+ warnings enabled prints only `.s [100%]` and no summary line — the runner
243
+ falls back to counting the progress characters.
244
+ 3. **`NOT VERIFIABLE` is not a pass.** If a check cannot run (missing device, no network, jail), it
245
+ scores 0 and the report says why. Silent skips are how a green board lies.
246
+ 4. **The security gate is fail-closed.** A secret in the diff or history, a high-severity SAST
247
+ finding, or an auth/path-traversal/injection issue found in review blocks delivery **even with a
248
+ perfect score**. An inconclusive answer counts as blocked, never as pass.
249
+
250
+ ## Reviewer panel
251
+
252
+ For anything other people will use, ask 2–3 specialists instead of one generalist — quality and
253
+ security always, performance only if there is a build or runtime cost, UX only if there is a
254
+ user-facing surface. Each returns strict JSON:
255
+
256
+ ```json
257
+ {"parecer":"CONCORDO|DISCORDO","nota":0-100,"gaps":["..."],"texto":"one paragraph with evidence"}
258
+ ```
259
+
260
+ Consensus → deliver. Majority disagree → reopen the loop with the combined gaps. Prompt in
261
+ `references/reviewer-prompt.md`, starting rubric in `references/scoring-rubric.md`.
262
+
263
+ ## Telemetry (opt-out, and what it is not)
264
+
265
+ The `npx ai-test-loop` wrapper sends **one anonymous event per run** so the project knows whether
266
+ the tool is actually used — downloads alone are not usage (npm counts mirrors and CI).
267
+
268
+ What is sent: event type (`run`/`help`/`version`/`erro`), package version, Node major, OS name,
269
+ duration in ms, and — only on a real run — the final score and the number of gaps.
270
+
271
+ What is **never** sent: your IP (not logged server-side), e-mail, project path, file names, the
272
+ content of your checks, the command output, or anything from your code.
273
+
274
+ The install id is a random UUID written to `~/.ai-test-loop/telemetry-id` once. It counts machines,
275
+ not people. Delete that file and you are a new machine.
276
+
277
+ ```bash
278
+ ai-test-loop --no-telemetry ... # that run only
279
+ export AI_TEST_LOOP_NO_TELEMETRY=1 # permanently, in your shell profile
280
+ export DO_NOT_TRACK=1 # the ecosystem-wide convention, also respected
281
+ # CI=1 is detected automatically: pipelines are not people
282
+ ```
283
+
284
+ Telemetry never blocks and never waits: if the network is down the CLI runs exactly the same.
285
+
286
+ ## When not to use it
287
+
288
+ Throwaway exploration, spike branches, and one-line answers where the cost of the loop exceeds the
289
+ cost of being wrong. It is for artifacts a human will rely on.
290
+
291
+ ## Files
292
+
293
+ | Path | What |
294
+ |---|---|
295
+ | `bin/cli.js` | the `npx` entry point (wrapper + telemetry) |
296
+ | `scripts/loop_runner.js` | the deterministic critic, Node port — zero dependencies |
297
+ | `scripts/loop_runner.py` | the same critic in Python (used by the pip package) |
298
+ | `scripts/selftest.js` | 22 assertions covering every way a check can fail — `npm test` |
299
+ | `SKILL.md` | the loop, the scoring rules, the fail-closed gate — drop it in your agent's skills dir |
300
+ | `references/reviewer-prompt.md` | independent-review prompt, strict JSON output |
301
+ | `references/scoring-rubric.md` | starting weights |
302
+ | `templates/loop.example.json` | config with the usual check set |
303
+
304
+ `npm test` runs the selftest. It needs nothing but node.
305
+
306
+ ## Get the full pack
307
+
308
+ This repo is the free, complete tool. The store has the ready-made packs for the cases where
309
+ writing the checks is the slow part — CI gates, visual regression, MCP servers, MLOps guards:
310
+
311
+ - Free download / e-mail delivery: **https://skills.seu.pet/gratis/ai-test-loop?utm_source=pypi&utm_medium=readme&utm_campaign=ai-test-loop**
312
+ - Full pack: **https://skills.seu.pet/en/p/pack-completo?utm_source=pypi&utm_medium=readme&utm_campaign=ai-test-loop**
313
+ - Catalog: **https://skills.seu.pet/?utm_source=pypi&utm_medium=readme&utm_campaign=ai-test-loop**
314
+ - Want it installed and wired into your repo: **https://skills.seu.pet/servico?utm_source=pypi&utm_medium=readme&utm_campaign=ai-test-loop**
315
+
316
+ ## License
317
+
318
+ MIT — see `LICENSE`. Use it commercially, fork it, ship it.
319
+
320
+ ---
321
+
322
+ ### Em português
323
+
324
+ O loop de teste para agentes: o construtor não assina o próprio trabalho. Um crítico roda checagens
325
+ de verdade, dá nota 0–100 e barra a entrega abaixo do limite.
326
+
327
+ ```bash
328
+ npx ai-test-loop --config loop.json # não precisa de Python
329
+ ```
330
+
331
+ Sem chave de API, sem dependência, sem chamada de modelo. Versão com entrega por e-mail e os packs
332
+ prontos: https://skills.seu.pet/gratis/ai-test-loop?utm_source=pypi&utm_medium=readme&utm_campaign=ai-test-loop
333
+
334
+ ## Integridade do runner e do contrato (v1.1.2, 12/11/2026)
335
+
336
+ O gate era decorativo porque **quem escreve o config é quem é avaliado**. Quatro
337
+ furos medidos por exploit e fechados nesta versão:
338
+
339
+ ### 1. O crítico não pode ser editável pelo réu
340
+
341
+ `config_sha256` congela a régua, não o código que lê a régua. O agente pode
342
+ reescrever `score()` para `return 100.0` e o hash de config não percebe.
343
+ Agora o runner publica `runner: {version, py_sha256, js_sha256}` no relatório e
344
+ comparar com o hash esperado é papel do orquestrador, que vive **fora** do repo:
345
+
346
+ ```bash
347
+ python3 ~/.hermes/scripts/roger-runner-pin.py pin --by "<quem>"
348
+ python3 ~/.hermes/scripts/roger-runner-pin.py check # exit 3 se divergir
349
+ ROGER_RUNNER_PY_SHA256=$(python3 ~/.hermes/scripts/roger-runner-pin.py env --key py) \
350
+ ./loop_runner.py --config loop.json
351
+ ```
352
+
353
+ Hash divergente → `GATE=blocked`, exit 3, `motivo=runner_drift`. O caso legítimo
354
+ exige `--approve-runner --approve-runner-reason "<por quê>"` — aceitar sem motivo
355
+ não é aceitar.
356
+
357
+ ### 2. O fingerprint deriva do schema
358
+
359
+ Lista literal de campos atrasa o próximo adendo: `strict_tests`, `min_passed` e
360
+ `allow_skipped` chegaram depois e ficaram **fora** do hash. O hash agora deriva de
361
+ `TOP_LEVEL_KEYS`/`CHECK_KEYS`, e `tests/test_fingerprint_schema.py` falha quando o
362
+ loader conhece uma chave que o schema não cobre. Foi esse teste que encontrou
363
+ `cwd` fora do hash.
364
+
365
+ ### 3. `--approve` não é auto-serviço
366
+
367
+ O ID de aprovação é **derivado do drift** (`sha256(expected+actual)[:8]`) e
368
+ `--approve-by <nome>` é obrigatório. O state guarda `approval_snapshot` com o
369
+ drift e a config do momento — sem ele auditar depois é impossível.
370
+
371
+ ```bash
372
+ # o bloqueio imprime o id correto:
373
+ GATE=blocked — motivo=config_drift: regua alterada sem aprovacao (a1b2 -> c3d4);
374
+ reexecute com --approve 7f3a91cc --approve-by <nome>
375
+ ```
376
+
377
+ ### 4. `blocking_gaps` bloqueia (exit 3), não desconta
378
+
379
+ Lista de regex case-insensitive no topo do config. Gap que casa invalida a
380
+ entrega mesmo com score acima do threshold. Regex inválido bloqueia
381
+ (fail-closed): padrão mal escrito não vira porta aberta.
382
+
383
+ ### Contagem de testes: JUnit XML manda
384
+
385
+ `junit_xml: "<arquivo>"` no check torna a contagem autoritativa — escrita pelo
386
+ framework, independe de `-q`/`-v`. O parser por linha de progresso (`.sxXFE`)
387
+ continua como fallback informativo, porque `-v` imprime nome de teste e cega o
388
+ parser. Saída mentirosa ("5 passed") perde para o XML real.
389
+
390
+ ---
391
+
392
+ # MIGRAÇÃO 1.1.x → 1.2.0 (breaking para configs antigos)
393
+
394
+ **O que mudou:** `required: true` sem `severity` deixou de ser aceito. Antes o
395
+ check era "bloqueante ou pontuável" a depender de quem lia o config — ambiguidade
396
+ que o próprio agente avaliado podia explorar. Agora é **erro de carga**.
397
+
398
+ **Quem é afetado:** qualquer config com `required: true` e sem `severity`. Se a
399
+ sua instalação atualiza por `pip` ou `npx` e não tinha `severity`, a próxima
400
+ execução termina com:
401
+
402
+ ```
403
+ [loop_runner] invalid config: check 'nome': required=true sem severity
404
+ [loop_runner] para corrigir automaticamente: loop_runner.py --config <arquivo> --migrate-config
405
+ ```
406
+
407
+ **Como migrar (um comando, com backup automático):**
408
+
409
+ ```bash
410
+ # 1. ver o que mudaria, sem tocar em nada
411
+ loop_runner.py --config seu-loop.json --migrate-config --dry-run
412
+
413
+ # 2. aplicar (grava seu-loop.json.bak-pre-migrate antes)
414
+ loop_runner.py --config seu-loop.json --migrate-config
415
+
416
+ # Node/npx
417
+ npx ai-test-loop --config seu-loop.json --migrate-config
418
+ ```
419
+
420
+ A regra da migração assume a intenção original: `required: true` significava
421
+ "quero isso bloqueando", então vira `severity: "block"`. Se a intenção era só
422
+ pontuar, troque para `severity: "score"` depois — o importante é que a decisão
423
+ seja explícita em vez de depender do leitor.
424
+
425
+ `strict_tests: true` também completa `allow_skipped: false` nos checks que não
426
+ declaram o campo (era o efeito implícito até a 1.1.2).
427
+
428
+ **Idempotente:** rodar de novo imprime "nada a migrar".
429
+
430
+ ---
431
+
432
+ # Mapa de severidade por classe de falha (v1.2.0)
433
+
434
+ Gap que vira desconto de ponto é gap que ninguém corrige. A varredura dos **62
435
+ critics** extraiu **257 gaps literais** de `gaps.append(...)` e classificou cada
436
+ um por classe de falha. Padrão que não casa nenhum gap real é teatro e foi
437
+ removido na validação.
438
+
439
+ **Bloqueiam (exit 3):** segredo · seguranca · antifraude · testes · build ·
440
+ cobertura · deploy · dados · ui · generico
441
+
442
+ **Não bloqueiam:** estilo (reversível em segundos) · infra (tem watchdog próprio;
443
+ bloquear aqui duplica o alarme no canal errado) · ambiente (`NÃO VERIFICÁVEL` é
444
+ ausência de prova, não prova de falha)
445
+
446
+ ## Precedência
447
+
448
+ O primeiro padrão que casar decide. Sem ordem, `test/front-audit.mjs ausente —
449
+ sem medição no navegador` casaria `testes` (bloqueia) e `ambiente` (aviso), e o
450
+ gap escaparia do bloqueio.
451
+
452
+ ```
453
+ 1. segredo 2. seguranca 3. antifraude 4. testes
454
+ 5. build 6. cobertura 7. deploy 8. dados
455
+ 9. ui 10. generico 11. estilo 12. infra 13. ambiente
456
+ ```
457
+
458
+ ## Resultado medido
459
+
460
+ Antes: 3 critics bloqueavam, 59 descontavam ponto. Gap de credencial vazada em
461
+ arquivo versionado valia −5 num rubric de 100.
462
+
463
+ Depois: 199 padrões bloqueantes nas 53 configs; 257/257 gaps classificados,
464
+ 0 órfãos. Verificação contra o orquestrador real — 12/12 casos no veredito
465
+ esperado (8 bloqueiam, 4 passam).
466
+
467
+ Mapa versionado em `~/.hermes/profiles/ajudante/state/mapa-severidade-62-critics.json`;
468
+ `tests/test_severidade_mapa.py` falha se uma classe bloqueante ficar sem gap real
469
+ (regex morto = trava decorativa).
470
+
471
+ ## Mutation testing do gate (v1.2.0)
472
+
473
+ **Score medido: 78,1%** (353 de 452 mutantes mortos, piso 70% no CI).
474
+
475
+ O alvo é `scripts/gate_core.py` — as funções que **decidem bloqueio**
476
+ (`score`, os dois fingerprints, `drift_approval_id`, `migrate_config`,
477
+ `validate_config`, `parse_junit_xml`, `parse_test_counts`). Elas foram extraídas do
478
+ `loop_runner.py` em 12/11/2026 por um motivo medido: o runner tem 864 linhas e o
479
+ mutmut expande o módulo inline para 21 MB — compilar o arquivo mutado levava mais de
480
+ 180s e a rodada de 1827 mutantes nunca terminava.
481
+
482
+ Por que isso importa mais que o meta-gate: o meta-gate do §10 prova que **um caso**
483
+ passa. Mutation testing prova que a suíte **pega regressão**.
484
+
485
+ ### Rodar localmente
486
+
487
+ ```bash
488
+ pip install mutmut pytest
489
+ mutmut run # ~20s, 452 mutantes
490
+ mutmut results # lista os sobreviventes
491
+ mutmut export-cicd-stats # killed/survived/total em JSON
492
+ ```
493
+
494
+ No CI (`.github/workflows/loop.yml`, job `mutation`, `needs: critic`) o piso é 70%,
495
+ e o job também falha se nenhum mutante for gerado — alvo removido é medição
496
+ ausente, não aprovação.
497
+
498
+ ### Três armadilhas que custaram rodadas
499
+
500
+ 1. **Teste que chama o runner por `subprocess` não mata mutante.** 9 dos 10 arquivos
501
+ de teste executam `loop_runner.py` como processo; dentro de `mutants/` o runner
502
+ não acha a config do mutmut, sai com erro de ambiente e o mutante morre por
503
+ crash. Todos parecem mortos e o score mede o sandbox, não os testes. Só
504
+ `pytest_add_cli_args_test_selection` com os arquivos que **importam** o módulo.
505
+ 2. **Import tem de ser qualificado** (`from scripts.gate_core import ...`). Com
506
+ `import gate_core` bare, as trampolines saem como `gate_core.x_...` contra
507
+ `scripts.gate_core.x_...` esperadas e o mutmut aborta.
508
+ 3. **`do_not_mutate = ["mutants/*"]` é obrigatório** — sem ele o mutmut copia a
509
+ própria árvore mutada dentro de si e a geração não termina.
510
+
511
+ ### Dois bugs que a mutação revelou
512
+
513
+ Os mutantes sobreviventes em `parse_test_counts` não eram só falta de cobertura:
514
+
515
+ - `Tests: 2 skipped, 10 passed, 12 total` (jest/vitest) era contado **duas vezes**
516
+ — pelo parser específico e pelo regex genérico — virando `passed: 21`;
517
+ - `Test Suites: 1 passed` era somado como teste, inflando `passed` de 10 para 11.
518
+
519
+ Nos dois casos o efeito era o mesmo: `min_passed` passava com **menos testes reais**
520
+ do que o exigido. Corrigido, com regressão em `tests/test_gate_parsing.py` (39 testes).