window.DATA_DOCS={"20260913_143905_original_folder_coverage_vs_canonical_audit.md":"# `original/` Folder Coverage vs. the BR-TAXQA-R Canonical Document List\n\n**Generated:** 2026-09-13 14:39:05 (local time, from `date +%Y%m%d_%H%M%S`)\n**Question:** have all required documents been captured inside `original/`?\n**Answer:** **Yes — 459 of the 462 canonical documents are present (99.4%). The 3 absent ones are the documents that were already known to be unobtainable or mis-keyed; no document that was successfully fetched is missing from `original/`.**\n\n**Reference audit:** [`../br-taxqa-document-fetcher/20260731_212654_canonical_duplicates_and_missing_documents_audit.md`](../../br-taxqa-document-fetcher/20260731_212654_canonical_duplicates_and_missing_documents_audit.md)\n**Canonical source:** `br-taxqa-document-fetcher/output_canonical/canonical_referred_documents.json` (478 references → 462 unique documents)\n\n---\n\n## Headline numbers\n\n| | Count |\n|---|---:|\n| Canonical references | 478 |\n| Unique canonical documents | 462 |\n| **Canonical documents covered by a file in `original/`** | **459 (99.4%)** |\n| **Canonical documents with no file** | **3** |\n| `.docx` files on disk under `original/` | 461 |\n| — of which distinct basenames | 459 |\n| — byte-identical copies filed in two folders | 2 |\n| Files not serving any canonical record | 3 |\n\nThe 459 covered documents are served by 456 distinct files: three files each satisfy two\ncanonical records (see [Files serving two records](#files-serving-two-canonical-records)).\n\n---\n\n## Method\n\nMatching reproduces the reference audit's rules, against the 462 unique records keyed by\n`(type_slug, number, date, canonical_name)`. Filenames were parsed as\n`__[_N].docx`; numbers normalized by stripping thousand\nseparators and leading zeros while **preserving Medida Provisória suffixes** (`2158-35`);\ndates normalized from the Portuguese long form. Prefixes come from\n`receita_norma_fetcher.ACT_TYPES[slug].file_prefix`, extended with `lei`, `lei_comp`,\n`decreto`, `decreto_lei`, `mp`, and the manual-round prefixes.\n\n| Rule | Matches |\n|---|---:|\n| 1. Exact `prefix + number + date` | 413 |\n| 2. Hand-verified mapping (jurisprudência, súmulas, pareceres SEI/PGFN, constituição, …) | 26 |\n| 3. Undated canonical record → `prefix + number`, any date | 9 |\n| 4. Hand-verified mapping, `outros` bucket (DBF, DIMOB, DMED, DOI, DIRF, DIAT, Carnê-Leão, …) | 6 |\n| 5. `prefix + number`, date differs — absorbs the audit's documented date defects | 2 |\n| **Total matched** | **456 files → 459 records** |\n\nRule 5 fired exactly twice, on the two date discrepancies the reference audit already\nrecorded — neither is a coverage gap:\n\n| Canonical record | File in `original/` | Note |\n|---|---|---|\n| `Decreto-Lei nº 1.535, de 15 de abril de 1977` | `articulados/decreto/decreto_lei_1535_19770413.docx` | Act text reads *\"DE 13 DE ABRIL DE 1977\"*; the canonical date is wrong. |\n| `Instrução Normativa RFB nº 1.131, de 20 de fevereiro de 2011` | `articulados/instrucao_normativa_rfb/in_rfb_1131_20110221.docx` | Act text reads *\"DE 21/02/2011\"*; canonical date off by one day. |\n\n---\n\n## The 3 documents not present\n\nAll three were already open in the reference audit, or are explained by it. **None is a\ncapture failure in `original/`** — there is no file to copy in the upstream folders either.\n\n| # | Document | `type_slug` | Status |\n|---:|---|---|---|\n| 1 | Convenção de Berna da União Postal Universal (UPU) | `tratados_convencoes` | **Known-missing (audit #1).** No act number, no date; the dataset's own `filedata` is a Wikipedia article about the UPU, not a treaty text. There is no Brazilian normative act to fetch unless the target is redefined as the promulgating decree of a specific UPU act. |\n| 2 | Solução de Consulta Interna Cosit nº 5, de 28 de março de 2006 | `solucao_de_consulta_interna_cosit` | **Known-missing (audit #2).** The canonical record is mislabelled — the dataset's `filedata` is `Ato Declaratório Executivo Cosit nº 5, de 24 de fevereiro de 2006`. The audit's recommended re-key **was never carried out**: `ato_declaratorio_executivo_cosit/` still holds only `ade_cosit_30_20010723.docx`, upstream and in `original/`. |\n| 3 | Acordo para Evitar a Dupla Tributação … Brasil e Alemanha | `tratados_convencoes` | **Not flagged as missing by the July audit, but absent here.** No treaty-like file exists anywhere under `original/`. The audit's coverage table credits `tratados_convencoes` with 1 of 2 served from `output_manual`; that manual file is not in the current `output_manual/documents/` listing either, so the accord is uncovered on both sides. |\n\n> **Note on item 3.** The July audit reported only 2 missing documents; this analysis reports 3.\n> The difference is the Brazil–Germany accord, which the audit counted as manually served. It is\n> not present in `original/` and no corresponding file remains in `output_manual/documents/`.\n> This is the one item worth re-checking against the manual round's working copies before\n> concluding it was lost.\n\n---\n\n## Findings worth recording\n\n### Files serving two canonical records\n\nThe canonical de-duplication key slightly over-counts: three pairs of records are the same act\nunder two canonical names, so 459 records are covered by 456 files.\n\n| File in `original/` | Canonical records served |\n|---|---|\n| `não_articulados/parecer_sei/parecer_sei_110_2018.docx` | `Parecer SEI nº 110, de 26 de agosto de 2020` (idx 334) · `Parecer SEI nº 110` (idx 336) |\n| `não_articulados/parecer_normativo_cst/pn_cst_129_19730913.docx` | `Parecer Normativo CST nº 129, de 13 de setembro de 1973` (idx 297) · `Parecer Normativo nº 129, de 13 de setembro de 1973` (idx 326) |\n| `articulados/instrucao_normativa_srf/in_srf_67_19880421.docx` | `Instrução Normativa RFB nº 67` (idx 140) — see below |\n\n`Instrução Normativa RFB nº 67` (undated) is served by `in_srf_67_19880421.docx`: the órgão in\nthe canonical record (`RFB`) is wrong — the dataset content is **IN SRF nº 67 de 21/04/1988**.\nThe file is correctly filed under `instrucao_normativa_srf/`, so the record *is* covered; only\nthe canonical metadata is defective.\n\n### Files present that serve no canonical record (3)\n\n| File | Status |\n|---|---|\n| `articulados/lei/lei_3071_19160101.docx` | Código Civil de 1916 — cited only indirectly, no canonical record. Harmless extra; carried over from `fetched_documents`. |\n| `articulados/lei/lei_5869_19730111.docx` | CPC de 1973 — same situation. |\n| `articulados/instrucao_normativa_srf/in_srf_67_19880421.docx` | Not actually extra — it serves canonical idx 140 under the corrected órgão (above). Listed here only because the strict `type_slug` key does not reach it. |\n\n### The two byte-identical duplicates\n\nTwo files are filed under **both** `articulados/` and `não_articulados/`, with matching MD5s:\n\n| Basename | MD5 | Locations |\n|---|---|---|\n| `port_conj_tse_srf_74_20060110.docx` | `17ff5f57…d01b2` | `articulados/outro/` · `não_articulados/outro/` |\n| `resol_cgpc_26_20080929.docx` | `91ac00d9…1bfe2` | `articulados/outro/` · `não_articulados/outro/` |\n\nThis is why the tree holds 461 files but only 459 distinct documents. Both acts are arguably\narticulated (a Portaria Conjunta and a Resolução, both with numbered articles); if the\narticulado/não-articulado split is meant to be a partition, **one copy of each should be\nremoved**. If the duplication is deliberate — e.g. each folder is meant to be independently\ncomplete — no action is needed.\n\n### Upstream drift since the July audit\n\n`output_manual/documents/` now holds **61** `.docx`, not the 62 the audit recorded. The\ndifference is `sci_cosit_20130215.docx`, which the audit identified as redundant (a 14 KB\nementa-only extract of an act already served in full by\n`output_receita_federal/…/sci_cosit_5_20130215.docx`) and marked *\"safe to delete\"*. It is gone\nfrom `output_manual/` and correctly absent from `original/` — the deletion was carried out as\nrecommended.\n\n---\n\n## Coverage by top-level bucket\n\n| Bucket | Folders | Files |\n|---|---:|---:|\n| `original/articulados` | 12 | 226 |\n| `original/não_articulados` | 20 | 235 |\n| **Total** | **32** | **461** |\n\n### `articulados/`\n\n| Folder | Files |\n|---|---:|\n| `ato_declaratorio_executivo_codac` | 1 |\n| `ato_declaratorio_executivo_cosit` | 1 |\n| `ato_declaratorio_executivo_rfb` | 2 |\n| `ato_declaratorio_executivo_srf` | 1 |\n| `ato_declaratorio_interpretativo_rfb` | 3 |\n| `ato_declaratorio_interpretativo_srf` | 9 |\n| `decreto` | 47 |\n| `instrucao_normativa_rfb` | 23 |\n| `instrucao_normativa_srf` | 17 |\n| `lei` | 110 |\n| `medida_provisoria` | 7 |\n| `outro` | 5 |\n\n### `não_articulados/`\n\n| Folder | Files |\n|---|---:|\n| `acao_direta_inconstitucionalidade` | 2 |\n| `ato_declaratorio_comum_cosar` | 1 |\n| `ato_declaratorio_comum_cosit` | 1 |\n| `ato_declaratorio_comum_pgfn` | 14 |\n| `ato_declaratorio_comum_srf` | 7 |\n| `ato_declaratorio_normativo_cosit` | 6 |\n| `ato_declaratorio_normativo_cst` | 5 |\n| `nota_pgfn` | 5 |\n| `nota_sei` | 1 |\n| `outro` | 20 |\n| `parecer_cosit` | 1 |\n| `parecer_normativo_cosit` | 7 |\n| `parecer_normativo_cst` | 24 |\n| `parecer_pgfn` | 7 |\n| `parecer_sei` | 3 |\n| `portaria_mf` | 4 |\n| `solucao_de_consulta_cosit` | 109 |\n| `solucao_de_consulta_disit` | 2 |\n| `solucao_de_consulta_interna_cosit` | 12 |\n| `solucao_de_divergencia_cosit` | 4 |\n\n---\n\n## Recommended actions\n\n1. **Brazil–Germany double-taxation accord** — re-check the manual round's working copies. This\n is the only item that may represent an actual loss rather than a known-unobtainable document.\n2. **SCI Cosit nº 5 (28/03/2006)** — carry out the July audit's recommendation: re-key the\n canonical record to `type_slug = ato_declaratorio_executivo_cosit`, `number = 5`,\n `date = 24 de fevereiro de 2006`, then run\n `python fetch_receita_normas_main.py --only ato_declaratorio_executivo_cosit`.\n3. **UPU / Convenção de Berna** — close as *not applicable* unless the target is redefined as a\n specific promulgating decree. There is no Brazilian act to fetch.\n4. **Decide the duplicate policy** for `port_conj_tse_srf_74_20060110.docx` and\n `resol_cgpc_26_20080929.docx` — remove one copy each if the two buckets are meant to partition.\n5. **Optional metadata fixes** (do not affect coverage): correct the canonical dates for\n Decreto-Lei nº 1.535 and IN RFB nº 1.131, and the órgão for IN RFB nº 67 → `instrucao_normativa_srf`.\n\n---\n\n## Reproducing this analysis\n\nThe matcher is at\n`/tmp/claude-0/-work-doutorado-artigos-RAG-evaluation-br-taxqa-r-v2-0/a6967aba-b5c9-44db-8ea2-b368bb093be0/scratchpad/match3.py`\n(session scratchpad — copy it into `scripts/` if it should be kept). It takes\n`output_canonical/canonical_referred_documents.json` plus a walk of `original/`, and its only\nproject dependency is `receita_norma_fetcher.ACT_TYPES`. Run it from the project root. The\nhand-verified mapping for the manual-round filenames is the only part that cannot be regenerated\nmechanically; it is embedded in the script and derived from the reference audit.\n","20260923_193852_segmentation_strategies_for_rag_experiments.md":"# Segmentation Strategies for the BR-TaxQA-R v2.0 RAG Experiments\n\n**Generated:** 2026-09-23 19:38:52 (local time, from `date +%Y%m%d_%H%M%S`)\n**Goal:** choose which segmentation strategies to compare when evaluating whether hierarchical\nsegmentation of the LexML-parsed legal documents gives better chunks for a RAG system that answers\nthe **prose** (not multiple-choice) questions of BR-TaxQA-R. System answers are compared against\nthe gold answers in `docs/P&R IRPF 2024 - v1.0 - 2024.05.03.pdf` using nuggets.\n\n**Decision (summary):**\n\n| ID | Strategy | Status |\n|---|---|---|\n| **S1** | Article (flat) + metadata | Baseline |\n| **S2** | Article + sub-article units (caput, §, inciso, alínea, item), each with its **ancestor path** (no siblings) + metadata; paragraph chunks carry the article label, **not** the caput | Main hypothesis |\n| S3 | S2 + grouping chunks (parte, livro, título, capítulo, seção, subseção) | Optional |\n| S4 | S3 with the caput's opening sentence after the article label in paragraph-family chunks (S2c: the same for S2) | Optional (added 2026-10-05) |\n| S5 | S3 with the full caput in paragraph-family chunks | Optional, later |\n\nAll of them come from **one** embedding run per embedding model: S1–S3 are `Tipo` filters over one\nchunk set, and S4/S2c swap in a second text variant of the paragraph-family chunks (column\n`variante`). This saves budget for sweeping context size, the generator LLM and the embedding model.\n\n> **Update 2026-10-05/08:** decisions D-A/D-B of\n> `docs/20261005_184116_segmentation_s3_vs_lima_ementa_and_caput_strategy_plan.md` removed the caput\n> sentence from the paragraph chunks of S2/S3 (§6 item 2 below is reversed) and added S4/S2c/S5. In\n> [F]'s terms, S1 = \"Core Chunks + Metadata\" and S2 = \"Hierarchical\" without hierarchy titles and\n> groupings. Since the 2026-10-08 rebuild the chunk counts are in `segmented/segmentation_report.md`.\n\n**Sources discussed:**\n\n- Fernandes, Lima, de Martim, Oliveira, Lotufo, Pereira — *Structural Segmentation for Brazilian\n Legal Document Retrieval* (`../Artigo chunks legislação.pdf`), referred to below as **[F]**.\n- Oliveira Lima, J.A. — *Unlocking Legal Knowledge with Multi-Layered Embedding-Based Retrieval*,\n arXiv:2411.07739 (2024), referred to below as **[L]**.\n- `../lexml-parser-projeto-lei/scripts/GeraCSVporArtigoPorAgrupador.xsl` (applied in batch by\n `run_segmentation_csv.py`), referred to below as **the XSL**.\n\n---\n\n## 1. Strategies evaluated in [F]\n\n[F] adopts the multi-layered segmentation of [L] (§3.2) with these levels:\n\n| Level | Content |\n|---|---|\n| Document | Whole text (used only as the baseline, from the Juá benchmark) |\n| Document component | Main normative text; non-normative components (tables, annexes, justification of bills) |\n| Basic unit hierarchy | Each grouping of articles (subseção, seção, capítulo, título, livro, parte) |\n| Basic unit | Each article, with all its subdivisions |\n| Basic unit component | Each caput and each paragraph |\n| Enumeration | Each inciso / alínea / item |\n\nEach chunk can be enriched with context: **document title + summary (ementa)** (\"metadata\") and the\n**titles of all enclosing groupings**.\n\nThe four representation strategies (Table 1 of [F]):\n\n| Strategy | Chunks | Context |\n|---|---|---|\n| Hierarchical Chunks | All levels from document component to enumeration | Title + Summary + Hierarchy |\n| Core Chunks + Full Context | Articles + non-normative document components | Title + Summary + Hierarchy |\n| Core Chunks + Metadata | Same | Title + Summary |\n| Core Chunks + No Context | Same | None |\n\nFindings relevant here:\n\n- Context-enriched segmentation beats whole-document indexing for dense retrievers; **No Context\n is consistently worse**.\n- There is **no clear evidence that hierarchy titles help beyond title + summary**; [F] recommends\n Core Chunks + Metadata.\n- Segmentation does not consistently help BM25.\n- Retrieval uses max-score aggregation of chunk scores into document scores (an IR evaluation, not RAG).\n\n## 2. What the XSL covers\n\nThe XSL writes one CSV row per structural unit (`Tipo, Rotulo, Num_Inicio, Num_Final, Texto, urn`).\n`Texto` = `[ ] `. Content inside `Alteracao` (quoted amending text) gets no rows\nof its own.\n\n| [F] level | XSL `Tipo` | Context added |\n|---|---|---|\n| Document | — not produced | — |\n| Document component (main text, annexes, tables, justification) | — **not produced** | — |\n| Basic unit hierarchy | `PRT, LIV, TIT, SBT, CAP, SEC, SSC` | Ementa + `NomeAgrupador` of the unit and its ancestors |\n| Basic unit | `ART` | Ementa + enclosing `NomeAgrupador`s |\n| Basic unit component | `CPT`, `PAR` | Ementa + enclosing `NomeAgrupador`s |\n| Enumeration | `INC, ALI, ITE` | Ementa + article label + text of the parent caput/§/inciso/alínea (no grouping names) |\n\nCoverage of the [F] strategies:\n\n- **Hierarchical Chunks — partial.** Four of the five evaluated levels are produced. Missing or\n different:\n - no document-component chunks;\n - the document **title (Epígrafe)** is not in the text (only the filename appears in `Rotulo`);\n - groupings contribute only their name (`NomeAgrupador`), not their label (\"CAPÍTULO I\");\n - enumeration chunks get the parent text instead of the grouping names.\n- **Core Chunks + Full Context — covered** (`Tipo == \"ART\"`), with the same title/label limits and\n no non-normative components (for statutes that means annexes and tables).\n- **Core Chunks + Metadata — not directly.** Needs an XSL variant that drops the `NomeAgrupador` loop\n in the `ART` block, or post-processing that keeps only the ementa part of the prefix.\n- **Core Chunks + No Context — derivable** by stripping the `[ ... ] ` prefix (breaks if an ementa\n contains `]`).\n\nTo match [F]'s context exactly: add `//Epigrafe` next to `$escopo`, and join each ancestor's\n`Rotulo` with its `NomeAgrupador`.\n\n## 3. What [L] proposes\n\n[L] does not compare several segmentation schemes. It proposes one and compares it against a flat\nbaseline in a qualitative RAG case study on the Brazilian Constitution (8 questions,\ntext-embedding-3-large at 256 dimensions, gpt-4-turbo-preview, chunk relevance graded\nessential / complementary / unnecessary).\n\n1. **Flat chunking by article** — \"traditional method of uniform fragments\"; 276 chunks for the\n Constitution.\n2. **Multi-layered chunking** (§4.1) — the six levels listed in §1 above; 2,954 chunks for the\n Constitution.\n3. **Semantic chunking** (semchunk-style recursive splitting) — mentioned and criticised for\n flattening the hierarchy; not evaluated. Footnote 2 also mentions averaging the embeddings of\n semantic chunks for texts longer than the model's token limit.\n\nDetails that matter here:\n\n- **Context enrichment in [L] is limited to enumerations:** incisos, alíneas and itens are embedded\n with the text of their ancestors up to the caput or paragraph (footnote 7:\n \"[A República Federativa … tem como fundamentos:] dignidade da pessoa humana\"). Prepending title,\n ementa or grouping names is new in [F].\n- **The XSL is most likely [L]'s implementation.** Its enumeration context matches footnote 7, and\n its `Rotulo` format matches the chunk labels in [L]'s appendix (\"Art. 29., caput, Inciso X\",\n \"TÍTULO IV, CAPÍTULO II, Seção V, Subseção I\"). The ementa + `NomeAgrupador` prefix looks like a\n later addition.\n- The worked example in [L] §4.1 uses other level names and counts incisos under the\n article-component level, which is inconsistent with the layer list.\n- No document-level or main-text chunk ever appears among the retrieved chunks, so the experiment\n apparently used the four levels the XSL produces.\n- **Retrieval-side filtering (§4.2):** 2,500-token budget; drop chunks whose similarity is more than\n 25% below the top hit; drop a chunk whose text is already covered by a higher-scored chunk (e.g.\n skip \"Art. 5, § 1, I\" if \"Art. 5, § 1\" was retrieved); keep at least 7 chunks.\n\n## 4. Constraints of this experiment\n\n- The article-level \"uniform fragments\" segmentation is the baseline.\n- Gold-answer references in the QA document go down to the enumeration level, so any hierarchical\n strategy must reach inciso / alínea / item.\n- The embedding budget is limited, and it must also cover sweeps over the number of chunks, the\n generator LLM and the embedding model, so the number of strategies should be minimal.\n\nCorpus facts (from `lexml/`, excluding `Alteracao` content):\n\n| | `articulados` (468 XML = 225 main + 243 annex files) | `nao_articulados` (235 XML) |\n|---|---:|---:|\n| Artigo | 19,393 (of which 2,231 in annex files) | 0 |\n| Caput | 19,393 | 0 |\n| Parágrafo | 21,620 | 0 |\n| Inciso | 20,703 | 0 |\n| Alínea | 5,349 | 0 |\n| Item | 2,148 | 0 |\n| Groupings (Parte … Subseção) | 5,278 | — |\n| Agrupamento / Bloco / `p` | — | 2,675 / 1,306 / 23,284 |\n| Text characters | ≈ 23.7 M | ≈ 4.5 M |\n\nThe 225 main documents all have a `ProjetoNorma` root. The parser writes each annex to a **separate\nfile** (`.anexoN.xml`, root `Anexo` → `DocumentoArticulado` or `DocumentoGenerico`); annexes\nare not `` elements inside the main documents. By **content** they fall into three categories\n(correction added 2026-09-24; see §6, item 3):\n\n| Category | Root | Files | Articles | Examples |\n|---|---|---:|---:|---|\n| **A – has `Artigo`** | `DocumentoArticulado` | 8 | 1,111 | `decreto_lei_5452_19430501.anexo1` (CLT, 922 arts.), `decreto_9358_20180430.anexo1` |\n| | `DocumentoGenerico` | 4 | 1,120 | **`decreto_9580_20181122.anexo1` (RIR/2018)**, `decreto_5128_20040706.anexo1`, `mp_2228-1_20010906.anexo1` |\n| **B – dispositivos, no `Artigo`** | `DocumentoArticulado` | 18 | 0 | `decreto_9358_20180430.anexo2`, `decreto_8289_20140725.anexo1`, `in_rfb_1548_20150213.anexo11` |\n| | `DocumentoGenerico` | 32 | 0 | `in_rfb_1500_20141029.anexo8`, `in_rfb_1717_20170717.anexo1` |\n| **C – plain text / tables** | `DocumentoGenerico` | 181 | 0 | `ade_rfb_3_20240402.anexo1..3`, `in_rfb_1500_20141029.anexo1` |\n\nThe root element is therefore **not** a reliable signal: four `DocumentoGenerico` annexes (including\nthe RIR/2018, likely the most-cited source in the IRPF Q&A) contain articles nested in\n`PartePrincipal` → `Livro`/`Capitulo`/`Secao`/`Artigo`, while 18 `DocumentoArticulado` annexes contain\nonly orphan `Item`/`Alinea`/`Inciso`/`Paragrafo` elements directly under `Articulacao` (often with a\n`TituloDispositivo`). Orphan dispositivos also occur directly under `PartePrincipal` in\n`DocumentoGenerico` annexes.\n\n## 5. Recommended strategies\n\n| ID | Chunks indexed | Approx. statutory chunks | Question answered |\n|---|---|---:|---|\n| **S1 – Article** | `ART` | ≈ 19.4 k | Baseline |\n| **S2 – Article + ancestor-path sub-units** | `ART` + `CPT`/`PAR` + `INC`/`ALI`/`ITE` | ≈ 88 k | Does going down to the enumeration level help? (S1 vs S2) |\n| S3 – Full multi-layer (optional) | S2 + `PRT`/`LIV`/`TIT`/`SBT`/`CAP`/`SEC`/`SSC` | ≈ 94 k | Do grouping chunks add anything? (S2 vs S3) |\n\n**Measured (2026-09-24, first full run, `docs/20260924_184339_segmentation_results.md`):** S1 =\n26,252 chunks (19,393 articles, 647 of them split into parts, → 20,479 ART rows; + 1,522 DSP + 4,251\nTXT/TAB), S2 = 82,644, S3 = 87,947. S2/S3 are lower than estimated above because CPT is only emitted\nfor articles with paragraphs (plan Q5).\n\nIf only two strategies fit the budget, keep **S1 vs S2**. Grouping chunks are the ones most likely\nto exceed embedding input limits (up to ~3.8 k tokens in [L]'s tables) and to crowd the RAG context.\n\nNot included:\n\n- **Document and document-component levels:** whole documents exceed embedding limits and are\n useless as RAG context; [L] did not evaluate them either.\n- **\"Leaves only\"** (sub-article units without the article chunks): free to build from the S3\n embeddings, but every extra strategy multiplies the generation and nugget-evaluation grid.\n It would test whether whole-article vectors are needed next to the fine ones — a secondary question.\n- **Context-free chunks:** [F] already shows they hurt dense retrieval.\n\n### 5.1 How S1 and S2 differ\n\nS1 and S2 cover **the same text**: an `ART` chunk already holds the whole article down to every\nitem. What differs is the **unit the retriever can match and return**. Each chunk has one vector\nand is retrieved as a whole:\n\n| | S1 | S2 |\n|---|---|---|\n| What a vector represents | A whole article | An article, **or** one caput / § / inciso / alínea / item |\n| What reaches the LLM on a hit | Always the full article | The smallest unit that matched |\n| Specific questions | Diluted match; context full of unrelated provisions | Precise match; small context |\n| Broad questions | Good match | Still covered, since article chunks are kept |\n\nSo S2 is not more text, but more entry points into the same text. If a gold answer depends on one\ninciso, S1 can reach it only through the whole-article vector and delivers it mixed with everything\nelse; S2 can find and deliver exactly that inciso. Nugget evaluation should show this as better\nrecall of specific nuggets, or the same recall with less context.\n\n### 5.2 Composition of a sub-article chunk (no isolated items)\n\nA sub-article unit is **never embedded alone**. Every caput / § / inciso / alínea / item chunk is:\n\n> **own text + own descendants + the opening text of each ancestor (without their other children) + metadata**\n\nExample — Lei 9.250/1995, Art. 8 (`lexml/articulados/lei_9250_19951226.xml`), chunk\n`art8_cpt_inc2_ali2_ite10` (education-deduction limit):\n\n```\n[ | ]\nArt. 8º A base de cálculo do imposto devido no ano-calendário será a diferença entre as somas:\nII – das deduções relativas:\nb) a pagamentos de despesas com instrução do contribuinte e de seus dependentes, ... até o limite anual individual de:\n10. R$ 3.561,50 (...), a partir do ano-calendário de 2015\n```\n\n- **Included:** caput opening sentence, inciso II text, alínea b text, item 10.\n- **Excluded:** items 1–9 of alínea b, alíneas a and c–j, inciso I, §§ 1–4.\n- The chunk for alínea b itself contains its items 1–10 (its own descendants), but not alíneas a or c.\n\nThis is [L]'s footnote-7 rule, and the XSL already applies it to incisos, alíneas and itens.\n\n## 6. Implementation changes before running\n\n1. **One context template for every chunk type, so embeddings are computed once.** If an article\n chunk has the same text in S1, S2 and S3, embed the S3 set once per model and build S1/S2 by\n filtering on `Tipo`.\n - Metadata = **Epígrafe + Ementa** (the XSL currently adds only the ementa; add `//Epigrafe`).\n - **Drop `NomeAgrupador`** from the prefix ([F] found no clear gain, and it removes a dimension).\n - **Keep the ancestor-path context** on enumerations (§5.2).\n - Put the metadata in **every** strategy, including the baseline, so the comparison measures\n segmentation rather than the presence of context.\n2. **Add the caput to paragraph-level chunks.** *(Reversed on 2026-10-05, caput plan D-A/D-B: the\n S1–S3 paragraph chunks keep only the article label; the caput sentence moved to the S4/S2c\n variant, and this Art. 8, § 2 example is now the S4 rationale.)* For `PAR` chunks and incisos/alíneas/itens inside\n paragraphs, the XSL context is only `Art. Nº` + the paragraph text. In LexML the caput is a\n sibling of the paragraph, not its ancestor, but paragraphs often depend on it — e.g. Art. 8, § 2\n (\"O disposto na alínea a do inciso II:\"). Add the caput's opening sentence (its own `p` only,\n not its incisos). Cross-references such as \"alínea a do inciso II\" remain unresolved inside the\n chunk; [L] lists inter-article relationships as future work.\n3. **Segment annex files by content, not by root element** (categories in §4). The XSL processes\n annex files, but they carry no `Ementa`/`Epigrafe`, so `$escopo` is empty; category B yields\n `INC`/`ALI`/`ITE` rows with an empty article label and drops orphan `Paragrafo`s (paragraphs are only\n reached through `Caput`); category C yields no rows at all. Rules:\n 1. **Category A → statutory**, identical to the main documents in S1/S2/S3. Metadata = the\n **parent** document's Epígrafe + Ementa + the annex label.\n 2. **Category B → top-level dispositivo as the basic unit.** Each top-level `Item` / `Alinea` /\n `Inciso` / `Paragrafo` (with its `TituloDispositivo` and subtree) plays the role of an article:\n S1 indexes these units; S2 adds their descendants with the ancestor path (§5.2). Same metadata\n as rule 1.\n 3. **Category C → the non-statutory treatment** of item 4, fixed across strategies. Same metadata\n as rule 1.\n4. **Treat non-statutory documents identically in all strategies.** The `nao_articulados` files and\n category-C annexes have no `Artigo`, only `Agrupamento` / `Bloco` / `p` / `table`, so the article\n baseline does not apply. Use one fixed treatment — e.g. `Agrupamento`-level chunks with metadata,\n split by `p` above a token cap; one chunk per table, split by rows with the header repeated when\n too large — unchanged across S1–S3, so the comparison stays about statutory segmentation.\n5. **Implementation split** (recommended):\n - **Statutory (main documents, annex categories A and B): an amended copy of the XSL** in this\n repo's `scripts/`, leaving the original in `lexml-parser-projeto-lei` untouched. It keeps the\n link to [L]'s implementation. Parent-document metadata can be passed in without restructuring:\n `$sigla` and `$escopo` are already `xsl:param`s, and `run_segmentation_csv.py` already groups\n `.anexoN` files by family stem (it just passes no parameters yet).\n - **Non-statutory (`nao_articulados` and category-C annexes): separate Python code (lxml).**\n Token caps need the embedding model's tokenizer, which XSLT cannot count; splitting tables by\n rows with repeated headers is simple in Python and painful in XSLT; and `Agrupamento`/`Bloco`\n share no templates with the article logic.\n - **Token cap (decided 2026-09-24): 1,024 tokens** for every basic unit — non-statutory chunks\n and also `ART` (and the category-B top-level dispositivo units): articles above the cap\n (≈ 2–3 %) are split along their structure into parts that repeat the article label and caput\n sentence, so S1 indexes \"article or article part\". Cap, tokenizer and splitting rules are in\n `docs/20260924_123747_segmentation_implementation_plan.md` §2.6 and §5b.\n - **Both emit the same CSV schema** (`Tipo, Rotulo, Num_Inicio, Num_Final, Texto, urn`), including\n the XSL's nested interval numbering (`calculaPos`: a parent's interval encloses its\n descendants'), so containment de-duplication works uniformly: X covers Y when\n `Num_Inicio_X ≤ Num_Inicio_Y` and `Num_Final_Y ≤ Num_Final_X`.\n\n## 7. Retrieval and evaluation notes\n\n- **Raw k is not comparable across strategies.** Chunk sizes range from a ~40-token inciso to a\n ~3.8 k-token título, so \"top-10\" gives very different context sizes in S1 and S2/S3. Sweep a\n **token budget** instead of (or alongside) k.\n- **Apply containment de-duplication** ([L] §4.2): drop a chunk whose text is already covered by a\n higher-scored retrieved chunk. Otherwise S2/S3 top-k will often contain both `Art. X` and\n `Art. X, caput, Inciso Y`.\n- Without these two controls, part of any measured difference will come from context length and\n redundancy rather than from segmentation.\n","20260924_123747_segmentation_implementation_plan.md":"# Segmentation Implementation Plan\n\n**Generated:** 2026-09-24 12:37:47 (local time, from `date +%Y%m%d_%H%M%S`)\n**Implements:** `docs/20260923_193852_segmentation_strategies_for_rag_experiments.md` (referred to below\nas **the strategy doc**; section numbers like §6 point into it).\n**Deliverables:** everything goes into `scripts/segmentation/`; outputs go into `segmented/`.\n\nThe plan has five parts:\n\n1. an **amended copy of the XSL** for statutory documents and annex categories A/B (§3 below);\n2. a **Python segmenter for non-statutory content** (`nao_articulados`, annex category C, and loose\n text/tables in A/B annexes) (§5);\n3. an **annex router** that picks the segmenter from each annex's content (§4);\n4. an **oversize-article splitter** that enforces the 1,024-token cap on articles (§2.6, §5b);\n5. an orchestrator and a validator that tie them together (§6–§7).\n\n---\n\n## 0. Corpus facts checked for this plan (2026-09-24)\n\nThese were measured on `lexml/` while writing this plan. They add to the strategy doc §4 and affect\nthe design:\n\n| Finding | Where | Consequence |\n|---|---|---|\n| Annex categories by content: **A = 12, B = 50, C = 181** | `lexml/articulados/*.anexoN.xml` | Matches the strategy doc; the router rule in §4 reproduces it |\n| **32 of 50 category-B annexes and 4 of 12 category-A annexes also have loose `p`/`table`** next to the dispositivos (e.g. `in_srf_256_20021211.anexo2`: 138 dispositivos + 148 loose `p`/`table`; RIR `decreto_9580_20181122.anexo1`: a tax table before `LIVRO I`) | `PartePrincipal`/`Articulacao` children | The XSL alone would drop them. They get the non-statutory treatment (§5), in the same CSV as the XSL rows |\n| **≈ 420 tables inside dispositivos**: 137 inside `Artigo` (58 in main documents, 79 in annexes), the rest under orphan dispositivos of category-B annexes (direct parents: `Item` 308, `Inciso` 81, `Caput` 22, `Alinea` 9, …); `td` never holds `p` | e.g. `decreto_3000_19990326.xml` | The XSL reads only `p` text, so **table content (tax tables) is lost**. Fix X8 |\n| `TituloDispositivo` in 1,324 dispositivos (1,038 under `Artigo`) | statutory | Ignored by the XSL. Fix X4 |\n| Remissions and links are `span`/`Remissao` children of `p` | all | The XSL's `p/text()` (enumeration context, lines 182–183, 196) **drops the cited text** (\"arts. 7°\", \"Lei nº …\"). Fix X3 |\n| 15 of 224 main-document `Ementa`s start with `CÂMARA DOS DEPUTADOS Centro de Documentação e Informação `; `constituição_1988_19881005.xml` has no `Ementa`; longest ementa is 2,951 chars | main docs | Clean ementas in one place (Python, §2.3) and pass the metadata to the XSL as a parameter |\n| Non-statutory structure: `PartePrincipal` → `Agrupamento[@nome]` (`texto` 1,438, `assinatura` 392, `nota` 366, `epigrafe` 226, `ementa` 121, `preliminar` 53, …) and `AgrupamentoHierarquico` (section with `Rotulo`/`NomeAgrupador`, nesting depth ≤ 4); `Bloco` is an empty ordering marker; `p` elements are **PDF lines**, not paragraphs | `lexml/nao_articulados` | Units are `Agrupamento`s; split on line boundaries that end a sentence (§5.3) |\n| `Agrupamento` text length: median 290 chars, p90 3.8 k, p99 20.8 k, max 83 k | `nao_articulados` | A token cap with splitting is required |\n| `decreto_lei_58_19371210.anexo1` has a `Livro` but no `Artigo` or dispositivo | category C | Python treats groupings as section headings (§5.2) |\n| Environment: `saxonche` and `lxml` are installed; `tiktoken` and `transformers` are not | — | Install both for the reference tokenizer (§2.6); keep the tokenizer pluggable (§5.4) |\n| Element `id`s are **hierarchical**: every dispositivo's `id` is its parent dispositivo's `id` + `_…` (0 exceptions), e.g. `art8_cpt_inc2_ali2_ite10`; grouping ids likewise (`liv2_tit4_stt1_cap2_sec7`). This is the same fragment scheme the linker uses in `Remissao`/`span` hrefs (`…;7713!art7`, `…;12618!art3_par1`) | statutory | An id alone gives the article and the full dispositivo path; gold citations passed through `lexml-linker` can be matched to chunks by id prefix (§2.7) |\n| **Duplicate ids in 61 files** (≈ 1.4 k repeats: orphan `Item` 532 / `Alinea` 305 such as `ali1`, and 65 `Artigo`s, e.g. two `Art. 16.` = `art16` in `circ_bc_3432_20090203`) | statutory | `urn` is **not** unique; add a unique `chunk_id` and flag ambiguous ids (§2.7) |\n| **Orphan dispositivos also in 21 main documents** (e.g. `decreto_67542_19701112` 104, `decreto_50656_19610524` 57) | statutory main docs | `DSP` rows must be emitted in every document, not only in category-B annexes (X6 amended) |\n| Loose `p` under `PartePrincipal`/`Articulacao` have **no `id`** (0 of 1,809); every `table` has one | annexes | Python builds synthetic ids for loose-text units (§2.7) |\n| `Artigo` text length: p50 372, p90 1,605, p99 4,841, max 32,740 chars; 409 articles > 3,500 chars (≈ 1,024 tokens), 51 of them with a single leaf dispositivo > 3,500 chars | statutory | Split oversize articles (§2.6, §5b) |\n\n---\n\n## 1. Layout in `scripts/` and `segmented/`\n\n```\nscripts/segmentation/\n README.md how to run; pointer to this plan\n GeraCSVporArtigoPorAgrupador.xsl verbatim copy of the original (reference, never edited)\n segmenta_estatutario.xsl amended XSL (§3)\n common.py metadata extraction, CSV writer, numbering, tokenizer (§2)\n classify_annexes.py annex router (§4) → segmented/annex_manifest.csv\n run_xsl_segmentation.py Saxon driver, adapted from run_segmentation_csv.py (§3.3)\n segment_non_statutory.py lxml segmenter (§5)\n split_oversize.py splits ART/DSP rows above the token cap (§5b)\n segment_all.py orchestrator (§6)\n validate_segments.py checks + statistics report (§7)\n strategies.py S1/S2/S3 filters over the chunk table (§2.2)\n tests/ pytest + small XML fixtures copied from lexml/\n\nsegmented/\n annex_manifest.csv router decisions, one row per annex\n statutory/.csv XSL output (+ loose-content rows for A/B annexes)\n non_statutory/.csv Python output (nao_articulados + category C)\n */.prov.jsonl provenance sidecars for split / synthetic-id rows (§5b, §2.7)\n chunks_all.csv merged table fed to the embedding step, with provenance (§2.7)\n segmentation_report.{md,json} counts, lengths, oversize list, validation results\n```\n\nOne CSV per source XML, named after that XML file, keeps provenance simple and lets a single\ndocument be regenerated.\n\n---\n\n## 2. Shared conventions (both segmenters)\n\n### 2.1 CSV schema and `Tipo` vocabulary\n\nPer-file CSVs keep the XSL schema exactly: `Tipo, Rotulo, Num_Inicio, Num_Final, Texto, urn`. All\nfields are quoted, and inner quotes are doubled. `chunks_all.csv` adds trailing columns:\n`arquivo` (source XML), `segmentador` (`xsl` | `python`), `categoria` (`main` | `A` | `B` | `C` |\n`nao_articulado`), and the provenance columns of §2.7.\n\n| `Tipo` | Produced by | Meaning | New? |\n|---|---|---|---|\n| `ART` | XSL (+ `split_oversize.py`) | Article (whole subtree), or one part of an article above the token cap (§5b) | — |\n| `DSP` | XSL (+ `split_oversize.py`) | **Top-level orphan dispositivo**: a `Caput`/`Paragrafo`/`Inciso`/`Alinea`/`Item` with no dispositivo ancestor. Mostly in category-B annexes, but also in 21 main documents (§0). It is the article-equivalent unit of rule 3.2 | **new** |\n| `CPT`, `PAR`, `INC`, `ALI`, `ITE` | XSL | Sub-article units with ancestor path | — |\n| `PRT`, `LIV`, `TIT`, `SBT`, `CAP`, `SEC`, `SSC` | XSL | Groupings | — |\n| `TXT` | Python | Non-statutory text unit (an `Agrupamento`, or one split part of it) | **new** |\n| `TAB` | Python | A table, or a row-group part of one | **new** |\n\n### 2.2 Strategy filters (`strategies.py`)\n\n```\nNS = {TXT, TAB} # identical in every strategy (§6 item 4)\nS1 = {ART, DSP} ∪ NS\nS2 = S1 ∪ {CPT, PAR, INC, ALI, ITE}\nS3 = S2 ∪ {PRT, LIV, TIT, SBT, CAP, SEC, SSC}\n```\n\nEvery chunk has one text regardless of strategy, so S1 and S2 are filters over the S3 embeddings.\n\n### 2.3 Chunk text template and metadata\n\n```\nTexto = \"[ \" + METADADOS + \" ] \" + CAMINHO + CONTEUDO\n```\n\n- **`METADADOS`** is computed **once, in Python** (`common.metadata_for(xml_path)`), and passed to the\n XSL as a parameter, so both segmenters use the same rules:\n - main statutory document: `Epígrafe | Ementa`;\n - annex (any category): ` | | `. The annex label is\n `Anexo N` (from the `!anexoN` URN suffix) plus the annex's own title when there is one (the annex\n `Epigrafe` for `DocumentoArticulado`, or the first `PartePrincipal/p` if it starts with\n `ANEXO`);\n - non-statutory document: `` text (fallback: `campo` fields, then the\n URN), then ` | ` and `` (fallback: `campo[@nome=EMENTA|Ementa|ASSUNTO|Assunto]`).\n - Cleaning: normalize whitespace; strip a leading `CÂMARA DOS DEPUTADOS Centro de Documentação e\n Informação` and a repeated epígrafe at the start of the ementa; replace `[`/`]` inside metadata\n with `(`/`)` so the prefix stays parseable. Truncate the ementa in the prefix to\n `--ementa-max-tokens` (default 128; see open question Q2). A non-statutory ementa that is\n truncated also gets its own `TXT` chunk, so no text is lost.\n- **`CAMINHO`** (ancestor path, §5.2 of the strategy doc) applies to sub-article units only: for\n each ancestor dispositivo, its `Rotulo` + `TituloDispositivo` + its **own** `p` (not its other\n children). For units inside a `Paragrafo`, the caput's own `p` is inserted after the article label\n (strategy doc §6 item 2). No `NomeAgrupador` is included.\n- **`CONTEUDO`**: the unit's own `Rotulo`, `TituloDispositivo`, `p` and table text, then the same for\n all its descendants, in document order.\n- Table serialization (both segmenters): cells joined with ` | `, rows joined with ` ; `, prefixed by\n `Tabela:`; the header row(s) come first.\n\n### 2.4 Interval numbering\n\nBoth segmenters produce nested intervals that follow the XSL's `calculaPos` contract: a parent's\n`[Num_Inicio, Num_Final]` encloses its descendants' intervals, and siblings are disjoint.\n\n- The XSL keeps `calculaPos` unchanged (a regression test guards it, §7).\n- Python numbers by a DFS counter (`start = ++c` on entry, `end = ++c` on exit). Split parts are\n sibling intervals inside the unit's range.\n- When Python adds **loose-content rows to an A/B annex CSV**, its counter starts at\n `max(Num_Final of the XSL rows) + 1`, so the intervals never overlap within a file.\n- Split article parts (§5b) take the interval `[min Num_Inicio, max Num_Final]` of the dispositivos\n they contain, so parts are disjoint and still enclose their sub-unit rows. Pieces of a single leaf\n split inside itself share the leaf's interval.\n- Containment de-duplication at retrieval time compares intervals **only within the same `arquivo`**,\n and never treats two parts of the same split unit (same base `urn` before `_p`) as covering\n each other.\n\n### 2.5 `urn` column\n\nIt holds `!`, as the XSL already does. Annex URNs already contain\n`!anexoN`, which gives e.g. `urn:…;9580!anexo1!art1`, so consumers split on the **last** `!`. Python\nrows use the `id` of the `Agrupamento`/`table`; split parts get the suffix `_p` (e.g.\n`…!pp1_agr5_p2`). Split article parts (§5b) follow the same pattern (`…!art8_p2`).\nBecause the source has duplicate ids (§0), `urn` is **not** guaranteed to be unique. The unique key is\n`chunk_id` (§2.7). For retrieval evaluation, use the provenance columns of §2.7 rather than parsing\n`urn`.\n\n### 2.7 Provenance columns (for retrieval evaluation)\n\nEach chunk must be traceable back to its document, annex, groupings, article and dispositivo, and a\nsplit part must say exactly which dispositivos it holds. The 6-column per-file CSVs cannot carry all\nof that, so a Python **provenance step** (orchestrator step 6, §6) adds these columns to\n`chunks_all.csv`. It looks up each row's element in the XML through the `id` in `urn`, or through the\npart and piece bookkeeping of §5 and §5b.\n\n| Column | Content | Example |\n|---|---|---|\n| `chunk_id` | Unique key: `#` | `lei_9250_19951226#412` |\n| `doc_urn` | URN of the **main** document (for an annex, the parent's URN) | `urn:lex:br:federal:lei:1995-12-26;9250` |\n| `anexo_urn` | Annex URN, empty for main documents | `urn:lex:br:federal:decreto:2018-11-22;9580!anexo1` |\n| `nivel` | Hierarchy level of the unit: `ART`, `DSP`, `CPT`, `PAR`, `INC`, `ALI`, `ITE`, `PRT`…`SSC`, `TXT`, `TAB` | `ITE` |\n| `unidade_id` | LexML `id` of the unit, with **no** part suffix (for a part, the article's id) | `art8_cpt_inc2_ali2_ite10` |\n| `artigo_id` | `id` of the enclosing article or `DSP` (empty for groupings and non-statutory rows) | `art8` |\n| `agrupadores_ids` | Ids of the enclosing groupings, outermost first, `;`-separated | `cap3` |\n| `agrupadores_rotulos` | Their labels + names | `CAPÍTULO III – DA DECLARAÇÃO DE RENDIMENTOS` |\n| `citacao` | Citation-style path | `Art. 8º, caput, II, b, 10` |\n| `parte`, `n_partes` | `k`, `n` for split units; `1`, `1` otherwise | `2`, `4` |\n| `cobre_ids` | Ids of the **maximal dispositivos wholly contained** in the chunk, `;`-separated. For an unsplit unit this is `unidade_id`; for an article part, the packed units (e.g. `art6_par3;art6_par4;art6_par5`, or `art6_cpt_inc20;…;art6_cpt_inc35` after descending). Descendants are implied by id prefix | `art6_par3;art6_par4` |\n| `parcial_ids` | Ids of dispositivos that are only **partly** in the chunk: a leaf split within itself (§5b step 4), plus the article and caput whose labels and sentence are repeated in `HEAD` but whose other children are in other parts | `art6;art6_cpt` |\n| `id_ambiguo` | `1` if `unidade_id` (or any id in `cobre_ids`) occurs more than once in the file | `0` |\n\nNon-statutory rows:\n- `unidade_id` = the `Agrupamento` or `table` id;\n- loose text runs, which have no id in the XML, get a synthetic id `_p-`,\n built from the 1-based positions of their `p` children (e.g. `anexo8_pp_p3-p7`);\n- `cobre_ids` = `unidade_id`; the `agrupadores_*` columns come from the `AgrupamentoHierarquico`\n path.\n\n**How the evaluation uses it** (the matching itself belongs to the evaluation code, not to this\nplan). A gold citation resolved to `doc_urn!fragment` (e.g. with `lexml-linker`, which uses the same\nid scheme) is **fully hit** by a chunk when some id in `cobre_ids` equals the fragment or is its\nancestor (id prefix up to a `_` boundary), and **partly hit** through `parcial_ids`. Coarser levels\ncome from the same columns: document (`doc_urn`), annex (`anexo_urn`), grouping\n(`agrupadores_ids`), and article (`artigo_id`).\nRows with `id_ambiguo = 1` are reported separately, since a match on them is not unique.\n\n**Known caveat for evaluation:** a gold citation such as \"art. 35 do RIR/2018\" may resolve to\n`…;9580!art35`, but the article lives in `…;9580!anexo1`. The decree's own articles and the annex's\narticles share `doc_urn`, and only `anexo_urn` tells them apart. The evaluation code must map these\ncitations to the annex (keep a small table of \"regulamento aprovado pelo decreto\" cases).\n\n### 2.6 Token cap: **1,024 tokens** (decided 2026-09-24)\n\nEmbedding models to be swept, with their input limits (checked 2026-09-24 on the model cards / API\ndocs):\n\n| Model | Max input (tokens) | Tokenizer | Notes |\n|---|---:|---|---|\n| `text-embedding-3-small` (OpenAI) | 8,192 | `cl100k_base` | API; over-limit input is rejected |\n| `gemini-embedding-2` (Google) | 8,192 | Gemini (count via API `countTokens`) | API; over-limit input is silently truncated |\n| `Qwen/Qwen3-Embedding-4B` | 32 k | Qwen | 2,560 dims (32–2,560 selectable) |\n| `ufca-llms/jua-4B-mixed` | 32 k inherited; model card example uses `max_length=8192` | Qwen (fine-tuned from Qwen3-Embedding-4B) | Training length not stated in the paper (arXiv 2605.04005) |\n| `infly/inf-retriever-v1` | 32,768 | Qwen2 (base: gte-Qwen2-7B-instruct) | 7B, 3,584 dims |\n\nThe binding model limit is therefore 8,192 tokens, but the cap is set well below it, as a\n**granularity** choice: non-statutory and oversize chunks compete with statutory chunks in the same\nindex and the same RAG context budget, so they should have the size of a typical article, not of a\nwhole opinion. Reference points (text chars, ≈ 3.5–4 chars/token for Portuguese): `Artigo` p50 372,\np90 1,605, p99 4,841, max 32,740 chars; 1,024 tokens ≈ article p97.\n\nRules:\n\n1. **Every chunk that a strategy indexes as its basic unit must be ≤ 1,024 tokens**, counted on the\n **full** `Texto` (metadata prefix and path included): `TXT`, `TAB` (§5.3) **and `ART`/`DSP`**,\n which are split into parts when above the cap (§5b). Expected: ≈ 400–600 of the 19.4 k articles\n (2–3 %) are split; ≈ 50 of them have a single dispositivo (usually a table) that is over the cap\n by itself and needs a within-leaf split.\n2. **Reference tokenizer = the per-text maximum over `tiktoken:cl100k_base` and\n `hf:Qwen/Qwen3-Embedding-4B`** (`--tokenizer max:tiktoken:cl100k_base,hf:Qwen/Qwen3-Embedding-4B`).\n The Qwen tokenizer covers the three Qwen-based models. Gemini cannot be counted locally at corpus\n scale: during step 7 (§8) count a random sample of ≈ 500 chunks with `countTokens` and confirm\n Gemini ≤ the reference count (with 8,192 as the real limit, a small excess would not truncate\n anything, but it is reported).\n3. One segmentation run, with this cap and tokenizer, serves **all** embedding models, so every model\n embeds exactly the same chunk set.\n\nDependencies to add: `tiktoken`, `transformers` (tokenizer only, no model weights).\n\n---\n\n## 3. XSL changes (`scripts/segmentation/segmenta_estatutario.xsl`)\n\nStep 1 is a **verbatim copy** of `../lexml-parser-projeto-lei/scripts/GeraCSVporArtigoPorAgrupador.xsl`,\ncommitted on its own so that later diffs show only the amendments. Line numbers below refer to the\noriginal.\n\n### 3.1 Amendments\n\n| # | Change | Original lines | Strategy doc |\n|---|---|---|---|\n| **X1** | New param `metadados` (full prefix, from Python). When `metadados` is empty, fall back to `normalize-space(//Epigrafe) \\|\\| ' \\| ' \\|\\| normalize-space(//Ementa)`, for standalone use. `sigla` stays. | 14–15 | §6.1 |\n| **X2** | Remove every `ancestor::*/NomeAgrupador` / `ancestor-or-self::*/NomeAgrupador` loop from the context of `CPT`, `PAR`, `ART` and the groupings. The prefix becomes `[ $metadados ]` for every `Tipo`. | 67, 78, 89, 99…159 | §6.1 |\n| **X3** | Replace the six hand-written enumeration-context expressions with **one function** `lx:caminho($n)`. It walks `$n/ancestor::*[self::Artigo or self::Caput or self::Paragrafo or self::Inciso or self::Alinea or self::Item]` in document order and emits each ancestor's `Rotulo`, `TituloDispositivo` and `string()` of its **direct** `p` children. Use `string(p)`, never `p/text()`, so `span`/`Remissao` text is kept (bug at 182–183, 196). | 168–171, 181–184, 194–197 | §5.2 |\n| **X3b** | In `lx:caminho`, when `$n` has a `Paragrafo` ancestor, insert `../Caput/p` (own `p` only) right after the article `Rotulo`. This applies to `PAR` rows too, whose context today is only the ementa. *Superseded by `docs/20261005_184116_*` (D-A): X3b is now the `caput_em_paragrafo=frase` option; the default `nao` writes no caput text.* | 73–82 + X3 | §6.2 |\n| **X4** | Replace the per-type content expressions (`descendant::p`, `descendant::p//text()\\|descendant::Rotulo`, …) with **one function** `lx:texto($n)`: `$n`'s own `Rotulo`, `TituloDispositivo`, `p`, table text, then the same for every descendant, in document order. Groupings include their **own** `Rotulo` + `NomeAgrupador` (today `descendant::` skips the grouping's own label, which only reaches the text through the context loop removed by X2). `CPT`/`PAR` content gains the inciso/alínea labels that `descendant::p` drops today. | 65, 76, 87, 97…157, 167, 180, 193 | §6.1 |\n| **X5** | Iterate `//Caput[parent::Artigo]` and `//Paragrafo[not(ancestor::Alteracao)]` independently, so a `Paragrafo` outside an `Artigo` (category B) gets a row and the nested loop no longer decides coverage. **Skip the `CPT` row when the article has no `Paragrafo`**, because its text would duplicate the `ART` row (see Q5). | 62–83 | §6.2, §6.3.2 |\n| **X6** | In **every** document (category-B annexes, but also the 21 main documents and any A annex that have orphan dispositivos, §0): emit a **`DSP`** row for each `Caput`/`Paragrafo`/`Inciso`/`Alinea`/`Item` that has no dispositivo ancestor (not in `Alteracao`), with content `lx:texto(.)`, and treat it as the root of `lx:caminho` for its descendants. `Rotulo` column: `sigla, ` (e.g. `in_rfb_1717_20170717.anexo1, Item 3`). Descendant `INC`/`ALI`/`ITE`/`PAR` labels drop the empty `Art.` part. | new | §6.3.2 |\n| **X7** | Build the `Rotulo` column in one `lx:rotulo($n)` function, which also fixes: the `ancestor::Subitulo` typo (135, 145, 155); the `caput, , Inciso` double comma in `ITE` (191); and `substring-before(Rotulo, ' –')` / `(Rotulo, ')')` / `(Rotulo, '.')`, which return `''` when the label uses `-`, `—` or no separator (replace with `replace(Rotulo, '^\\s*([^\\s–—\\-).]+).*$', '$1')`). | 105–202 | — |\n| **X8** | Serialize `table` descendants of a dispositivo into the text (format in §2.3), both as own content and as descendant content. Tables inside `Alteracao` follow the text: they are included in the text but get no rows. | new | — |\n| **X9** | Pass all `Rotulo` column values through the `escape` template (today the label is written between raw quotes). | 63, 74, 85, … | — |\n| **X10** | Performance: `calculaPos` counts `preceding::` nodes for every row (O(n²)). Time it on the largest files (`decreto_lei_5452_19430501.anexo1`, `decreto_9580_20181122.anexo1`, `decreto_3000_19990326`). Only if a file takes more than about 60 s, precompute positions with an `xsl:key`/accumulator that yields **identical** numbers (the regression test must still pass). | 53–58 | — |\n\nOut of scope for the XSL (kept as is): `Alteracao` content gets no rows of its own; the main-document\n`Preambulo`/`ParteFinal` are not segmented. The XSL always emits whole `ART`/`DSP` rows (it cannot\ncount tokens); rows above the 1,024-token cap are replaced by parts in a Python post-processing step\n(§5b).\n\n### 3.2 Worked target (acceptance fixture)\n\nIn `lei_9250_19951226.xml`, the `ITE` row for `art8_cpt_inc2_ali2_ite10` must equal the strategy\ndoc §5.2 example: `[ LEI Nº 9.250, … | Altera a Legislação … ] Art. 8º A base de cálculo … somas: II\n– das deduções relativas: b) a pagamentos de despesas com instrução … até o limite anual individual\nde: 10. R$ 3.561,50 …`. In the same file, `art8_par2` (`PAR`) must contain `Art. 8º`, the caput\nsentence, and then `§ 2º O disposto na alínea a do inciso II: …`.\n\n> **Superseded (2026-10-05, `docs/20261005_184116_*` D-A):** the base `art8_par2` row is now\n> `Art. 8º § 2º O disposto na alínea a do inciso II: …` (no caput sentence); the text above is its\n> `caput` variant (S4/S2c), produced with `caput_em_paragrafo=frase`. The `ITE` target is unchanged.\n\n### 3.3 Driver (`run_xsl_segmentation.py`)\n\nAdapted from `../lexml-parser-projeto-lei/scripts/run_segmentation_csv.py`, keeping its Saxon\nsetup, `is_lexml`, and report writing. Changes:\n\n- It takes the **job list** from the orchestrator (`xml_path`, `out_csv`, `metadados`)\n instead of globbing a folder. It passes the parameters with\n `executable.set_parameter(name, proc.make_string_value(v))` and resets them per file.\n- It writes one CSV per XML into `segmented/statutory/` and returns per-file `rows`,\n `max_num_final` (used for the loose-content offset, §2.4), duration and errors.\n- The stylesheet is compiled once, and `--jobs N` can use a process pool (one Saxon processor per\n worker).\n\n---\n\n## 4. Annex router (`classify_annexes.py`)\n\nIt is the only place that decides which segmenter handles an annex.\n\n**Input:** `lexml/articulados/*.anexo*.xml`. **Output:** `segmented/annex_manifest.csv` with\n`arquivo, familia, pai, raiz, categoria, n_artigos, n_dispositivos_topo, n_soltos (p/table), segmentadores, metadados`.\n\n**Classification rule** (elements inside `Alteracao` are ignored):\n\n```\nif any Artigo → A (XSL)\nelif any Item|Alinea|Inciso|Paragrafo|Caput → B (XSL; top-level dispositivos → DSP)\nelse → C (Python, full document)\nand for A and B: if Articulacao/PartePrincipal/ParteInicial-Preambulo holds\n direct p or table children → also Python, loose-content mode\n```\n\n- The root element (`DocumentoArticulado` vs `DocumentoGenerico`) is recorded but **not used** to\n decide (strategy doc §4).\n- **Parent resolution:** the family stem (`ANEXO_RE` from the original driver) gives `.xml` in\n `lexml/articulados/`. If that file is missing, the router strips `!anexoN` from the annex URN and\n looks for a main document with that `Identificacao/@URN`, first in `articulados/` and then in\n `nao_articulados/`. Unresolved parents are listed in the report, and the annex keeps only its own\n label as metadata.\n- **Self-check:** the run fails loudly if the category counts differ from **A = 12 / B = 50 /\n C = 181** without the `--allow-count-change` flag. This catches silent changes after a re-parse.\n- It also exposes `classify(path) -> AnnexDecision` for the orchestrator and the tests.\n\n---\n\n## 5. Non-statutory segmenter (`segment_non_statutory.py`, lxml)\n\n### 5.1 Modes\n\n- `--mode document`: a whole `nao_articulados` file or a category-C annex.\n- `--mode loose --offset K --append `: only the direct `p`/`table` children of\n `Articulacao`/`PartePrincipal` (and an annex `Preambulo`) of an A/B annex, appended to the XSL CSV\n with numbering starting at `K`.\n\n### 5.2 Units\n\n| Source | Unit → `Tipo` |\n|---|---|\n| `Agrupamento[@nome in (texto, nota, preambulo, formulaPromulgacao, tituloAnexo)]` | `TXT` (split if needed) |\n| `Agrupamento[@nome = ementa]` | in the prefix; also its own `TXT` if truncated there (§2.3) |\n| `Agrupamento[@nome in (epigrafe)]` | prefix only |\n| `Agrupamento[@nome in (assinatura, localDataFecho, preliminar)]` | dropped (signatures, dates, NUP/INTERESSADOS header lines); listed in the report (see Q4) |\n| `table` (anywhere) | `TAB`, taken out of the surrounding text; the `p` right before it becomes its caption when it is shorter than 200 chars and does not end with `.` |\n| `AgrupamentoHierarquico`, and `Livro`/`Capitulo`/… with no articles | no row of its own; its `Rotulo` + `NomeAgrupador` go into a heading line that starts each contained unit's `CONTEUDO` (non-statutory treatment is fixed across S1–S3, so this does not bias the comparison) |\n| Runs of loose `p` in category C / loose mode | consecutive `p`s between tables or dispositivos form one `TXT` unit |\n| `Bloco` | ignored (empty ordering marker) |\n\n### 5.3 Splitting to the token cap\n\n- Cap = `--max-tokens` (**1,024**, §2.6), counted on the **full** `Texto`, prefix included, with the\n reference tokenizer.\n- **Text:** join `p` lines with spaces. If the unit is over the cap, cut it greedily at the last line\n boundary that ends with `.`, `;`, `:` or a paragraph number such as `12.`, keeping each part under\n the cap. If no such boundary exists, cut at a line boundary, then at a word boundary. No overlap\n (see Q3). Each part is a `TXT` row (`Rotulo` gets `, parte k/n`).\n- **Tables:** header = the first row, plus the second when the first is a single spanning title\n (`colspan` = column count). If the table is over the cap, pack consecutive rows into parts and\n repeat caption + header in every part.\n- **Oversize after splitting** (a single line or row above the cap) is kept, flagged, and counted in\n the report.\n\n### 5.4 Tokenizer\n\n`common.Tokenizer` accepts `chars:4` (≈ chars / 4, no dependency; for quick tests only),\n`hf:` (lazy `transformers` import, tokenizer files only), `tiktoken:`, and\n`max:,,…` (per-text maximum). The production default is the reference tokenizer of §2.6,\n`max:tiktoken:cl100k_base,hf:Qwen/Qwen3-Embedding-4B`. Token counts are cached per text, because the\nsame texts are measured again when packing parts.\n\n### 5.5 `Rotulo` column\n\n`, [, Tabela k][, parte i/n]`, where `sigla` is the file\nstem. Example: `urn_lex_br_federal_parecer_2010_1503, I, parte 2/3`.\n\n---\n\n## 5b. Oversize article splitting (`split_oversize.py`)\n\nThe XSL cannot count tokens, so it always writes whole `ART`/`DSP` rows. A Python post-processing\nstep replaces each such row whose `Texto` is above the cap (§2.6) with parts built **along the\nstructure**, so every part is a self-contained piece of the article.\n\n**Input:** a statutory CSV + its XML (the element is found through the `id` after the last `!` in\n`urn`). **Output:** the same CSV, where each oversize `ART`/`DSP` row is replaced in place by its parts.\nAll other rows are unchanged.\n\n**Algorithm** (greedy, in document order):\n\n1. The article's split units are its direct dispositivo children, in order: `Caput` (own `p` +\n descendants) and each `Paragrafo`. For a `DSP`, they are its direct child dispositivos.\n2. Pack consecutive units into a part while `Texto(part) ≤ cap`, where\n `Texto(part) = \"[ \" + METADADOS + \" ] \" + HEAD + units`, and `HEAD` is:\n - the article's `Rotulo` + `TituloDispositivo`;\n - plus the caput's own `p` when the part does not start with the caput. This is the same rule as\n X3b, so a part made of §§ 3–5 still reads \"Art. 8º § 3º …\".\n3. **A unit that is over the cap by itself** is replaced by its own children (incisos → alíneas →\n itens). These are packed the same way, with that unit's `CAMINHO` (ancestor path, §2.3) added to\n `HEAD`. For example, a part made of incisos XX–XXXV of the caput starts with\n \"Art. 6º \".\n4. **A leaf that is over the cap by itself** (no child dispositivos, ≈ 50 cases, mostly tables) is\n split within the leaf:\n - tables: by row groups with the caption and header repeated (as in §5.3);\n - text: at sentence boundaries, then at word boundaries;\n - every piece keeps `HEAD` + the leaf's path.\n5. Parts keep the `Tipo` (`ART`/`DSP`), so the strategy filters (§2.2) are unchanged: S1 indexes the\n parts instead of the whole article.\n\n**Columns of a part:**\n- `Rotulo` = the original label + `, parte k/n` (e.g. `decreto_9580_20181122.anexo1, Art. 6º, parte 2/4`);\n- `urn` = the original `urn` + `_p`;\n- `Num_Inicio`/`Num_Final` as in §2.4.\n\n**Provenance sidecar.** The 6-column CSV cannot hold the part contents, so `split_oversize.py` writes\n`.prov.jsonl` next to the CSV, with one record per part:\n`{urn, parte, n_partes, cobre_ids, parcial_ids}` (§2.7). `segment_non_statutory.py` writes the same\nkind of sidecar for split `TXT`/`TAB` units and for synthetic loose-text ids. The provenance step\n(§6 step 6) reads these files; a row without a sidecar record is an unsplit unit whose `cobre_ids`\nis its own id.\n\nThe report lists each split article with its original token count, number of parts, and whether a\nwithin-leaf split was needed.\n\n**Consistency with the XSL text rules.** `split_oversize.py` rebuilds text from the XML, so\n`common.py` carries Python versions of `lx:texto`, `lx:caminho` and table serialization (§2.3). A\n**parity test** runs both implementations on every article that is *not* split and requires the\nPython text to equal the XSL `ART` text. This keeps the two implementations from drifting apart.\n\n**Scope.** Only the basic units (`ART`, `DSP`, `TXT`, `TAB`) are bounded by the cap. Sub-article rows\n(`CPT`, `PAR`, `INC`, `ALI`, `ITE`) and groupings (`PRT`…`SSC`, S3 only) are not split. Their\nover-cap counts are reported (see Q7).\n\n---\n\n## 6. Orchestrator (`segment_all.py`)\n\n```\n1. manifest = classify_annexes(lexml/articulados) # §4\n2. jobs_xsl = main docs + A + B, each with metadados = common.metadata_for(file)\n3. run_xsl_segmentation(jobs_xsl) → segmented/statutory/*.csv\n3b. split_oversize on every statutory CSV (ART/DSP > 1,024 tokens → parts, §5b)\n4. for A/B annexes with loose content:\n segment_non_statutory --mode loose --offset max_num_final+1 --append …\n5. segment_non_statutory --mode document on lexml/nao_articulados/* and category C\n → segmented/non_statutory/*.csv\n6. merge all CSVs into segmented/chunks_all.csv (+ arquivo, segmentador, categoria)\n and add the provenance columns (§2.7) from the XML + the .prov.jsonl sidecars\n7. validate_segments → segmented/segmentation_report.{md,json}; non-zero exit on failure\n```\n\nFlags: `--only ` to regenerate selected files, `--overwrite`, `--jobs`, `--max-tokens`\n(default 1,024), `--tokenizer` (default: the reference tokenizer of §2.6), `--ementa-max-tokens`. The command line and the flag values are written into the\nreport, so every chunk set can be traced back to its parameters.\n\n---\n\n## 7. Validation (`validate_segments.py` + `tests/`)\n\n**Structural checks (every run):**\n\n- every CSV parses with 6 columns (`chunks_all.csv`: 6 + 3 + the §2.7 columns); no empty `Texto`;\n `chunk_id` is unique; `urn` is unique except where `id_ambiguo = 1`;\n- **provenance:** every `unidade_id` and every id in `cobre_ids`/`parcial_ids` exists in the source\n XML (synthetic loose-text ids resolve to their `p` run); `artigo_id` and `agrupadores_ids` agree\n with the XML ancestors; the `cobre_ids` of an article's parts add up to all its dispositivos\n exactly once, and no part's `cobre_ids` overlap another's;\n- within each `arquivo`, all intervals are nested or disjoint, and each `INC`/`ALI`/`ITE`/`PAR`\n interval lies inside its `ART`/`DSP` interval;\n- **coverage:** one `ART` (or one complete set of parts `parte 1..n`) per `Artigo` outside\n `Alteracao`; the same for `DSP` per top-level dispositivo in B annexes; every non-dropped\n `Agrupamento` and `table` appears in at least one row;\n- **cap:** every `ART`, `DSP`, `TXT` and `TAB` row is ≤ 1,024 reference tokens. The only exception is a\n single sentence, table row or word that cannot be cut further; these are listed and must be under\n 8,192;\n- **split completeness:** the parts of a split article together contain every dispositivo of that\n article exactly once (leaf pieces count as one);\n- **text coverage:** for each file, the characters of the S1 chunk bodies (prefix removed) are at\n least 98 % of the document's text characters outside `Alteracao`, the preamble and the dropped\n `Agrupamento`s. This catches dropped tables or labels.\n\n**Statistics in the report:** rows per `Tipo`, per strategy (expected S1 ≈ 19.4 k + DSP + NS,\nS2 ≈ 88 k, S3 ≈ 94 k; strategy doc §5; S1 grows by the extra parts of split articles), per\ncategory; token-length percentiles per `Tipo` and per tokenizer; the split articles (§5b); the\nover-cap counts of the sub-article and grouping rows (Q7); the Gemini `countTokens` sample check\n(§2.6).\n\n**Tests (pytest, fixtures copied from `lexml/`):**\n\n| Test | Fixture |\n|---|---|\n| XSL regression: for the unchanged `Tipo`s, the `(Tipo, Num_Inicio, Num_Final, urn)` sets of the original and the amended XSL are identical, except for the `CPT` rows removed by X5 | `lei_9250_19951226.xml`, `decreto_9580_20181122.anexo1.xml` |\n| §3.2 worked target (`ITE` art8…ite10, `PAR` art8_par2) | `lei_9250_19951226.xml` |\n| Remission text kept in the enumeration context (X3) | a `p` with `span` inside an inciso of `lei_9250` |\n| Table inside a dispositivo is serialized (X8) | `decreto_3000_19990326.xml` (one article with a table) |\n| Orphan dispositivos: `DSP` rows, orphan `Paragrafo` gets a row, no empty `Art.` label | `in_rfb_1548_20150213.anexo11.xml`, `decreto_8289_20140725.anexo1.xml` |\n| Router categories + loose-content flag | one file per category, plus `in_srf_256_20021211.anexo2.xml` |\n| Non-statutory: epígrafe/ementa extraction, dropped agrupamentos, split respects the cap, table header repetition | `urn_lex_br_federal_parecer_2010_1503.xml`, `ade_rfb_3_20240402.anexo1.xml` |\n| Loose-mode offset keeps the intervals disjoint | `decreto_9580_20181122.anexo1.xml` |\n| Provenance: `cobre_ids`/`parcial_ids` of split parts; `id_ambiguo` on duplicated ids; `DSP` + provenance for orphan dispositivos in a main document; synthetic loose-text ids | a split article (as below), `circ_bc_3432_20090203.xml` (duplicate `art16`, orphan `par1u`), `decreto_67542_19701112.xml`, `in_rfb_1500_20141029.anexo8.xml` |\n| Python/XSL text parity on non-split articles (§5b) | `lei_9250_19951226.xml`, `decreto_3000_19990326.xml` (tables) |\n| Article split: parts ≤ cap, caput sentence repeated in `HEAD`, descent into incisos, within-leaf table split with header repeated, disjoint part intervals, dispositivo coverage | the largest articles of `decreto_9580_20181122.anexo1.xml` and `decreto_3000_19990326.xml` (pick by length when building fixtures) |\n\n---\n\n## 8. Work order\n\n| Step | Content | Done when |\n|---|---|---|\n| 1 | Copy the XSL and the driver verbatim into `scripts/segmentation/`; run the original on the corpus into a scratch folder as the regression baseline | Commit \"verbatim copy\" |\n| 2 | Install `tiktoken` + `transformers`; `common.py` (metadata, CSV writer, reference tokenizer) + `classify_annexes.py` | Manifest reproduces A/B/C = 12/50/181; parents resolved |\n| 3 | XSL X1–X2, X4, X7, X9 (template, content and labels) | Regression + label tests pass |\n| 4 | XSL X3/X3b (ancestor path + caput for paragraphs) | §3.2 target test passes |\n| 5 | XSL X5, X6, X8 (orphan dispositivos → `DSP`, CPT rule, tables); X10 only if needed | Orphan-dispositivo and table tests pass |\n| 6 | `segment_non_statutory.py`, document mode, then loose mode | Non-statutory tests pass |\n| 6b | Python `texto`/`caminho` in `common.py` + `split_oversize.py` | Parity and split tests pass |\n| 7 | `segment_all.py` + `validate_segments.py`, full run; Gemini `countTokens` sample check | Report clean; counts near the strategy doc §5 estimates; no chunk over the cap except the listed uncuttable ones |\n| 8 | Dated note in `docs/` with the final counts and length distributions; update the strategy doc §4/§5 numbers if they differ | — |\n\n---\n\n## 9. Open questions (defaults used until decided)\n\n- **Q1 – Reference tokenizer and cap.** **Decided (2026-09-24):** 1,024 tokens, applied to\n `TXT`/`TAB` and to `ART`/`DSP` (articles above it are split, §5b); tokenizer = per-text maximum of\n `cl100k_base` and the Qwen3 tokenizer, checked against Gemini on a sample (§2.6).\n- **Q2 – Ementa length in the prefix.** Solução-de-consulta ementas can be long; a full ementa on\n every chunk would dominate short chunks. Default: truncate to 128 tokens in the prefix, and keep\n the full ementa as its own chunk.\n- **Q3 – Overlap between split parts.** Default: none (parts carry the same prefix and heading line).\n- **Q4 – Dropped `Agrupamento`s** (`assinatura`, `localDataFecho`, `preliminar`). `preliminar` holds\n the NUP/INTERESSADOS/ASSUNTO header lines; `ASSUNTO` is already reachable through the metadata\n fallback. Default: drop all three.\n- **Q5 – `CPT` for caput-only articles.** Default: not emitted, since it would duplicate `ART` in\n S2/S3. The regression test accounts for it.\n- **Q6 – Main-document `Preambulo`.** Default: not segmented (enacting formula, as in the original\n XSL). Annex preambles are segmented, because in category B they can hold substantive text (e.g.\n `decreto_9358_20180430.anexo2`).\n- **Q7 – Over-cap sub-article and grouping rows.** A `CPT`/`PAR` with many incisos, or a grouping in\n S3, can exceed 1,024 tokens. Only the largest ones can approach 8,192 (the longest article has\n ≈ 32.7 k chars), and the report flags any that do. Default: not split, because in S2\n their children are indexed as well, and the groupings belong only to the optional S3. The report\n counts them. If many exceed the cap, apply the §5b algorithm to them too (the parts would keep\n their own `Tipo`).\n","20260924_175304_segmentation_execution_log.md":"# Segmentation Implementation — Execution Log\n\n**Started:** 2026-09-24 17:53:04 (local time, from `date +%Y%m%d_%H%M%S`)\n**Executes:** `docs/20260924_123747_segmentation_implementation_plan.md` (referred to as **the plan**;\n§ numbers point into it).\n**Code:** `scripts/segmentation/` · **Outputs:** `segmented/`\n\n---\n\n## 0. Environment setup\n\n- `python3` 3.12.3; `saxonche` 13.0.0, `lxml` 6.1.1, `pandas` 3.0.3 and `pytest` 9.1.1 were already\n installed in the system `dist-packages`.\n- `pip install tiktoken transformers` failed first with PEP 668 (externally managed environment).\n `--break-system-packages` then failed as well: pip needed to upgrade the Debian-owned `rich`\n 13.7.1 (`uninstall-no-record-file`). I did not overwrite the system package.\n- `python3 -m venv` failed because `ensurepip` is missing (`python3.12-venv` is not installed).\n- **Solution:** a venv **without pip** that also sees the system site-packages, filled by the system\n pip through `--python`:\n\n ```bash\n python3 -m venv --system-site-packages --without-pip .venv\n pip --python .venv/bin/python install tiktoken transformers\n ```\n\n This installed `tiktoken` 0.14.0, `transformers` 5.17.0, `tokenizers` 0.23.2 and `huggingface_hub`\n 1.33.0. The `Qwen/Qwen3-Embedding-4B` tokenizer files download from the HF Hub without a token (no\n weights). `.venv/` is in `.gitignore`; the pins are in `scripts/segmentation/requirements.txt`.\n **Every command below uses `.venv/bin/python`.**\n\n## Step 1 — Verbatim copies and regression baseline\n\n- Copied `GeraCSVporArtigoPorAgrupador.xsl` and `run_segmentation_csv.py` unchanged from\n `../lexml-parser-projeto-lei/scripts/` (source commit `322b437`) into `scripts/segmentation/`.\n `diff -q` confirms they are identical. Work goes on branch `segmentation-implementation`, and the\n copies are committed alone (\"Verbatim copy …\", `5255a80`), so later diffs show only amendments.\n- **Finding:** the verbatim driver does not run on `saxonche` 13.0\n (`AttributeError: 'PyXslt30Processor' object has no attribute 'exception_occurred'`; since\n saxonche 12, errors are raised as `PySaxonApiError`). The copy stays untouched as a reference. The\n adapted driver `run_xsl_segmentation.py` (plan §3.3) was written right away (job list, per-file\n parameters, process pool with `spawn`, saxonche-13 API, `max_num_final` per file), and it also runs\n the baseline.\n- **Finding:** the first baseline run failed on 9 files with `field larger than field limit (131072)`\n when counting rows. Grouping rows (whole títulos) are longer than Python's default CSV field limit,\n so the driver now calls `csv.field_size_limit(sys.maxsize)`.\n- **Baseline** (original XSL, no parameters, `--jobs 16`): 468/468 files, **93,801 rows**, 31.1 s\n wall-clock, in the scratchpad (`baseline_orig/`). Slowest files: `decreto_9580_20181122.anexo1`\n 30.4 s, `lei_10406_20020110` 23.5 s, `decreto_3000_19990326` 23.4 s; everything is under the\n 60 s threshold of X10.\n\n## Step 2 — `common.py` and the annex router\n\n- `common.py`: LexML helpers (XPath `string()`/`normalize-space()` equivalents, so only XML\n whitespace is collapsed, as in the XSL); the Python mirror of the XSL text rules (`texto`,\n `caminho`, `tabela`, `rotulo`, and `xsl_row_elements`, which reproduces the XSL's row selection and\n order); `Positions` (calculaPos in one DFS: `start = 2·before − anc + 1`,\n `end = start + 2·desc + 1`); `metadata_for`; the pluggable `Tokenizer` (`chars:N`,\n `tiktoken:…`, `hf:…`, `max:…`, cached, batched); CSV/sidecar I/O.\n- **Metadata cleaning had to go beyond plan §2.3.** A survey of the 224 main-document ementas found\n Planalto/Câmara page furniture before the real ementa, besides the `CÂMARA DOS DEPUTADOS …` header\n already known: `Vide Recurso extraordinário nº 522897`, `Texto compilado`, `Texto original`,\n `Texto para impressão`, `Vigência`, `Exposição de Motivos`, `Convertida na Lei nº …`,\n `Produção de efeito`, `Sem eficácia`, `all_inclusiveRegulamentação`,\n `Revogado pelo Decreto nº 9.580, de 2018` (RIR/1999), `Publicado(a) no DOU de …`,\n `(Republicada no DOU …)`, and a page number `1 ` before a repeated epígrafe (5 laws).\n `clean_ementa` strips these with anchored patterns, repeatedly, together with the repeated\n epígrafe. After cleaning, every one of the 224 ementas starts with its real text (checked by\n listing those that do not start with a usual verb: only genuine ones such as \"Código de Processo\n Civil.\" remain). `constituição_1988` has no ementa, so its prefix is the epígrafe only.\n- **Non-statutory metadata** (235 files): epígrafe from `Agrupamento[@nome=epigrafe]` in 229 files.\n Fallbacks added for the 6 others, since no `campo` holds a title:\n - `solucao.consulta_2019-03-25_6007`: its only `ementa` group is really its title (\"Solução de\n Consulta Disit/SRRF06 nº 6007…\"), so it becomes the epígrafe and the ementa falls back to\n `campo Assunto`;\n - 5 `servico_2026_*` pages and `solucao.consulta_2009-03-09_15`: first line of `preliminar` (the\n page or document title);\n - `servico_2026_carne.leao`: first section heading. The URN fallback is no longer needed.\n\n Ementa: `Agrupamento[@nome=ementa]` in 121 files, `campo EMENTA`, else `campo ASSUNTO` (104\n soluções de consulta; repeated case-variant values are deduplicated). 5 files have no ementa at all\n (court decisions, `servico` pages).\n- **Router** (`classify_annexes.py`): **A = 12, B = 50, C = 181**, as expected (self-check passes).\n Roots: A = 8 `DocumentoArticulado` + 4 `DocumentoGenerico`, B = 18 + 32, C = 181\n `DocumentoGenerico`, matching the strategy doc §4. All 243 parents resolve through the family stem.\n Loose content: 4 A and 32 B annexes counting `Articulacao`/`PartePrincipal` only, which reproduces\n plan §0 exactly; **10 A and 46 B** once the annex `Preambulo` is counted (plan §5.1/Q6: annex\n preambles are segmented, e.g. the convênio clauses in `in_rfb_1548_20150213.anexo11`).\n Output: `segmented/annex_manifest.csv`.\n- **Deviation D1 — loose content in main documents.** Plan §4 routes loose `p`/`table` only for A/B\n annexes, but **27 main documents** also have them directly under `Articulacao`: 685 elements,\n ≈ 116 k chars. Examples: treaty texts in `decreto_67542_19701112` (184 elements, 42.6 k chars) and\n `decreto_50656_19610524`, the \"Tabela Progressiva Anual\" in `lei_10451_20020510`, and\n `circ_bc_3432_20090203`. The XSL would drop them, so loose mode runs on every statutory file that\n has them (main-document `Preambulo` still excluded, as in Q6).\n- Not segmented, as the plan says: an `Alteracao` directly under `Articulacao` in `lei_13043_20141113`\n (8.2 k chars of quoted amending text outside any article; \"Alteracao content gets no rows of its\n own\").\n\n## Steps 3–5 — Amended XSL (`segmenta_estatutario.xsl`, X1–X9)\n\nWritten as one pass over the verbatim copy, since X2–X7 all replace the same per-type blocks: one\n`linha` template, with `lx:csv` (X9), `lx:tabela` (X8), `lx:texto` (X4), `lx:caminho` (X3/X3b),\n`lx:rotulo`/`lx:curto` (X7), the `metadados` parameter with Epígrafe|Ementa fallback (X1/X2), CPT only\nwhen the article has a `Paragrafo` and PAR iterated independently (X5), and `DSP` for top-level\norphan dispositivos in every document (X6). `calculaPos` is verbatim. Notes:\n\n- Row order in the CSV: CPT, PAR, ART, DSP, PRT…SSC, INC, ALI, ITE.\n- All string fields are quoted. `Num_Inicio`/`Num_Final` stay unquoted because `calculaPos` is kept\n verbatim; CSV readers treat both the same way.\n- A top-level orphan dispositivo gets only its `DSP` row, not an `INC`/`PAR`/… row too, so S2 does\n not hold two copies of the same text (the same holds for articles: ART, never an \"article-level\" CPT\n duplicate).\n- `TituloDispositivo` always comes **before** `Rotulo` in the XML (1,324/1,324), so document order\n gives \" Art. 8º …\".\n- **X10 not needed:** with the amended XSL, the slowest files take 22 s (`decreto_9580…anexo1`) and\n 15 s (`decreto_3000`) under the process pool.\n- **Early parity check** (Python `xsl_row_elements` + `rotulo` + `Positions` + `row_text` against the\n XSL output, every column of every row) on `lei_9250`, `in_rfb_1548.anexo11`, `decreto_8289.anexo1`,\n `circ_bc_3432`, `decreto_3000`, `decreto_9580.anexo1`: **11,680 rows, 0 mismatches**.\n- §3.2 worked target reproduced: `ITE art8_cpt_inc2_ali2_ite10` = `[ LEI Nº 9.250, DE 26 DE DEZEMBRO\n DE 1995 | Altera a Legislação do Imposto de Renda das Pessoas Físicas e dá outras providências. ]\n Art. 8º A base de cálculo … somas: II – das deduções relativas: b) a pagamentos de despesas com\n instrução … 10. R$ 3.561,50 …`; `PAR art8_par2` = `… ] Art. 8º A base de cálculo … somas: § 2º O\n disposto na alínea a do inciso II: I – …`. Remission text is kept (`Art. 3º … de que tratam os\n arts. 7°, 8° e 12, da Lei n° 7.713 …`) and tables are serialized (`Tabela: BASE DE CÁLCULO EM R$ |\n ALÍQUOTA% | … ; até 900,00 | - | - ; …`).\n\n## Step 6 — Non-statutory segmenter (`segment_non_statutory.py`)\n\n- Document mode (235 `nao_articulados` + 181 category-C annexes) and loose mode (appended to the\n statutory CSV, numbering from `max Num_Final + 1`). Units, captions, splitting, `Rotulo` and ids\n follow plan §5. Every Python row gets a record in `<csv>.prov.jsonl`, not only split parts and\n synthetic ids (a superset of §5b), so the provenance step never has to re-derive Python rows.\n- **Split boundaries:** paragraph numbers (\"2.\", \"11.\") sit on lines of their own in the PDF-derived\n `p`s, so a preferred cut is *before* a bare paragraph-number line, or after a line ending in\n `.`/`;`/`:` that is not itself a bare number. Lines over the cap by themselves are cut at sentences,\n then at words. Example: parecer 1503, section II, parts start at \"5.\", \"6.\", …\n- `ul`/`li` lists (195 `ul` in `nao_articulados`) become one line per `li`, nested lists included.\n- **Annex title line is prefix-only.** Without this, the first `p` \"ANEXO I\" of a `DocumentoGenerico`\n annex (or its `tituloAnexo` group), which is already in the prefix as `Anexo 1 – ANEXO I`, became a\n useless chunk \"[ … Anexo 1 – ANEXO I ] ANEXO I\" (e.g. `ade_rfb_3_20240402.anexo1`, the RIR/2018\n \"ANEXO\" line). Small departure from §5.2, which lists `tituloAnexo` under `TXT`.\n- **Deviation D2 — long \"dropped\" Agrupamentos are kept.** Q4 drops `assinatura`, `localDataFecho`\n and `preliminar`. A survey found substantive text in some of them: `preliminar` holding a\n solução-de-consulta ementa (\"ASSUNTO: IRPF Aplicação em moeda estrangeira…\", 1,551 chars), court\n case headers (1.9 k chars), and `localDataFecho` holding case facts (\"O interessado protocolou…\").\n Flag `--keep-dropped-min-chars` (default 300) keeps those at least that long as TXT; **11** were\n kept, and 449 short ones were dropped (392 assinatura, 44 preliminar, 13 localDataFecho).\n `--keep-dropped-min-chars 0` restores the plain Q4 default.\n- **Heading-only groupings become a TXT unit.** Found by the text-coverage check:\n `decreto_lei_58_19371210.anexo1` ends with an empty `Livro` \"LIVRO AUXILIAR – N. 8\", whose text was\n lost. A grouping/`AgrupamentoHierarquico` with a heading but no contained unit now yields a TXT\n unit of its heading (24 corpus-wide).\n\n## Step 6b — Structural split of oversize ART/DSP (`split_oversize.py`)\n\n- Implemented as in §5b. The items of a unit are its direct children that carry text: dispositivos,\n and also `table`, `Alteracao`, `Pena`, `DispositivoGenerico`, whose text would otherwise be lost\n when an item is descended into. HEAD = `caminho` of the part's first item, which is exactly \"article\n label [+ caput sentence for paragraphs, X3b] + the opening of every descended unit\". Parts thus\n concatenate back to the article text without their heads.\n- Part interval = span of the whole counted items; pieces use their nearest counted ancestor. The\n sidecar also stores the unit's original interval (`intervalo_unidade`) for validation.\n- **Finding / deviation D3 — huge repeated HEAD.** The first full run left 133 over-cap parts, all\n in **CLT art. 670** (`decreto_lei_5452_19430501.anexo1`). Its caput sentence (the composition of\n the 24 Tribunais Regionais plus a list of amending laws) is ≈ 1.9 k tokens, and X3b repeats it before\n every paragraph, so the article shattered into 136 parts that were all over the cap. Rule added:\n a HEAD that alone takes more than half of the cap goes into part(s) of its own, cut at sentence\n boundaries, the first time it appears; in later parts it is truncated to a quarter of the cap\n (256 tokens + \"…\"). A first version truncated it everywhere, which lost text, e.g. a DSP's opening\n sentence appears only as HEAD (text coverage of `in_rfb_2060_20211213.anexo1` fell to 97.7 %);\n hence the \"first appearance in full\" rule. Art. 670 now has **7 parts, all ≤ 1,024**. 8 units use\n the truncated HEAD.\n\n## Step 7 — Orchestrator, validation, full run\n\n- `segment_all.py` runs steps 1–7 with process pools (`spawn`); `validate_segments.py` writes\n `segmented/segmentation_report.{md,json}`. `chunks_all.csv` = 6 + 3 + 14 provenance columns +\n 3 token columns (`n_tokens` = reference, `n_tokens_cl100k`, `n_tokens_qwen3`). The token columns\n are an addition, for the token-budget sweeps of strategy doc §7.\n- **Problem: workers stalled on the HF Hub.** In the first full run only 10 of 16 workers finished\n loading the Qwen tokenizer: each worker called `AutoTokenizer.from_pretrained`, which contacts the\n Hub unauthenticated and gets rate-limited. Moreover, `import transformers` alone takes ≈ 12 s wall\n (2.7 s CPU) on this WSL 9p filesystem. **Fix:** the `hf:` tokenizer now loads the cached\n `tokenizer.json` with the `tokenizers` library (`local_files_only` first, network only when not\n cached, transformers as a last fallback). Counts are **identical** to the transformers fast\n tokenizer on 3,000 RIR chunks (970 k tokens), and the load takes 2.3 s instead of ≈ 21 s.\n- **Problem: `--only` overwrote `run_info.json`** with the regenerated files only, so the validator\n lost the per-file \"dropped\"/\"annex title\" information and reported 450 false coverage failures.\n `--only` now merges its per-file results into the existing `run_info.json`.\n- **Validator fixes** (the data was right): split units sharing a duplicate id (two orphan `ali2`,\n two `art33`) are now grouped by occurrence (a unit starts at `parte = 1`). The dispositivo\n completeness check accepts an id covered m times when m elements of the unit carry it (duplicate\n ids *inside* an article: `art100_par1` ×2 in the Constitution, `art106_cpt_ite8` ×6 in\n `decreto_9358.anexo1`), and it picks the candidate root that the parts fit (the split `ali9` of\n `decreto_8289.anexo1` is the 2nd `ali9` of the file).\n- **Interval rule refined:** a sub-unit that was descended into (e.g. inciso II of art. 8, split\n across parts 1–4) necessarily *crosses* the part intervals. The nested-or-disjoint check therefore\n represents each split unit by its original interval and checks separately that every part lies\n inside it (plan §2.4 already says that parts of one unit never cover each other).\n- **Final full run** (`segment_all.py --jobs 16 --overwrite`, 87.5 s): router 9.1 s, metadata 4.6 s,\n XSL 31.5 s, split + loose 14.5 s, non-statutory 9.1 s, merge + provenance 17.8 s; validation\n ≈ 20 s. **All checks pass:** csv_schema, non_empty, chunk_id_unique, provenance, intervals,\n coverage, cap (1 flagged uncuttable TAB row, 1,163 tokens, in `portaria_2012_1114`), split_complete,\n text_coverage (min 99.8 %).\n- **Gemini `countTokens` sample: not run.** There is no `GEMINI_API_KEY`/`GOOGLE_API_KEY` and no\n Google SDK in this environment. `validate_segments.py` runs it (500 random chunks, stdlib REST,\n `--gemini-model gemini-embedding-2`) when a key is set; the report says \"not run\".\n\n### Extra corpus-wide checks (beyond the pytest fixtures)\n\n- **Python/XSL parity on every unsplit row** of all 287 statutory CSVs: 81,944 rows, **0 mismatches**\n (selection, label, interval, text, urn). It found one bug: the XSL's default `sigla` comes from\n `document-uri()`, which URL-encodes non-ASCII names (`constitui%C3%A7%C3%A3o_1988_19881005`).\n The orchestrator now passes `sigla` explicitly.\n- **XSL regression over the whole corpus** (original vs amended, no parameters, 468 files):\n `(Num_Inicio, Num_Final, urn)` sets are identical for ART and all groupings. CPT loses 11,309\n caput-only rows (X5). 1,403 orphan INC/ALI/ITE rows became DSP (X6); DSP adds another 109 orphan\n `Paragrafo`/`Caput` that the original never emitted. The only other difference is\n `port_conj_tse_srf_74_20060110`, whose URN **contains a comma**\n (`…receita.federal,tribunal.superior.eleitoral:…`): the original XSL wrote `urn` unquoted, which\n broke its CSV for that file. X9 fixes it.\n\n## Tests (`scripts/segmentation/tests`, pytest)\n\n**35 passed** (68 s): regression vs the original XSL (`lei_9250`, RIR annex), §3.2 worked target,\nremission text in the ancestor path, tables (lei 9.250 art. 3, decreto 3.000), orphan dispositivos\n(`in_rfb_1548.anexo11`, `decreto_8289.anexo1`), labels without separator, Python/XSL parity (4\nfiles), router (7 annexes, all categories), annex metadata, non-statutory document mode (parecer\n1503: epígrafe/ementa, dropped groups, cap, headings, disjoint intervals), table header + caption\nrepetition (`ade_rfb_3.anexo1`), loose-mode offset (RIR tax table), synthetic loose ids, preferred\nsplit boundaries, strategies, reference tokenizer, article split (largest articles of RIR/2018 and\nRIR/1999: parts ≤ cap, label/caput in HEAD, ordered intervals inside the article, dispositivo\ncoverage), within-leaf table split with repeated header, caput in HEAD of paragraph parts, and\nprovenance (chunk ids, `id_ambiguo` on duplicate `art16`, DSP in a main document, split parts,\ncitation path, groupings, annex `doc_urn`/`anexo_urn`). Fixture notes: parent documents are copied\ntoo, because annex metadata comes from the parent. The two large files (`decreto_9580…anexo1`,\n`decreto_3000`, 4.6 MB) are read from `lexml/articulados` instead of being duplicated. The structural\nsplit tests use the fast `chars:4` tokenizer with a small cap to force descent and leaf splits.\n\n## Step 8 — Results\n\nFinal counts and length distributions: `docs/20260924_184339_segmentation_results.md`.\nHeadline: **S1 = 26,252, S2 = 82,644, S3 = 87,947 chunks**; ART units = 19,393 = the `Artigo` count;\n647 articles + 9 DSP split into 1,752 parts. A pointer was added to strategy doc §5 (the estimates\nthere were ≈ 88 k / ≈ 94 k before the X5 CPT rule).\n\n## Summary of deviations and decisions to review\n\n| # | What | Why | How to revert |\n|---|---|---|---|\n| D1 | Loose `p`/`table` of **main** documents also segmented (27 docs, 685 elements, ≈ 116 k chars) | the XSL would drop treaty texts and tables | — |\n| D2 | `preliminar`/`localDataFecho`/`assinatura` ≥ 300 chars kept as TXT (11 kept) | mis-tagged ementas and facts | `--keep-dropped-min-chars 0` |\n| D3 | HEAD over half the cap: full once, then truncated to cap/4 | CLT art. 670 made 133 over-cap parts | — |\n| — | Ementa noise stripping beyond §2.3; epígrafe fallbacks for 7 non-statutory files | page furniture in ≈ 20 ementas (plus the 15 known CÂMARA headers) | — |\n| — | Annex title line/`tituloAnexo` is prefix-only | avoided \"ANEXO I\"-only chunks | — |\n| — | Heading-only groupings → TXT | lost text in `decreto_lei_58.anexo1` | — |\n| — | `hf:` tokenizer via `tokenizers` + `tokenizer.json` | HF Hub rate limit and slow imports; same counts | — |\n| — | 3 token-count columns in `chunks_all.csv`; provenance records for every Python row | token-budget sweeps; simpler provenance | — |\n| — | Large test fixtures read from `lexml/` | avoid 4.6 MB of duplicates | — |\n\nOpen points: the Gemini sample check (needs a key); 243 grouping rows are ≥ 8,192 tokens and\ncannot be embedded as they are if S3 is run (Q7); `segmented/` is 256 MB\n(`chunks_all.csv` 148 MB, above GitHub's 100 MB file limit), so it was **not committed**.\n\n**Finished:** 2026-09-24 ≈ 18:50.\n\n## Addendum — S3 grouping limit (decided 2026-09-24, after review)\n\n- Reviewed with the user: S3 keeps its original meaning (a grouping chunk = its own label + the\n whole content below it, as in the original XSL, [L]/[F] and plan X4). The **Q7 condition is met**\n for groupings (2,030 of 5,303 above 1,024 tokens, 243 ≥ 8,192), and the user chose **option 2:\n keep only the grouping chunks that fit the models' 8,192-token input**. Applying §5b to groupings\n (option 1) would mostly duplicate the S1 article chunks.\n- Implemented in `segment_all.py` step 6 (`--grouping-max-tokens`, default 8192; 0 keeps all).\n PRT…SSC rows with more than 8,192 reference tokens are left out of `chunks_all.csv` and listed in\n **`segmented/groupings_over_limit.csv`**: the same columns minus `Texto`, plus `n_chars`, sorted by\n tokens. Their rows stay in the per-file CSVs, so they can be handled later. New validation check\n `grouping_limit` (none left above the limit, list and `chunks_all` disjoint): ok.\n- Result: **243 groupings listed** (TIT 84, CAP 76, LIV 43, SEC 19, PRT 13, SBT 5, SSC 3; top files\n RIR/2018 annex 33, IN RFB 1.911 29, RIR/1999 25, Código Civil 18, CPC 18). The largest is the\n Código Civil PARTE ESPECIAL (179 k tokens). **S3 = 87,704 chunks** (5,060 groupings kept); S1 and S2\n unchanged (26,252 / 82,644). `chunks_all.csv` shrinks from 148 MB to 130 MB.\n- The user accepted the other defaults and deviations (D1–D3 and the smaller ones in the table above).\n\n## Addendum — freeze for embedding and manual sample review (2026-09-24)\n\n- **Freeze.** `run_info.json` records the git commit of the run (`git.commit`, and `git.dirty`,\n true when `scripts/segmentation` or `lexml/` had uncommitted changes) and the SHA-256 of\n `chunks_all.csv`, `groupings_over_limit.csv` and `annex_manifest.csv`. `chunks_all.csv` has a new\n column **`texto_sha256`** (first 16 hex digits of the SHA-256 of `Texto`); embeddings should be\n keyed by `chunk_id` + `texto_sha256`. New validation check `texto_sha256`: ok. The reference run was\n made at commit `7b145ba` (clean; `aadd584` before the history rewrite below): 87,704 rows, `chunks_all.csv` sha256 `d24a4af1…a1a9a5`. Only\n the merged files changed relative to the previous run; the 1,300 per-file CSV/sidecar files came\n out byte-identical, so the pipeline is deterministic.\n- **Manual sample review** (seeded random sample: 5 unsplit ART, 5 ART parts, 5 DSP, 8 TXT, 5 TAB,\n plus the earlier spot checks). Metadata prefixes are clean; article parts read coherently, with the\n article label and caput sentence in HEAD; DSP, TXT and statutory TAB chunks are as intended.\n Findings, all from the source/parse rather than the segmentation, none blocking:\n - **Prose parsed as tables:** 52 of 623 loose tables (45 in `nao_articulados`, 7 in statutory\n files) hold running text, ≈ 47 k chars ≈ 0.2 % of the corpus. Examples: the one-column STJ case\n list of `portaria_2012_1114` (which also holds the one uncuttable 1,163-token row) and paragraphs\n of some soluções de consulta. They come out as `Tabela: 13. Primeiramente, … | ; faz-se …`: the\n text is complete, but with table separators. Possible later fix: serialize one-column or\n prose-like tables as plain text.\n - Boilerplate `nota` groups (e.g. the AGU electronic-signature notice) are kept as TXT, as §5.2\n specifies for `nota`.\n - Parse artifacts in the source labels/text: e.g. `decreto_9358.anexo1` items whose `Rotulo` \"6.\"\n precedes the real number (\"6. 29 examinar…\"), and old tables flattened into text\n (`lei_4504` art. 50, \"ALÍQUOTAAté 2 ...\").\n- **Gemini `countTokens` check (plan §2.6) — done.** The key is read from `~/keys/gemini_api_key` (outside\n the repository) only for the command that runs the check:\n `GEMINI_API_KEY=\"$(cat ~/keys/gemini_api_key)\" .venv/bin/python scripts/segmentation/validate_segments.py`.\n The user's first attempt looked hung: 500 sequential requests plus the validation took ≈ 3 min with no\n output. The check now uses 8 threads with retries, prints progress, sends the key in the\n `x-goog-api-key` header instead of the URL, and adds the **100 largest chunks** to the 500 random\n ones. Model `gemini-embedding-2` (it lists `countTokens`). Result over the S3 chunk set (0 errors):\n - random sample (500): Gemini/reference ratio p50 **0.883**, p99 0.964, max 1.099; only 2 chunks\n count more in Gemini than in the reference (by at most 60 tokens); max 4,847 Gemini tokens;\n - 100 largest chunks (reference counts up to 8,192): ratio p50 0.878, max 0.929; **max 7,253 Gemini\n tokens; none above 8,192**.\n\n So Gemini tokenizes this corpus ≈ 12 % more compactly than the max(cl100k, Qwen3) reference, and\n **no chunk in `chunks_all.csv` would be truncated by `gemini-embedding-2`**. At most, a basic\n unit at the 1,024 cap could count ≈ 1,125 Gemini tokens (ratio 1.099), which affects granularity\n only.\n\n## Addendum — GitHub 100 MB limit: `chunks_all.csv` versioned as gzip (2026-09-24)\n\n- The push of `segmentation-implementation` was rejected: two versions of `segmented/chunks_all.csv`\n (132 MB and 131 MB) were in the local commits, over GitHub's 100 MB file limit. `git-lfs` is not\n installed. The user chose to **version a gzip instead** (over Git LFS or not versioning it).\n- **History rewrite (local, unpushed commits only):** backup branch\n `backup/segmentation-before-lfs-fix`, then\n `git filter-branch --index-filter 'git rm --cached --ignore-unmatch segmented/chunks_all.csv' origin/main..segmentation-implementation`.\n New hashes: `5255a80` (unchanged), `3816ec8`→`c1f7535`, `aadd584`→`7b145ba`, `be704f4`→`7cb3a2d`,\n `82d31b2`→`c2e7f9d`, `484564e`→`406bac6`. No blob over 20 MB is left in the unpushed history.\n- `segment_all.py` now also writes **`segmented/chunks_all.csv.gz`** (gzip with mtime 0 and no file\n name, so it is byte-deterministic: re-gzipping gives the same SHA-256; 20.4 MB). The plain CSV is\n gitignored. `run_info.json` records both SHA-256s. `validate_segments.py` reads the `.gz` when the\n CSV is absent (fresh clone), and `pd.read_csv(\"segmented/chunks_all.csv.gz\")` works directly.\n- Re-run at `9e6addd` (clean): **`chunks_all.csv` SHA-256 unchanged (`d24a4af1…a1a9a5`)**, so the\n frozen chunk set is the same; `.gz` SHA-256 `0f495ef0…fb920e`. All validation checks pass, Gemini\n check included.\n- After a successful push, the backup branch (which still holds the large blobs locally) can be\n deleted: `git branch -D backup/segmentation-before-lfs-fix`. It must not be pushed.\n","20260924_184339_segmentation_results.md":"# Segmentation Results (first full run)\n\n**Generated:** 2026-09-24 18:43:39 (local time, from `date +%Y%m%d_%H%M%S`)\n**Implements:** step 8 of `docs/20260924_123747_segmentation_implementation_plan.md`. How the numbers\nwere produced, with problems found and deviations, is in\n`docs/20260924_175304_segmentation_execution_log.md`.\n**Run:** `.venv/bin/python scripts/segmentation/segment_all.py --jobs 16 --overwrite`. Cap\n1,024 tokens, reference tokenizer `max:tiktoken:cl100k_base,hf:Qwen/Qwen3-Embedding-4B`, ementa in\nthe prefix ≤ 128 tokens. 87.5 s wall-clock on 16 workers. Validation: **all checks pass**\n(`segmented/segmentation_report.md`).\n\n## 1. Chunk counts\n\n| Strategy | Tipos | Chunks | Σ reference tokens | Strategy doc §5 estimate |\n|---|---|---:|---:|---:|\n| **S1** | ART, DSP, TXT, TAB | **26,252** | 8.20 M | ≈ 19.4 k statutory + DSP + NS |\n| **S2** | S1 + CPT, PAR, INC, ALI, ITE | **82,644** | 20.94 M | ≈ 88 k |\n| S3 | S2 + PRT…SSC ≤ 8,192 tokens | **87,704** ² | — | ≈ 94 k |\n\n- **ART units = 19,393**, exactly the number of `Artigo` outside `Alteracao` (strategy doc §4). 647\n of them (3.3 %) are above the cap and were split into parts, so S1 holds 20,479 ART rows.\n- S2/S3 are ≈ 5.5 k below the estimates because **CPT is emitted only for articles that have a\n paragraph** (plan X5/Q5): 8,084 CPT rows instead of 19,393. The other difference is the 1,403\n orphan INC/ALI/ITE rows of the original XSL, which are now `DSP` rows.\n- S3 holds 32.5 M tokens against 8.2 M for S1. Groupings are the bulk: one PRT reaches 179 k tokens.\n\n| Tipo | Rows | p50 | p90 | p99 | max (reference tokens) |\n|---|---:|---:|---:|---:|---:|\n| ART | 20,479 | 193 | 680 | 1,007 | 1,024 |\n| DSP | 1,522 | 150 | 592 | 911 | 1,009 |\n| TXT | 3,545 | 309 | 984 | 1,021 | 1,024 |\n| TAB | 706 | 354 | 981 | 1,022 | 1,163 ¹ |\n| CPT | 8,084 | 162 | 356 | 1,013 | 8,103 |\n| PAR | 21,511 | 233 | 381 | 642 | 5,936 |\n| INC | 20,617 | 193 | 352 | 569 | 4,116 |\n| ALI | 4,878 | 200 | 349 | 573 | 1,420 |\n| ITE | 1,302 | 165 | 295 | 436 | 1,358 |\n| SEC / SSC | 2,125 / 717 | 588 / 500 | 2,227 / 1,965 | 7,383 / 4,990 | 33,325 / 10,328 |\n| CAP / TIT | 1,919 / 410 | 871 / 2,476 | 4,516 / 14,610 | 15,847 / 34,857 | 72,385 / 76,134 |\n| LIV / SBT / PRT | 88 / 26 / 18 | 8,092 / 4,200 / 21,256 | — | — | 147,686 / 18,756 / 179,420 |\n\n² Updated 2026-09-24 after review (option 2): the 243 grouping chunks above 8,192 tokens are left\nout of `chunks_all.csv` and listed in `segmented/groupings_over_limit.csv`. The first run had 87,947.\n\n¹ The only chunk above the cap: one table row of `portaria_2012_1114`, which cannot be cut (plan\n§5.3); it is flagged.\n\nThe Qwen3 tokenizer counts ≈ 4–6 % more tokens than `cl100k_base` on this corpus (e.g. ART p50 194 vs\n187; INC 193 vs 182). It sets the reference count almost everywhere.\n\nPer category (rows, all Tipos): main documents 72,103 · A annexes 11,257 · B annexes 1,041 ·\nC annexes 495 · `nao_articulados` 3,051.\n\n## 2. Splitting\n\n- **ART/DSP split** (§5b): 656 units (647 ART, 9 DSP) → 1,752 parts. 72 needed a within-leaf split\n (text or table). In 8 of them the repeated HEAD was truncated after its first full appearance\n (deviation D3). Largest: `lei_10865_20040430` art. 8 (16.2 k tokens → 25 parts),\n `in_rfb_1343_20130405` art. 9 (14.4 k → 21), RIR/2018 art. 35 (10.2 k → 12).\n- **Non-statutory TXT/TAB** units split: 342.\n\n## 3. Over-cap rows left unsplit (Q7)\n\n| Tipo | Rows | > 1,024 | ≥ 8,192 |\n|---|---:|---:|---:|\n| CPT | 8,084 | 78 | 0 |\n| PAR | 21,511 | 43 | 0 |\n| INC | 20,617 | 23 | 0 |\n| ALI / ITE | 4,878 / 1,302 | 4 / 1 | 0 |\n| SEC / SSC | 2,125 / 717 | 619 / 155 | 19 / 3 |\n| CAP | 1,919 | 856 | 76 |\n| TIT / SBT | 410 / 26 | 288 / 21 | 84 / 5 |\n| LIV / PRT | 88 / 18 | 73 / 18 | 43 / 13 |\n\nSub-article rows: 149 of 56.4 k are above the cap, all below 8,192. They can go into S2 as they are\n(the Q7 default holds). Groupings: 243 rows are **≥ 8,192 tokens**, so they would be rejected by\n`text-embedding-3-small` and truncated by Gemini. **Decision (option 2):** only the embeddable groupings\nare kept; the 243 others are listed in `segmented/groupings_over_limit.csv` (see the execution log\naddendum).\n\n## 4. Other figures\n\n- Rows with `id_ambiguo = 1`: 1,810, of which 1,195 are basic units (ART/DSP/TXT/TAB). These are\n duplicate ids in the source, e.g. orphan `ali1`/`ite2` repeated in the annexes of\n `decreto_8289_20140725` and two `art16` in `circ_bc_3432_20090203`.\n- Dropped `Agrupamento`s (Q4): 392 `assinatura`, 44 `preliminar`, 13 `localDataFecho`. **11 long\n ones were kept as TXT** (deviation D2, ≥ 300 chars): mis-tagged soluções-de-consulta ementas (up to\n 1.5 k chars), case facts, and court-case headers.\n- Text coverage (word multiset of the S1 bodies vs. document text): minimum 99.8 %, every file\n ≥ 98 %.\n- Gemini `countTokens` check (`gemini-embedding-2`, run later on 2026-09-24): 500 random + the 100\n largest chunks. Gemini counts ≈ 12 % fewer tokens than the reference (ratio p50 0.88, max 1.10);\n the largest chunk counts 7,253 Gemini tokens, so **none is above 8,192** and nothing would be\n truncated.\n- Outputs: `segmented/chunks_all.csv` is 148 MB (groupings account for most of it), and\n `segmented/` is 256 MB in total.\n","20260925_122058_embedding_implementation_plan.md":"# Embedding Implementation Plan\n\n**Generated:** 2026-09-25 12:20:58 (local time, from `date +%Y%m%d_%H%M%S`)\n**Input:** `segmented/chunks_all.csv.gz`, produced by the segmentation pipeline\n(`docs/20260924_123747_segmentation_implementation_plan.md`, results in\n`docs/20260924_184339_segmentation_results.md`).\n**Strategy background:** `docs/20260923_193852_segmentation_strategies_for_rag_experiments.md` (referred\nto below as **the strategy doc**). It requires **one embedding run per model over the S3 chunk set**;\nS1 and S2 are filters on `Tipo`, so they need no extra embedding.\n**Deliverables:** code in `scripts/embedding/`, outputs in `embeddings/`. The script is meant to be\n**released with the research data**, so clarity, reproducibility and ease of use are requirements,\nnot extras (§6).\n\nStatus (2026-09-25, evening): **steps 0–6 implemented for the `tei` provider** (`scripts/embedding/`,\nsee §10). Only the `jua-4b-mixed` endpoint exists; the user works with jua alone for now, so the\nOpenAI and Gemini providers and the other two endpoints are deferred.\n\n---\n\n## 1. Decisions from the 2026-09-25 discussion\n\n### 1.1 Models to compare\n\n| Slug | Model | Provider / how it runs | Dim | Max input | License |\n|---|---|---|---|---|---|\n| `jua-4b-mixed` | `ufca-llms/jua-4B-mixed` @ `57f491c1718171c0ad71d723c4f6b2030684c4eb` | HF Inference Endpoint (TEI) | 2560 | 8192 (card) | MIT |\n| `qwen3-emb-4b` | `Qwen/Qwen3-Embedding-4B` @ `5cf2132abc99cad020ac570b19d031efec650f2b` | HF Inference Endpoint (TEI) | 2560 | 32k (we cap at 8192) | Apache-2.0 |\n| `inf-retriever-v1` | `infly/inf-retriever-v1` @ `6c5b3f3156c0a705e30608f8ef6375d965b0f18f` | HF Inference Endpoint (TEI) | 3584 | 32k (we cap at 8192) | Apache-2.0 |\n| `openai-te3-large` | `text-embedding-3-large` | OpenAI API | 3072 | 8192 | paid API |\n| `openai-te3-small` | `text-embedding-3-small` | OpenAI API | 1536 | 8192 | paid API |\n| `gemini-emb-2` | `gemini-embedding-2` | Gemini API | 3072 | 8192 | paid API |\n\nThe commit SHAs are the Hub `main` revisions on 2026-09-25. **Pin them** on the endpoints and in the\nconfig (§3.3, §5.2) so a later model update can't silently change the embeddings.\n\nModel facts checked in the repos' own files on 2026-09-25:\n\n- **jua-4B-mixed:** fine-tune of `Qwen/Qwen3-Embedding-4B`. The architecture is `Qwen3ForCausalLM`\n with 36 layers, hidden size 2560 and `dtype: bfloat16`. Weights are about 8 GB in two safetensors\n shards. The sentence-transformers modules are Transformer → last-token Pooling → Normalize, and\n `config_sentence_transformers.json` has the prompts `query` = the Qwen web-search instruction and\n `document` = `\"\"`. The Hub repo has **no `text-embeddings-inference` tag**, unlike the other two.\n TEI should still load it because the architecture is identical to Qwen3-Embedding-4B, but this is\n checked at setup (§3.8).\n - Its card reports results on **BR-TaxQA-R (v1)** (NDCG@10 0.777) in the JUÁ evaluation\n environment. The listed training data (JUÁ-Juris, Ulysses legislative supervision, a synthetic\n legislative extension, SQuAD-pt) does not include BR-TaxQA-R. Cite this in the paper and state\n that no BR-TaxQA-R data was used for training (paper: arXiv:2605.04005).\n- **Qwen3-Embedding-4B:** same architecture and modules as jua. TEI lists it as supported.\n- **inf-retriever-v1:** built on `gte-Qwen2-7B-instruct`. The architecture is `Qwen2Model` with\n 28 layers, hidden size 3584 and bf16 weights of about 15 GB. It uses last-token pooling +\n Normalize. The only prompt is `query` = the web-search instruction with a **trailing space**\n after `Query:`. Its transformers usage needs `trust_remote_code` (`modeling_qwen.py`) because\n **gte-Qwen2 models use bidirectional attention**. TEI lists gte-Qwen2 as supported. Its training\n data is mainly Chinese and English, so note it in the paper as a non-Portuguese baseline.\n- **text-embedding-3-large / -small** (both are run; D2 decided 2026-09-25): 8192-token input limit using the `cl100k_base` tokenizer. The output\n is L2-normalized. Price is about **$0.13 per 1M tokens** (derived from OpenAI's \"9,615 pages per\n dollar\" at 800 tokens/page), so ≈ $3.5 for the corpus. `-small` costs about $0.02 per 1M tokens\n (≈ $0.5 for the corpus).\n- **gemini-embedding-2:** 8192-token input limit and 3072 dimensions by default. Embeddings are\n normalized automatically, including at reduced dimensions. Task selection uses **text prefixes**:\n queries are `task: search result | query: {content}` and documents are\n `title: {title} | text: {content}` (§4.3). The Batch API costs 50 % of the normal price.\n\n### 1.2 Why the local GPU is not used\n\n- **Hardware:** the local GPU is an RTX 4050 Laptop with 6 GB of memory, in WSL2 with 15 GB of RAM.\n The 4B models need about 8 GB for their BF16 weights alone.\n- **Quantization would fit, but it changes the embeddings.** Options include 8-bit bitsandbytes,\n 4-bit NF4, or GGUF Q8_0 with `llama-server --embedding`. The embeddings would then no longer come\n from the published checkpoint, which is a confound in a model comparison. It would also be slow\n on 8k-token chunks.\n- **Decision:** run every open model **unquantized** on HF Inference Endpoints. The local machine\n is used only as a client, and for the CPU parity reference of the 4B models (§5.4).\n\n### 1.3 Why HF Inference Endpoints + TEI\n\n- **Managed service:** HF runs the GPU. The endpoint is an HTTPS URL protected by the HF token, so\n it works just like a paid embedding API.\n- **Supported models:** TEI (Text Embeddings Inference) supports Qwen3 and gte-Qwen2 natively. It\n batches requests by token count on the server side.\n- **OpenAI compatibility:** it exposes `/v1/embeddings` as well as its own `/embed`.\n- **Billing:** per minute, with **scale-to-zero** and pause. At current prices (§3.2), each open\n model costs a few dollars to embed the corpus.\n- **Fallback:** if TEI fails the parity check for a model (§5.4), use the **vLLM** engine on the\n same endpoint service. vLLM supports bf16 and pooling models. For gte-Qwen2 it needs\n `--hf-overrides '{\"is_causal\": false}'`; without it the embeddings come out silently wrong.\n\n### 1.4 Rules shared by every model (so the comparison is fair)\n\n1. **Same inputs.** Embed the `Texto` column of `chunks_all.csv.gz` exactly as it is: no cleaning,\n no truncation, and the same text for every model.\n2. **No silent truncation.** Every chunk is at or below 8192 tokens for every model. Tokens counted\n by the segmentation pipeline: max Qwen3 **8119** and max cl100k **7895**; the Gemini\n `countTokens` sample max was 7253. Each model's own tokenizer checks this before sending (§5.5),\n and the server is set to **reject** oversize inputs instead of truncating (TEI\n `AUTO_TRUNCATE=false` or per-request `truncate: false`).\n3. **Documents without an instruction, queries with one.** This is how all three open models are\n meant to be used (the `document` prompt is `\"\"`). A useful consequence is that **the query\n instruction can be changed later without re-embedding the corpus**, since 715 queries cost\n almost nothing.\n4. **L2-normalized vectors at native dimension.** There is no MRL reduction in the main runs.\n Normalize on the client side too, since it is idempotent and protects against provider\n differences.\n5. **Embed each unique text once.** The corpus has 87,702 rows but **84,568 distinct\n `texto_sha256`**. Store vectors per unique text and map them back to `chunk_id` (§4.1). Check\n that the full text matches for equal hashes (the hash is truncated to 16 hex characters).\n6. **Record provenance.** For each run, record the model and revision, provider, engine version,\n dtype, prompts, input file SHA-256, the parity-check result, timings and the approximate cost\n (§4.4).\n\n### 1.5 Corpus and query facts (measured 2026-09-25, after the metadata fixes of §2 step 0)\n\n| Item | Value |\n|---|---|\n| Chunk rows / unique texts | 87,702 / 84,568 |\n| Rows by `Tipo` | PAR 21,511 · INC 20,617 · ART 20,477 · CPT 8,084 · ALI 4,878 · TXT 3,545 · SEC 2,106 · CAP 1,843 · DSP 1,522 · ITE 1,302 · SSC 714 · TAB 706 · TIT 326 · LIV 45 · SBT 21 · PRT 5 |\n| Qwen3 tokens: total / p50 / p90 / p99 / max | 27.0 M / 210 / 539 / 2,009 / 8,119 |\n| cl100k tokens: total / max | 25.7 M / 7,895 |\n| Rows > 2,048 Qwen3 tokens | 847 |\n| Queries | 715 questions in `../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json` (`question_number`, `question_text`, …) |\n\nExpected output sizes as float32 over 84,568 texts: 2560 dimensions ≈ 0.87 GB, 3584 ≈ 1.21 GB,\n3072 ≈ 1.04 GB. All are above GitHub's 100 MB file limit (§4.2).\n\n---\n\n## 2. Work breakdown (order of execution)\n\n0. **Fix synthesized document metadata** (§8.2). **Done 2026-09-25**, see\n `docs/20260925_125514_constitution_metadata_fix.md` (§5 there). The statutory parser was fixed\n (`../lexml-parser-projeto-lei/work_history/20260925_130918_numero_complemento_and_constituicao_epigrafe_fix.md`),\n `original/articulados` re-parsed, and `lexml/articulados` updated. Segmentation was then\n re-run. As a result:\n - the Constitution and MPs 2.158-35, 2.159-70, 2.189-49 and 2.228-1 now have correct URNs and\n epígrafes;\n - the chunks have 87,702 rows / 84,568 unique texts (§1.5).\n\n All of it was committed (`ebf6567` in the parser repo; `ecd68e5` and `d3581fb` here, with a\n clean `run_info.json`).\n1. **Scaffold `scripts/embedding/`** (§6.1): config file, CLI skeleton, README, pinned requirements,\n `.env.example`, and a `.gitignore` entry for `embeddings/**/*.npy` and `.env`.\n2. **Providers** (§5.3): `tei`, `openai`, `gemini`, all behind one interface.\n3. **Corpus and query loaders** (§4.1, §4.3), with de-duplication and token-length guards (§5.5).\n4. **Resumable runner with a shard store** (§5.6) and a `finalize` step that writes the release\n format (§4.2).\n5. **Parity check** (§5.4) and **smoke test** (`check` subcommand).\n6. **Tests** (§6.4) that use a fake provider, so no network or GPU is needed.\n7. **HF setup** (§3), done by the user following this document. Then run the models in cost order:\n `qwen3-emb-4b` first (TEI officially supports it, so it's the best test of the pipeline), then\n `jua-4b-mixed`, `inf-retriever-v1`, `openai-te3-small`, `openai-te3-large` and `gemini-emb-2`.\n8. **Record costs** in the ledger as each step runs (§9), and reconcile them with the providers'\n billing once it is available.\n9. **Record results** in a dated `docs/…_embedding_execution_log.md`: timings, cost, parity numbers\n and deviations. Update `CLAUDE.md` (`embeddings/` folder) and the release README.\n\n---\n\n## 3. Hugging Face Inference Endpoints setup (user reference)\n\nThis section is a self-contained guide. Prices and UI labels were checked on 2026-09-25; check them\nagain when creating the endpoints.\n\n### 3.1 Account prerequisites\n\n1. **HF account with billing.** Go to <https://huggingface.co/settings/billing> and add a payment\n method. HF recommends prepaid credits with automatic recharge so an endpoint doesn't stop\n mid-run. If the endpoints should be billed to an organization (e.g. `unicamp-dl`), the org\n needs its own billing, and you create the endpoints under the org namespace.\n2. **Access token.** At <https://huggingface.co/settings/tokens>, create a **fine-grained** token\n named e.g. `br-taxqa-embeddings` with these permissions:\n - *Inference → Make calls to Inference Endpoints* (needed to embed);\n - *Inference → Manage Inference Endpoints* (needed only if the script or you pause, resume or\n delete endpoints programmatically, §3.6);\n - if you use an org, grant these for the org namespace.\n3. **Store the token locally** without committing it: either run `hf auth login`, which writes it\n to `~/.cache/huggingface/token`, or put `HF_TOKEN=hf_…` in the repo's `.env` (gitignored, §6.3).\n4. **GPU quota.** New accounts may have a small GPU quota. If an instance type is greyed out or\n creation fails with a quota error, request more through the Endpoints UI or HF support. Paused\n endpoints don't count against the quota; **scaled-to-zero endpoints do**.\n\n### 3.2 Hardware choice and expected cost\n\nPrices are per hour and billed per minute (HF pricing page, 2026-09-25):\n\n| Instance | GPU memory | AWS | GCP |\n|---|---|---|---|\n| nvidia-t4 | 14–16 GB | $0.50 | $0.50 |\n| **nvidia-l4** | 24 GB | $0.80 | $0.70 |\n| nvidia-a10g | 24 GB | $1.00 | — |\n| **nvidia-l40s** | 48 GB | $1.80 | — |\n| nvidia-a100 | 80 GB | $2.50 | $3.60 |\n\n| Model | Recommended | Why | Rough time / cost for the corpus |\n|---|---|---|---|\n| `qwen3-emb-4b`, `jua-4b-mixed` | **L4** (A10G as alternative) | 8 GB of weights plus room for 8k-token batches | ~1–3 h / ~$1–3 each |\n| `inf-retriever-v1` | **L40S** | 15 GB of weights. 24 GB fits but leaves little room for activations at 8k tokens, and 48 GB allows a larger `MAX_BATCH_TOKENS` | ~1–2 h / ~$2–4 |\n\nAvoid **T4**. It has no native bf16, TEI runs in fp16 anyway (§3.4), and it is slow. The time\nestimates assume 30–40 % of peak throughput on about 2·params·27 M FLOPs. Treat them as order of\nmagnitude, and replace them with the rate measured in the first 5 minutes of the real run (§3.7).\n\n### 3.3 Creating an endpoint in the UI (once per open model)\n\n1. Open <https://endpoints.huggingface.co> and click **New** (or **Catalog**, then search).\n Alternatively, on the model's Hub page use **Deploy → Inference Endpoints**.\n2. **Model repository:** enter the repo id, e.g. `Qwen/Qwen3-Embedding-4B`.\n - Set the **revision** to the commit SHA from §1.1 instead of `main`, under the\n advanced/model settings.\n3. **Endpoint name:** use something short, since it becomes part of the URL, e.g.\n `qwen3-emb-4b-brtaxqa`, `jua-4b-mixed-brtaxqa`, `inf-retriever-v1-brtaxqa`.\n4. **Cloud / region:** AWS `us-east-1` has the widest GPU choice. The provider must offer the\n chosen instance (L40S is AWS only).\n5. **Hardware:** as in §3.2, with instance size `x1` (one GPU).\n6. **Security level: Protected.** Requests need a valid HF token. Don't use *Public*, which has no\n auth. *Private* requires AWS PrivateLink and isn't needed.\n7. **Autoscaling:**\n - **min replicas 0**, **max replicas 1**;\n - **scale-to-zero after 15 min** of inactivity. The UI default is 1 h; lower it so an\n unfinished session doesn't keep billing.\n - One replica is enough. Throughput comes from TEI's internal batching, and more replicas\n would only multiply the cost.\n8. **Container / engine: Text Embeddings Inference.** It is usually pre-selected for models\n tagged `text-embeddings-inference`. **For `jua-4B-mixed` it may not be**, since the repo lacks\n the tag. Select TEI by hand; if the UI refuses, see §3.8.\n - **What worked for `jua-4B-mixed` (2026-09-25).** The repo has no `library_name` and its\n `pipeline_tag` is `sentence-similarity`, so the UI offers the Default engine, which asks for\n a custom `handler.py`. A **Custom container** was used instead, on the original repo at the\n pinned revision:\n - image `ghcr.io/huggingface/text-embeddings-inference:89-1.9.4` (`89` = Ada, for L4/L40S;\n `86` for A10G; no prefix for A100). Pin the full patch version;\n - port `80`, health route `/health`;\n - env `MODEL_ID=/repository`, `AUTO_TRUNCATE=false`, `MAX_BATCH_TOKENS=40960`,\n `MAX_CLIENT_BATCH_SIZE=64`.\n\n `/info` then shows `model_id: /repository` and no model SHA, so record the revision from the\n endpoint's configuration page. The §3.4 smoke tests passed: 2,560 dimensions, norm 1,\n sensible ranking, and an input over 40,960 tokens was rejected.\n9. **Engine settings.** Set these in the TEI configuration panel; the environment-variable name is\n given in brackets:\n - **Max Tokens per batch** [`MAX_BATCH_TOKENS`]:\n - `40960` on L4 / A10G (the minimum for the Qwen3 models, see below);\n - `65536` on L40S;\n - it must be at least the model's max input length when `AUTO_TRUNCATE=false`, otherwise\n TEI refuses to start. TEI takes that length from `sentence_bert_config.json`\n (`max_seq_length`), and since neither jua nor Qwen3-Embedding-4B has that file, it falls\n back to `config.json` `max_position_embeddings` = **40,960** (it logs the warning\n \"Could not find a Sentence Transformers config\", which is harmless). Found on the first jua\n endpoint (2026-09-25), which failed to start with `32768`. The server then accepts inputs up\n to 40,960 tokens, so the 8192 limit is enforced by the client guard (§5.5). If TEI fails\n at startup with a max-length message, raise `MAX_BATCH_TOKENS` to the value it prints.\n - **Max Concurrent Requests** [`MAX_CONCURRENT_REQUESTS`]: leave the default (512).\n - **Pooling** [`POOLING`]: **leave empty**, so it's read from `1_Pooling/config.json`, which is\n last-token for all three models. Set `last-token` only if TEI logs a different choice.\n - **Environment variables** (advanced section):\n - `AUTO_TRUNCATE=false`: oversize inputs are rejected with an error instead of being cut.\n The client also sends `truncate: false`.\n - `MAX_CLIENT_BATCH_SIZE=64`: inputs per request. The default is 32. The 2 MB payload limit\n is safe because 64 × 8k tokens is about 2 MB at worst, and the client caps each request by\n tokens anyway (§5.3).\n - `DTYPE` (only `float16` / `float32` are accepted): **leave it unset** at first, and TEI\n runs in fp16 on GPU. The models were trained and published in **bf16**, which TEI's\n `--dtype` does not offer. This is exactly what the parity check (§5.4) measures. If fp16\n fails the parity check, try `DTYPE=float32`, which needs 16 GB of weights for 4B and 30 GB\n for 7B, so an L40S or A100. If that also fails or is too slow, use the vLLM fallback\n (§3.8).\n10. Click **Create Endpoint**. Initialization takes about 3–10 minutes, including the weight\n download. Wait until the status is **Running**.\n11. Copy the **Endpoint URL**, e.g. `https://xxxxxxxx.us-east-1.aws.endpoints.huggingface.cloud`,\n into `.env` under the variable named in the model config, e.g. `ENDPOINT_URL_QWEN3_EMB_4B=…`\n (§6.3).\n\n### 3.4 Smoke test (before any real run)\n\n```bash\nsource .env # HF_TOKEN, ENDPOINT_URL_…\nURL=$ENDPOINT_URL_QWEN3_EMB_4B\n\n# engine, model, revision, dtype, pooling, max_input_length, max_batch_tokens, version\ncurl -s \"$URL/info\" -H \"Authorization: Bearer $HF_TOKEN\" | python -m json.tool\n\n# one embedding, no truncation allowed\ncurl -s \"$URL/embed\" -X POST -H \"Authorization: Bearer $HF_TOKEN\" -H 'Content-Type: application/json' \\\n -d '{\"inputs\": [\"Art. 1º Teste.\"], \"normalize\": true, \"truncate\": false}' | head -c 200\n\n# token count as the server sees it\ncurl -s \"$URL/tokenize\" -X POST -H \"Authorization: Bearer $HF_TOKEN\" -H 'Content-Type: application/json' \\\n -d '{\"inputs\": \"Art. 1º Teste.\"}' | head -c 400\n```\n\nThe script's `check` subcommand (§6.2) runs the same test, saves `/info` into the run manifest,\nand fails if the `model_id`, `model_sha` or `max_input_length` doesn't match the config.\n\n### 3.5 Running, then pausing\n\n1. Run `embed corpus` (§6.2). The client keeps several requests in flight so TEI can fill its\n batches.\n2. **Watch the first ~5 minutes** in the endpoint's **Analytics / Logs** tabs: GPU use, request\n latency, and any 4xx/5xx errors. Tune the concurrency flag or `MAX_BATCH_TOKENS` if the GPU is\n idle or out of memory.\n3. **Right after the run, pause the endpoint.** Use **Settings → Pause** in the UI, or §3.6.\n Paused endpoints cost nothing and keep their configuration, so `resume` brings back the same\n URL. Delete the endpoint once all runs, including query re-runs, are final.\n4. After scale-to-zero, the first request gets a **503** while the replica starts (minutes). The\n client retries with backoff for up to ~15 minutes, so a cold start doesn't fail the run.\n\n### 3.6 Optional: managing endpoints from Python (`huggingface_hub`)\n\nThis is useful to pause and resume from the script's `endpoint` subcommand (§6.2) and to keep a\nrecord of the configuration used. Create the endpoints **in the UI** (§3.3). Programmatic creation\nneeds the correct TEI image tag per GPU architecture (e.g. `89-<ver>` for Ada L4/L40S, `86-<ver>`\nfor A10G, `<ver>` for A100), and the UI picks that for you.\n\n```python\nfrom huggingface_hub import get_inference_endpoint\n\nep = get_inference_endpoint(\"qwen3-emb-4b-brtaxqa\") # namespace=… for an org\nep.resume().wait() # blocks until Running\nprint(ep.url, ep.status, ep.raw[\"compute\"], ep.raw[\"model\"]) # save ep.raw in the run manifest\n# … run the embedding …\nep.pause() # stop billing; ep.delete() when all runs are final\n```\n\nIf you do want creation in code, use `huggingface_hub.create_inference_endpoint(name, repository=…,\nrevision=<sha>, framework=\"pytorch\", task=\"sentence-embeddings\", accelerator=\"gpu\", vendor=\"aws\",\nregion=\"us-east-1\", instance_type=\"nvidia-l4\", instance_size=\"x1\", min_replica=0, max_replica=1,\nscale_to_zero_timeout=15, type=\"protected\", custom_image={…TEI image, health_route \"/health\", env…})`.\nCheck the argument names against the installed `huggingface_hub` version first.\n\n### 3.7 Measuring throughput and cost\n\n- The runner logs tokens/s and texts/s every N batches, and at the end writes the wall time into\n the manifest.\n- **Cost is recorded automatically** in the cost ledger (§9). For endpoints the script measures\n the **replica-minutes** the endpoint was up, including cold start and idle time, not only the\n time spent embedding (§9.3).\n- **Reproducibility note:** TEI batches dynamically, so batch composition and padding change\n between runs. In fp16 this can change the last digits of a vector. That's expected; the parity\n check thresholds (§5.4) allow for it, and the stored vectors are the reference.\n\n### 3.8 Troubleshooting\n\n| Symptom | Likely cause | Fix |\n|---|---|---|\n| 401 / 403 | Token lacks *Make calls to Inference Endpoints*, or is for the wrong namespace | Fix the token's permissions (§3.1) |\n| 503 on the first request | Scaled to zero, replica starting | Wait; the client retries automatically |\n| 413 Payload too large | Too many long inputs in one request | Lower the client's `max_request_tokens` (§5.3) |\n| 422 / \"input validation error … must have less than N tokens\" | A chunk longer than the server's max input length | Should not happen (§1.4 rule 2). Check the chunk; **never** turn truncation on to get around it |\n| Endpoint fails at startup: `max_batch_tokens` < max input length | `AUTO_TRUNCATE=false` needs `MAX_BATCH_TOKENS` ≥ `max_input_length` | Raise `MAX_BATCH_TOKENS` to the value in the log |\n| CUDA OOM at startup or under load | `MAX_BATCH_TOKENS` too high for the GPU | Halve it, or move to a larger GPU |\n| TEI won't load `jua-4B-mixed` (\"model not supported\"), or the UI doesn't offer TEI | Missing Hub tag, or an architecture-detection problem | Pick **Custom container** with the TEI image, or duplicate the repo into your namespace with the `text-embeddings-inference` tag added in its README metadata (same weights; record both SHAs). Otherwise use the vLLM fallback below |\n| Parity check fails in fp16 | fp16 overflow or precision loss vs bf16, or (inf-retriever) a causal-attention mismatch | Try `DTYPE=float32`. Otherwise **vLLM engine**: `--runner pooling` (older versions `--task embed`), `--dtype bfloat16`, `--max-model-len 8192`, and for inf-retriever `--hf-overrides '{\"is_causal\": false}'`. vLLM exposes the OpenAI `/v1/embeddings` route; the `tei` provider has an `openai_compat` mode for it (§5.3) |\n\n---\n\n## 4. Data formats\n\n### 4.1 Corpus input\n\n- **Default input:** `segmented/chunks_all.csv.gz`. Read it with pandas, `dtype=str` for ids, and\n `keep_default_na=False` so a text like \"NA\" isn't turned into NaN.\n- **Columns used:** `chunk_id`, `texto_sha256` and `Texto`, plus the token-count columns for\n planning. The script **recomputes** `texto_sha256` over `Texto` and fails if it differs from the\n column, which catches an edited or re-encoded file.\n- **Unique texts:** group by the full `Texto`, not only by the 16-hex hash, and embed each text\n once. The `text_id` is the hash; if two different texts ever share a hash prefix, it fails\n loudly.\n- **Order:** sort unique texts by `text_id` so shards and outputs don't depend on the CSV row order.\n- **Generic by design:** `--input` accepts any CSV/CSV.GZ/Parquet/JSONL with configurable `--id-col`\n and `--text-col`. Other people can reuse the script on their own chunks.\n\n### 4.2 Output layout (release format)\n\n```\nembeddings/\n <model_slug>/\n corpus/\n vectors.npy float32 [n_texts, dim], L2-normalized, rows in text_id order\n texts.csv row, text_id (texto_sha256), n_tokens (model tokenizer)\n chunk_map.csv.gz chunk_id, text_id (87,702 rows → 84,568 texts)\n manifest.json provenance (§4.4)\n queries/\n vectors.npy float32 [n_queries, dim]\n queries.csv row, query_id (question_number), text_sent (exact string embedded, prompt included)\n manifest.json\n parity.json parity-check result (§5.4)\n _shards/ in-progress shard store (§5.6); removed by `finalize`\n```\n\n- Use **`.npy`** so it loads with `np.load(..., mmap_mode=\"r\")`, needs no extra dependencies, and\n is language-neutral. A CSV sidecar maps rows to ids.\n- **Size and release:** 0.9–1.2 GB per model doesn't fit in git. `embeddings/` stays gitignored\n except for manifests, `parity.json`, `endpoint_meter.jsonl` and the cost ledger `costs.csv` (§9), which are small and versioned so the provenance is in\n git. Release the vectors as a **Hugging Face dataset**, e.g. `unicamp-dl/BR-TaxQA-R` v2.0 files\n or a companion repo, with a README that states the `.npy` layout. Optionally also provide a\n float16 copy (half the size, negligible retrieval change). The float32 files are canonical.\n\n### 4.3 Queries input and prompt templates\n\n- **Queries** are the `question_text` of the 715 entries in\n `../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json`, with `question_number` as the id.\n Using `question_summary` too is left to §8. `--input` accepts any JSON/JSONL/CSV with\n configurable id and text fields, so the released script doesn't depend on the sibling repo path.\n Its README points to the HF dataset instead.\n- **Templates live in the config, per model and per side.** `{text}` is the chunk or question and\n `{instruction}` is the shared task description:\n\n | Model | Query template | Document template |\n |---|---|---|\n | `jua-4b-mixed` | `Instruct: {instruction}\\nQuery: {text}` (as on its card; note the space) | `{text}` |\n | `qwen3-emb-4b` | `Instruct: {instruction}\\nQuery:{text}` (as in its ST config and the official usage) | `{text}` |\n | `inf-retriever-v1` | `Instruct: {instruction}\\nQuery: {text}` (as in its ST config) | `{text}` |\n | `openai-te3-large`, `openai-te3-small` | `{text}` | `{text}` |\n | `gemini-emb-2` | `task: search result \\| query: {text}` | `title: none \\| text: {text}` (§8) |\n\n The exact string sent for every query is saved in `queries.csv` (`text_sent`), so there's no\n doubt about spaces or newlines.\n- **Instruction (default, §8):** use **one shared, task-specific instruction** for the three\n instruct models, in English, since Qwen3's docs recommend English instructions even for\n non-English data:\n `Given a question about Brazilian personal income tax (IRPF), retrieve the legal provisions that answer it`.\n Qwen's default web-search instruction and jua's legal instruction are kept as named alternatives\n in the config. Changing the instruction only re-embeds the queries (§1.4 rule 3), so an\n instruction ablation is cheap.\n\n### 4.4 Manifest (`manifest.json`)\n\nThe manifest records:\n\n- `schema_version`, `created_at`, script version (git commit + dirty flag, as in the segmentation\n `run_info.json`), and the full command line;\n- `model`: slug, provider, model id, revision SHA, dimension, and the templates and instruction\n used;\n- `server`: the TEI `/info` output (model id and SHA, dtype, pooling, max input length, version),\n or the OpenAI/Gemini model name and API version;\n- `input`: path, SHA-256 of the file, id/text columns, row count, unique-text count, and token\n stats from the model's own tokenizer;\n- `output`: SHA-256 of `vectors.npy` and of the sidecar CSVs, shape, dtype, and a check that the\n vector norms are 1 ± 1e-3;\n- `run`: start/end time, wall time, tokens/s, number of requests, retries and error counts;\n cost: a pointer to the ledger rows of this run (§9) and their estimated USD;\n- `parity`: a pointer to `parity.json` and a pass/fail summary.\n\n---\n\n## 5. Script design\n\n### 5.1 Location and dependencies\n\n- **Folder:** `scripts/embedding/`, parallel to `scripts/segmentation/`. It is self-contained so it\n can be released on its own.\n- **Dependencies:**\n - core: `numpy`, `pandas`, `pyyaml`, `huggingface_hub` (TEI client + endpoint management),\n `tokenizers` (length checks with the models' `tokenizer.json`), `tiktoken` (OpenAI length\n checks), `python-dotenv`, `tqdm`;\n - providers: `openai` and `google-genai`. Import them lazily so a user who only runs the open\n models doesn't need them.\n - **Parity reference only**, as an optional extra (`requirements-parity.txt`):\n `sentence-transformers`, `torch`, `transformers`.\n- **Python 3.12**, with versions pinned in `requirements.txt` like the segmentation step.\n\n### 5.2 Configuration (`scripts/embedding/models.yaml`)\n\nOne entry per model slug. The code contains **no model-specific settings**, so adding a model means\nadding a YAML entry.\n\n```yaml\ndefaults:\n instruction_name: irpf # D1, §8.1\n instructions:\n irpf: \"Given a question about Brazilian personal income tax (IRPF), retrieve the legal provisions that answer it\"\n web_search: \"Given a web search query, retrieve relevant passages that answer the query\"\n jua_legal: \"Given a Brazilian legal search query, retrieve relevant legal passages or documents.\"\n max_input_tokens: 8192\n normalize: true\n\nmodels:\n qwen3-emb-4b:\n provider: tei\n model_id: Qwen/Qwen3-Embedding-4B\n revision: 5cf2132abc99cad020ac570b19d031efec650f2b\n endpoint_url_env: ENDPOINT_URL_QWEN3_EMB_4B\n endpoint_name: qwen3-emb-4b-brtaxqa # for pause/resume and the cost meter (§9.3)\n dim: 2560\n tokenizer: hf:Qwen/Qwen3-Embedding-4B@5cf2132…\n query_template: \"Instruct: {instruction}\\nQuery:{text}\"\n document_template: \"{text}\"\n request: {max_inputs: 64, max_request_tokens: 32768, concurrency: 8}\n price: {usd_per_hour: 0.80, instance: nvidia-l4, checked: 2026-09-25}\n # jua-4b-mixed, inf-retriever-v1: same shape (see §1.1, §4.3)\n openai-te3-large:\n provider: openai\n model_id: text-embedding-3-large\n api_key_env: OPENAI_API_KEY\n dim: 3072\n tokenizer: tiktoken:cl100k_base\n query_template: \"{text}\"\n document_template: \"{text}\"\n request: {max_inputs: 256, max_request_tokens: 250000, concurrency: 4}\n price: {usd_per_million_tokens: 0.13, checked: 2026-09-25}\n openai-te3-small: # same as openai-te3-large except:\n provider: openai\n model_id: text-embedding-3-small\n dim: 1536\n price: {usd_per_million_tokens: 0.02, checked: 2026-09-25}\n gemini-emb-2:\n provider: gemini\n model_id: gemini-embedding-2\n api_key_env: GEMINI_API_KEY\n dim: 3072\n tokenizer: gemini:countTokens # the API's own count; used only for the pre-check sample\n query_template: \"task: search result | query: {text}\"\n document_template: \"title: none | text: {text}\" # D3, §8.2\n request: {max_inputs: 100, concurrency: 4}\n price: {usd_per_million_tokens: null, checked: null} # fill from the Gemini pricing page before the run (§9.2)\n```\n\nCheck the OpenAI per-request limits (inputs per request and total tokens per request) and the\nGemini batch limits against the current API reference when implementing, and put them in the\nconfig, not the code.\n\n### 5.3 Provider interface\n\n```python\nclass Provider(Protocol):\n name: str\n def info(self) -> dict: ... # goes into the manifest\n def embed(self, texts: list[str]) -> np.ndarray: ... # float32 [len(texts), dim]\n def count_tokens(self, texts: list[str]) -> list[int]: ... # model's own tokenizer\n```\n\n- **`tei`:**\n - Uses `huggingface_hub.InferenceClient(model=<endpoint url>, token=HF_TOKEN)` and\n `feature_extraction(texts, normalize=True, truncate=False)`, or a plain `POST /embed` with the\n same body.\n - `info()` = `GET /info`.\n - Retries on 429/5xx and cold-start 503 with exponential backoff and jitter, up to a total wait\n limit.\n - `openai_compat: true` mode sends the request to `/v1/embeddings` instead. This is needed for\n the vLLM fallback, and in that case length checks rely only on the client-side guard.\n- **`openai`:**\n - Uses the `openai` SDK `embeddings.create(model=…, input=[…], encoding_format=\"float\")`, with\n no `dimensions` argument (native size).\n - Batches are packed under both the input-count and token-count limits.\n- **`gemini`:**\n - Uses `google-genai` `client.models.embed_content(model=…, contents=[…])`, with no\n `output_dimensionality` (native 3072).\n - Turns off auto-truncation if the API offers the option; otherwise it relies on the pre-check.\n - The **Batch API** (50 % cheaper, asynchronous) is an optional mode, `--gemini-batch`. It is\n not the default, because the synchronous path is simpler to resume and the corpus costs\n little either way.\n- **`fake`:** deterministic vectors from a hash of the text, used in tests and for dry runs\n (`--dry-run` estimates tokens and cost without sending anything).\n\n### 5.4 Parity check (`embed.py parity`)\n\n**Purpose:** show that the served embeddings equal those of the model's reference implementation.\nThis matters most for TEI, which runs in fp16 rather than bf16, and for inf-retriever's\nbidirectional attention.\n\n- **Sample:** a fixed and versioned set of **64 corpus texts** (stratified by `Tipo` and by length,\n including the 5 longest chunks) and **16 queries**. The ids are listed in\n `scripts/embedding/parity_sample.json`.\n- **Reference:** sentence-transformers using **exactly the model card's usage**:\n - `SentenceTransformer(model_id, revision=sha, model_kwargs={\"torch_dtype\": torch.bfloat16})`,\n plus `trust_remote_code=True` for inf-retriever;\n - `prompt` = the same query string the endpoint gets (the templates are applied before both\n paths, so the prompt handling is the same);\n - `normalize_embeddings=True`.\n- **Where the reference runs:**\n - 4B models: **on the local CPU in bf16**, about 8 GB of RAM (fits in the 15 GB), slow but fine\n for 80 texts.\n - `inf-retriever-v1` (15 GB in bf16, which doesn't fit): run on a **cloud GPU notebook**. Options\n are a Hugging Face Space with the JupyterLab template on an L4/L40S (pause it afterwards) or\n a Colab L4/A100 session. `embed.py parity --reference-only --out parity_ref_<slug>.npz` writes\n the reference vectors so they can be computed elsewhere and compared locally.\n- **Metrics** saved in `parity.json`: per-text cosine similarity between served and reference\n vectors (min, p1, median), plus the **ranking agreement** of the 16 queries over the 64 texts\n (top-1 equal, Kendall τ of the full ranking).\n- **Pass thresholds (provisional; adjust after the first run):** median cos ≥ 0.999, min cos\n ≥ 0.995, top-1 identical for all 16 queries.\n- **Gate:** `embed corpus` refuses to start for a `tei` model without a passing `parity.json`\n for the same endpoint `/info` (model SHA + dtype). Override with `--skip-parity`, which is\n recorded in the manifest.\n- **API models:** a lighter check, since there's no reference to compare against. It embeds the\n sample twice to confirm the results are deterministic up to ~1e-6 and that the norms are 1.\n\n### 5.5 Length guard\n\n- Before any request, the script counts tokens for every unique text with the **model's own\n tokenizer**, as set by `tokenizer` in the config:\n - `tokenizers` + the pinned `tokenizer.json` for the open models;\n - `tiktoken` for OpenAI;\n - Gemini `countTokens`: a full count is slow and costs API calls, so it covers only texts whose\n Qwen3 count is > 6,000, plus a random sample.\n- It stops with a list of offending `chunk_id`s if any text is over `max_input_tokens`. It **never**\n truncates.\n- The instruction prefix is added before counting for queries. Questions are short, so this only\n matters for correctness.\n- For TEI the server double-checks (`truncate: false` → 422).\n\n### 5.6 Resumable runner\n\n- **Work unit:** a batch of unique texts, packed greedily in `text_id` order under\n `max_inputs` and `max_request_tokens`.\n- **Shard store:**\n - each completed batch is written atomically (temp file + rename) as\n `_shards/<first_text_id>_<n>.npz` with `text_ids` and `vectors`;\n - on restart, the text ids already in shards are skipped. An interrupted run, cold start, or\n network failure loses at most the batches in flight.\n- **Concurrency:** a thread pool of `concurrency` in-flight requests. TEI does the actual batching\n on the GPU, so the client only has to keep it fed.\n- **Validation per batch:** shape = (n, dim), all values finite, norm 1 ± 1e-3 (it renormalizes\n and warns if not), and no all-zero vectors.\n- **`finalize`:**\n - assembles the shards into `vectors.npy` in `text_id` order and checks for complete coverage\n (every unique text exactly once);\n - writes `texts.csv`, `chunk_map.csv.gz`, and the manifest with checksums;\n - deletes `_shards/` only after the checksums are written.\n- **Idempotent:** re-running `corpus` on a finalized model does nothing unless `--overwrite` is\n given.\n\n---\n\n## 6. Release quality requirements\n\n### 6.1 Files in `scripts/embedding/`\n\n```\nscripts/embedding/\n README.md usage for outside users (see 6.3); points to this plan\n embed.py CLI entry point (subcommands below)\n embedding/ small package: config.py, providers/{tei,openai,gemini,fake}.py,\n corpus.py, runner.py, store.py, parity.py, manifest.py, tokens.py,\n costs.py (ledger, endpoint meter, reconciliation; §9)\n models.yaml model registry (§5.2)\n parity_sample.json fixed parity sample ids (§5.4)\n requirements.txt pinned runtime\n requirements-parity.txt optional: sentence-transformers + torch for the reference\n .env.example HF_TOKEN=, OPENAI_API_KEY=, OPENAI_ADMIN_KEY= (optional, §9.4),\n GEMINI_API_KEY=, ENDPOINT_URL_…=\n tests/ pytest, fake provider only (no network, no GPU)\n```\n\n### 6.2 CLI (single entry point with subcommands)\n\n```bash\npython scripts/embedding/embed.py models # list configured models and whether their env vars are set\npython scripts/embedding/embed.py check --model qwen3-emb-4b # connectivity + /info + 1-text embed + config match\npython scripts/embedding/embed.py parity --model qwen3-emb-4b # §5.4 → embeddings/qwen3-emb-4b/parity.json\npython scripts/embedding/embed.py corpus --model qwen3-emb-4b [--input segmented/chunks_all.csv.gz] [--dry-run]\npython scripts/embedding/embed.py queries --model qwen3-emb-4b [--input …questions.json] [--instruction-name default]\npython scripts/embedding/embed.py finalize --model qwen3-emb-4b # (corpus runs finalize automatically at the end)\npython scripts/embedding/embed.py endpoint --model qwen3-emb-4b {status|resume|pause} # optional, §3.6; metered, §9.3\npython scripts/embedding/embed.py costs [summary|add|reconcile --provider openai|import --provider {hf|gemini} FILE] # §9\n```\n\n- **Defaults:** every subcommand works with no options other than `--model`, using the repo's\n default paths.\n- **Help text:** `--help` shows an example for each subcommand.\n- **Errors say what to do**, e.g. \"ENDPOINT_URL_QWEN3_EMB_4B is not set; see README §HF setup\" or\n \"endpoint is paused; run `embed.py endpoint --model … resume`\".\n- **Progress and logs:** a `tqdm` bar with tokens/s and ETA; logs go to\n `embeddings/<slug>/run.log` as well as stderr.\n\n### 6.3 README contents (for release)\n\n1. **What it does**, in one paragraph, and the output format (§4.2) with a 5-line loading example:\n\n ```python\n import numpy as np, pandas as pd\n V = np.load(\"embeddings/jua-4b-mixed/corpus/vectors.npy\", mmap_mode=\"r\")\n texts = pd.read_csv(\"embeddings/jua-4b-mixed/corpus/texts.csv\")\n cmap = pd.read_csv(\"embeddings/jua-4b-mixed/corpus/chunk_map.csv.gz\")\n Q = np.load(\"embeddings/jua-4b-mixed/queries/vectors.npy\"); scores = Q @ V.T\n ```\n\n2. **Install:** a venv plus `pip install -r requirements.txt`, and the optional parity extra.\n3. **Credentials:** copy `.env.example` to `.env`; which variable each provider needs.\n4. **Quick start per provider:** OpenAI, Gemini, and open models through an HF endpoint (a short\n version of §3 with a link to the full guide).\n5. **Reproducing the paper's runs:** the exact commands, the model revisions, and where the\n released vectors are on the Hub, so people can use the vectors without re-embedding.\n6. **Adding a model:** a YAML entry and nothing else.\n7. **Cost and time table** from the actual runs, generated by `embed.py costs summary --markdown` (§9.5).\n8. **License** (same as the dataset release) and a citation block.\n\n### 6.4 Code quality\n\n- Type hints; each module has a docstring stating its responsibility. Keep functions small and use\n no global state except the loaded config.\n- **Tests** with pytest and the `fake` provider:\n - dedup and chunk map (including an equal-hash/different-text failure);\n - shard resume after a simulated crash;\n - `finalize` coverage and checksums;\n - template rendering (spaces and newlines are exact);\n - length guard rejection;\n - manifest completeness;\n - cost ledger: token and replica-minute pricing, and the endpoint meter with a fake status\n sequence;\n - CLI `--dry-run`.\n- **No secrets in logs or manifests.** Tokens are read from the environment, and URLs are logged\n without query strings.\n- **Deterministic output:** the same input + the same served vectors give byte-identical\n `texts.csv`, `chunk_map.csv.gz` (gzip with `mtime=0`, as in the segmentation step) and\n manifests, apart from the timestamps and timings in the `run` section.\n\n---\n\n## 7. Validation after each model run\n\nThe following checks go into the model's manifest and the execution log:\n\n1. Coverage: every one of the 84,568 unique texts has exactly one vector, and all 87,702 chunk ids\n map to a text.\n2. Norms are 1 ± 1e-3, values are finite, and there are no duplicate vectors for different texts\n (except the exact near-duplicates found by a `cos > 0.9999` scan, which should be reported).\n3. **Sanity retrieval:** for 20 questions whose gold references are known\n (`formatted_references` in the questions file), check whether the referenced article appears\n in the top-100. This is a quick smoke signal, not the evaluation; it catches swapped\n query/document templates or a broken pooling.\n4. Cross-model agreement: Spearman correlation of the query-chunk scores between models on the\n parity sample. It is only reported, not used as a gate.\n\n---\n\n## 8. Open decisions (defaults chosen; confirm before running)\n\n| # | Question | Default in this plan | Cost of changing later |\n|---|---|---|---|\n| D1 | Query instruction (explained in §8.1) | One shared IRPF-specific English instruction (§4.3); model defaults kept as alternatives | Low: only 715 queries |\n| D2 | OpenAI model | **Decided 2026-09-25:** both `text-embedding-3-large` (~$3.5) and `-small` (~$0.5) | — |\n| D3 | Gemini document `title` (explained in §8.2) | `title: none`, since the chunk text already starts with Epígrafe + Ementa. The alternative, the chunk's `Rotulo` or document epígrafe, would add information to Gemini that other models don't get | **High**: re-embedding the corpus |\n| D4 | Query text | `question_text` only (not `question_summary`) | Low |\n| D5 | Full native dimensions vs reduced (MRL) | Native for all models | Low: truncation + renormalization can be done later from stored vectors, for the MRL-trained models |\n| D6 | Where to release the vectors | HF dataset repo (float32, optional float16 copy) | Low |\n| D7 | Parity thresholds | median ≥ 0.999, min ≥ 0.995, top-1 identical | Low |\n| D8 | Query-side prompt also for OpenAI | none (the model has no instruction format) | Low |\n\n### 8.1 D1 explained: what the query instruction is\n\nThe three open models (jua-4B-mixed, Qwen3-Embedding-4B, inf-retriever-v1) are **instruction-tuned\nembedders**. A query is encoded together with a short *task description* that tells the model what\nkind of match to look for. Documents are encoded **without** one; their configured document prompt\nis `\"\"`. For question 001, the string actually sent to the model is:\n\n```\nInstruct: Given a question about Brazilian personal income tax (IRPF), retrieve the legal provisions that answer it\nQuery: Quem está obrigado a apresentar a Declaração de Ajuste Anual relativa ao exercício de 2024, ano-calendário de 2023?\n```\n\nThe same question can be embedded differently depending on the task: finding passages that\n**answer** it, finding **similar questions**, or classifying it. These models were trained on many\nsuch instructions, and Qwen reports about a 1–5 % gain from a task-specific instruction over a\ngeneric one. Candidates:\n\n| Name in `models.yaml` | Task description | Source |\n|---|---|---|\n| `web_search` | `Given a web search query, retrieve relevant passages that answer the query` | Default prompt of Qwen3-Embedding-4B, jua-4B-mixed and inf-retriever-v1 (`config_sentence_transformers.json`) |\n| `jua_legal` | `Given a Brazilian legal search query, retrieve relevant legal passages or documents.` | Usage example on the jua-4B-mixed model card |\n| **`irpf` (default)** | `Given a question about Brazilian personal income tax (IRPF), retrieve the legal provisions that answer it` | Written for this task. It is in English because Qwen recommends English instructions even for non-English data |\n\n**Why one shared instruction:** the three open models get the same task description, so\ndifferences between them come from the models and not from the prompts.\n\n**The paid models have nothing equivalent:**\n- OpenAI has no instruction mechanism, so the question is sent as it is.\n- Gemini selects the task with a **fixed task name** (`task: search result | query: …`) rather\n than free text.\n\n**Cost of changing:** it is cheap, because documents never carry the instruction. Changing it\nre-embeds only the 715 questions, so an ablation over `web_search` / `jua_legal` / `irpf` costs\nalmost nothing (`embed.py queries --model … --instruction-name …`). The name used goes in the\nquery manifest.\n\n### 8.2 D3 explained: why the document title only concerns Gemini\n\nEach model expects documents in a particular input format:\n\n| Model | Document input format |\n|---|---|\n| jua-4B-mixed, Qwen3-Embedding-4B, inf-retriever-v1 | Raw text (document prompt `\"\"` in their configs) |\n| text-embedding-3-small / -large | Raw text (OpenAI has no prompt format) |\n| **gemini-embedding-2** | **`title: {title} \\| text: {content}`**, the format Google trained it with |\n\nOnly Gemini's format has a **title slot**, so the question of what to put there exists only for\nGemini. The options:\n\n- **`title: none`** (Google's convention when there is no title). Gemini then sees the same chunk\n text as every other model.\n- **A real title**, such as the document's epígrafe or the chunk's `Rotulo`. Gemini would then get\n information the other four models don't, which biases the comparison. Evening it out would mean\n adding the title to every model's text, which changes the chunk text itself and breaks rule 1\n of §1.4.\n\nA title would also be **redundant**, because every chunk already starts with its document's\nmetadata (strategy doc §6, item 1), e.g.:\n\n```\n[ DECRETO Nº 56.435, DE 8 DE JUNHO DE 1965 | Promulga a Convenção de Viena sôbre Relações Diplomáticas. … ] …\n[ CONSTITUICAO Nº 1, DE 5 DE OUTUBRO DE 1988 ] Art. 5º Todos são iguais perante a lei, …\n```\n\n**Default: `title: none`.** This decision changes the **document** vectors, so changing it later\nmeans paying to embed the whole corpus again. Confirm it before the Gemini run.\n\n**Data-quality item found while checking this (2026-09-25), now fixed:** the Constitution chunks'\nmetadata read `CONSTITUICAO Nº 1, DE 5 DE OUTUBRO DE 1988`, an epígrafe the statutory parser built\nbecause it was run without a document number. Its URN had the same cause (`…;1` instead of the\nlinker's `…;1988`). Both were corrected in the LexML XML; the epígrafe is now **`Constituição da\nRepública Federativa do Brasil`**. The same bug affected four MPs (2.158-35, 2.159-70,\n2.189-49, 2.228-1). All five documents were then fixed at the source, in the statutory parser, and\nre-parsed. Details, the diffs and the checks are in\n`docs/20260925_125514_constitution_metadata_fix.md` (§5).\n\n---\n\n## 9. Recording embedding costs\n\n**Goal:** a versioned record of what each model cost, split by activity (smoke test, parity,\ncorpus, queries, re-runs). It is filled **automatically** by the script, then **reconciled** with\neach provider's own billing, so the paper can report both the estimate and the amount actually\ncharged.\n\n### 9.1 The ledger: `embeddings/costs.csv` (versioned in git)\n\nOne row per billable activity, appended by the script and never rewritten. Reconciliation adds\nnew rows that refer to the originals.\n\n| Column | Meaning |\n|---|---|\n| `row_id` | UUID |\n| `timestamp_start`, `timestamp_end` | UTC, ISO 8601 |\n| `model_slug` | e.g. `jua-4b-mixed` |\n| `activity` | `smoke` / `parity` / `parity_reference` / `corpus` / `queries` / `idle` / `other` |\n| `run_id` | links to the manifest of the run (§4.4) |\n| `provider` | `hf_endpoint` / `openai` / `gemini` / `hf_space` / `colab` / `other` |\n| `billing_unit` | `tokens` or `replica_minutes` |\n| `quantity` | number of tokens or replica-minutes |\n| `unit_price_usd` | price per 1M tokens or per hour, copied from `models.yaml` |\n| `price_checked` | the date the price in the config was checked |\n| `usd` | `quantity × price` |\n| `source` | `auto_estimate` (script), `provider_reported` (usage returned by the API or read from the provider's usage/cost API), `invoice` (entered by hand from the billing page) |\n| `reconciles` | for reconciliation rows: the `row_id`s they cover |\n| `notes` | free text, e.g. \"first attempt, OOM, restarted\" |\n\nFailed or repeated runs are recorded too. The paper should report the actual cost of the\nexperiment, not only the successful run.\n\n### 9.2 API models (OpenAI, Gemini): tokens × price, automatic\n\n- **OpenAI:**\n - every `embeddings.create` response has `usage.prompt_tokens` / `usage.total_tokens`. The\n provider **adds them up exactly**, and the ledger row's quantity is that sum\n (`source=provider_reported`);\n - the `tiktoken` pre-count (§5.5) is kept in the manifest as a cross-check. The two should\n match.\n- **Gemini:**\n - the REST `embedContent` / `batchEmbedContents` response may include\n `usageMetadata.promptTokenCount`, but the `google-genai` SDK currently hides it\n (`EmbedContentResponse` exposes only `embeddings` and `metadata`). The provider reads it from\n the raw HTTP response if it's there;\n - otherwise it calls **`countTokens`** (no charge, but rate-limited) on every text actually sent,\n concurrently, and records `source=auto_estimate`;\n - the Batch API mode (§5.3) uses the 50 % price.\n- **Prices** come from `models.yaml` (`price.usd_per_million_tokens` + `checked`). The script\n **refuses to run a paid model whose price is missing** unless given `--price-unknown`, which\n writes `usd` as empty. The Gemini price must be filled in from\n <https://ai.google.dev/gemini-api/docs/pricing> before its run; this plan doesn't record it.\n- `--dry-run` prints the expected cost from the pre-counts before anything is sent.\n\n### 9.3 HF Inference Endpoints: replica-minutes × hourly price, automatic\n\nHF bills the **time a replica is up** (per minute), not tokens. That includes initialization,\ncold starts and the idle time before scale-to-zero. HF had no documented billing API on\n2026-09-25, so the script **meters the endpoint itself**:\n\n1. **Endpoint meter.** Whenever the script touches an endpoint (`check`, `parity`, `corpus`,\n `queries`, `endpoint resume`), a background thread polls\n `huggingface_hub.get_inference_endpoint(name).fetch()` every 60 s. It records the status and\n the number of running replicas (`ep.raw[\"status\"]`, which includes the ready/target replica\n counts) into `embeddings/<slug>/endpoint_meter.jsonl`. The endpoint therefore needs\n `endpoint_name` in `models.yaml` and a token with *Manage Inference Endpoints* permission\n (§3.1), which is needed only for reading the status here.\n2. **When the script's work ends**, the meter:\n - if the script **paused** the endpoint (`--pause-after`, **the default for `corpus`**): stops\n when the status reaches `paused`, so the interval is exact;\n - if the endpoint is left running: adds the **scale-to-zero timeout** from the endpoint's\n config (15 min in §3.3) as the expected idle tail, and marks that part as\n `activity=idle, source=auto_estimate`.\n3. **Ledger rows:**\n - `quantity` = Σ(running replicas × minutes), rounded up to whole minutes;\n - `unit_price_usd` = the instance's hourly price from `models.yaml`;\n - the instance type is read from the endpoint (`ep.raw[\"compute\"]`) and checked against the\n config, and a mismatch is a warning.\n4. **Manual use of the endpoint** outside the script (UI playground, curl, leaving it running) is\n not metered. Use `embed.py costs add --model … --activity other --replica-minutes N --notes …`,\n or rely on reconciliation (§9.4) to catch it.\n5. **Cross-check:** the endpoint's **Analytics → Running Replicas / Timeline** view (§3.5) shows\n the same intervals.\n\n### 9.4 Reconciliation with actual billing\n\nEstimates are good to a few percent. The amounts actually charged come from the providers. For\nthis to work, **each provider's charges must be attributable to this experiment only**:\n\n| Provider | Isolation (set up before the first run) | Where the actual cost is | Automation |\n|---|---|---|---|\n| OpenAI | A dedicated **project** (e.g. `br-taxqa-r-embeddings`) with its own API key, used for nothing else | Costs API `GET /v1/organization/costs?start_time=…&group_by=project_id,line_item` (daily buckets); needs an **Admin key** (`OPENAI_ADMIN_KEY`, created by an org owner) | **Automatic:** `embed.py costs reconcile --provider openai --since 2026-09-25` fetches the daily costs of the project and appends `source=provider_reported` rows per day and line item, with `reconciles` set to the matching estimate rows |\n| Gemini | A dedicated **Google Cloud project** for the Gemini API key (AI Studio → API keys → create key in a new project) | Google Cloud Console → Billing → Reports, filtered by that project, service \"Gemini API\", with SKUs per model | **Manual:** export the report as CSV, then run `embed.py costs import --provider gemini report.csv`. It is also possible with BigQuery billing export, but that's not worth setting up for a one-off experiment |\n| HF Inference Endpoints | Only this experiment's endpoints in the account or org during the runs; if not possible, filter by endpoint name | <https://huggingface.co/settings/billing> (or the org's billing page): usage per endpoint | **Manual:** copy per-endpoint amounts, or download the usage CSV if the page offers it, then run `embed.py costs import --provider hf FILE` (or `costs add --source invoice`) |\n| Parity reference (HF Space / Colab, §5.4) | — | The Space's billing line, or the Colab compute units used | **Manual:** `embed.py costs add --activity parity_reference …` |\n\n- **Timing:** reconcile **a day or two after** the runs, since billing data lags; OpenAI's daily\n buckets fill in within about a day.\n- `costs summary` then shows estimate vs actual per model, and flags differences above 10 % for a\n note in the execution log.\n\n### 9.5 Reporting\n\n`embed.py costs summary [--markdown] [--by model|activity|provider]` produces:\n\n| Model | Corpus tokens | Corpus cost (est.) | Queries | Parity + smoke | Idle / failed | **Total est.** | **Total actual** | Wall time |\n|---|---|---|---|---|---|---|---|---|\n\n- The Markdown table goes into the execution log and the release README (§6.3 item 7).\n- The per-model total also goes into each corpus manifest (§4.4), so the released vectors carry\n their cost.\n- **Also report tokens per model.** A model with a different tokenizer (e.g. `cl100k_base` vs\n Qwen) processes a different number of tokens for the same corpus, which explains part of any\n cost difference.\n\n### 9.6 Checklist per model run\n\n1. Before: price in `models.yaml` checked (date), dedicated project/key (OpenAI, Gemini), and\n `endpoint_name` set (HF).\n2. `embed.py corpus --model … --dry-run` gives the expected cost. Continue only if it's acceptable.\n3. Run. The ledger rows are appended automatically, and HF endpoints are paused at the end by\n default.\n4. `embed.py costs summary --model …`, then note anything unusual (retries, restarts) with\n `costs add --notes` or in the execution log.\n5. After 1–2 days, reconcile (§9.4) and update the execution log with the actual amounts.\n\n---\n\n## 10. Implementation notes (2026-09-25)\n\n`scripts/embedding/` follows §5–§6 with these differences, all recorded here so the plan stays the\nreference:\n\n- **Scope.** Providers `tei` (with the `openai_compat` mode) and `fake`. `openai` and `gemini`,\n and the token-priced ledger rows, `costs reconcile` and `costs import` (§9.2, §9.4) are deferred\n until those models are run. `models.yaml` has entries for jua, Qwen3 and inf-retriever.\n- **Token counting** lives in the config (`tokenizer` spec) rather than in the `Provider`\n interface. For TEI, `check` compares the client counts with the server's `/tokenize` on three\n probes. With jua's `tokenizer.json`, the corpus is 26,319,851 tokens, max **8,120** (the\n `<|endoftext|>` the server appends is counted), 1,323 requests of ≤ 64 inputs / 32,768 tokens.\n- **Queries go to `queries/<instruction_name>/`**, not `queries/`, so the instruction ablation\n (§8.1) keeps each variant.\n- **Shards live next to their output** (`corpus/_shards/`, `queries/<name>/_shards/`), with a\n `state.json` holding the run fingerprint (template, instruction, input SHA-256, server\n fingerprint). A resume with a different fingerprint is refused.\n- **Server fingerprint** (parity gate, §5.4): with the custom TEI container, `/info` reports\n `model_id: /repository` and no SHA, so the fingerprint also takes the endpoint's own\n repository, revision and image from the endpoint API (`ep.raw`), plus TEI's dtype, version and\n pooling.\n- **Endpoint URL**: read from the endpoint API when `ENDPOINT_URL_…` is unset.\n- **Parity reference**: sentence-transformers 6.1.0, model loaded with `model_kwargs={\"dtype\":\n torch.bfloat16}` (transformers 5 renamed `torch_dtype`); the pooled output is cast to float32\n and normalized there, since normalizing in bf16 leaves norms at 1 ± 6e-4. It is cached in\n `embeddings/<model>/parity_reference.npz` (not versioned), keyed by model, revision and the\n exact strings.\n- **Parity sample** (`scripts/embedding/parity_sample.json`, versioned): the 5 longest texts\n (8,061–8,119 Qwen3 tokens), then 59 texts round-robin over the 16 `Tipo`s at increasing length\n quantiles (median 330 tokens), and questions 001, 045, …, 671 (every ~45th). No RNG.\n- **Extra outputs**: `check.json` (smoke test result, versioned), `run.log` (not versioned). The\n `.gitignore` keeps only manifests, `check.json`, `parity.json`, `endpoint_meter.jsonl` and\n `costs.csv` under `embeddings/`.\n- **Tests**: 26 pytest tests with the fake provider (no network or GPU), covering the §6.4 list.\n\n","20260925_125514_constitution_metadata_fix.md":"# Document Metadata Fix (Constitution + 4 MPs: epígrafe + URN) and Segmentation Re-runs\n\n**Generated:** 2026-09-25 12:55:14 (local time, from `date +%Y%m%d_%H%M%S`)\n**Found while writing:** `docs/20260925_122058_embedding_implementation_plan.md` §8.2 (the Gemini\ndocument-title decision). The plan's step 0 requires this fix before any embedding run.\n**Affects:** `lexml/articulados/constituição_1988_19881005.xml` and every segmentation output\nderived from it. Segmentation design: `docs/20260924_123747_segmentation_implementation_plan.md`;\nprevious results: `docs/20260924_184339_segmentation_results.md`.\n\n**Update, 2026-09-25 afternoon:** the manual edit of §2 was replaced by a **parser fix**, which\nalso fixed four MPs with the same bug. The parser change is documented in\n`../lexml-parser-projeto-lei/work_history/20260925_130918_numero_complemento_and_constituicao_epigrafe_fix.md`,\nand the resulting re-parse and second segmentation run are in §5 below. §1–§4 describe the first,\nmanual step and remain as a record.\n\n---\n\n## 1. Problem\n\nThe Constitution's LexML file had two **synthesized** metadata values:\n\n| Element | Before | Problem |\n|---|---|---|\n| `ParteInicial/Epigrafe` | `CONSTITUICAO Nº 1, DE 5 DE OUTUBRO DE 1988 ` | Not the document's title: no accent, and a \"Nº 1\" the Constitution doesn't have |\n| `Metadado/Identificacao/@URN` | `urn:lex:br:federal:constituicao:1988-10-05;1` | `lexml-linker` writes the Constitution as `…:1988-10-05;1988` (the standard LexML URN). It appears **1,303 times** in `lexml/`, and `;1` appeared only here |\n\n**Origin:** the statutory parser. `constituição_1988_19881005.err.log` shows it was run with\n`-t constituicao --data 1988-10-05` and **no number**. It then built the URN and the epígrafe\nfrom type, number (default 1) and date. The source `.docx` has no such epígrafe.\n\n**Why it matters:**\n\n- **Epígrafe:** segmentation copies it into the metadata prefix of every chunk (strategy doc §6,\n item 1). All **3,018** Constitution chunks started with `[ CONSTITUICAO Nº 1, DE 5 DE OUTUBRO\n DE 1988 ]`, which is wrong text in what gets embedded.\n- **URN:** the chunks' `urn` / `doc_urn` (`<doc URN>!<element id>`) are built from\n `Identificacao/@URN`. They could not match the linker's references to the Constitution\n (`…;1988!art5_…`), so gold references to the Constitution could not be matched to its chunks.\n\n## 2. Fix (applied 2026-09-25)\n\nTwo lines were changed by hand in `lexml/articulados/constituição_1988_19881005.xml`. There is no\ncode change; the XML stays the single source of truth for segmentation.\n\n```diff\n- <Identificacao URN=\"urn:lex:br:federal:constituicao:1988-10-05;1\"/>\n+ <Identificacao URN=\"urn:lex:br:federal:constituicao:1988-10-05;1988\"/>\n- <Epigrafe id=\"epigrafe\">CONSTITUICAO Nº 1, DE 5 DE OUTUBRO DE 1988 </Epigrafe>\n+ <Epigrafe id=\"epigrafe\">Constituição da República Federativa do Brasil</Epigrafe>\n```\n\n- The title is the one decided on 2026-09-25: **\"Constituição da República Federativa do Brasil\"**.\n The canonical list in `../br-taxqa-document-fetcher/output_canonical/canonical_referred_documents.json`\n (index 59) uses \"Constituição da República Federativa do Brasil de 1988\".\n- The XML has no `Ementa` for the Constitution, so the chunk prefix is only the title:\n `[ Constituição da República Federativa do Brasil ] Art. 5º …`.\n- **Re-parse warning (resolved):** re-running the old parser command would undo this edit.\n **Resolved by §5**: the fixed parser now produces exactly this XML, byte for byte.\n\n## 3. Segmentation re-run\n\n```bash\n.venv/bin/python scripts/segmentation/segment_all.py --jobs 16 --overwrite\n```\n\nThe run took 92 s and **all validation checks passed** (`csv_schema, non_empty, texto_sha256,\nchunk_id_unique, provenance, intervals, coverage, cap, split_complete, text_coverage,\ngrouping_limit`). The run was made on commit `24f450e` with the XML edit uncommitted, so\n`run_info.json` records `dirty: true` with the XML as the only dirty file.\n\n### 3.1 What changed (compared with the frozen output of commit `24f450e`)\n\n| Item | Before | After |\n|---|---|---|\n| `chunks_all.csv` rows | 87,704 | **87,703** |\n| Constitution rows | 3,018 | 3,017 |\n| Unique texts (`texto_sha256` / full `Texto`) | 84,569 | 84,569 |\n| Rows per strategy S1 / S2 / S3 | 26,252 / 82,644 / 87,704 | 26,251 / 82,643 / 87,703 |\n| ART/DSP units split | 656 → 1,752 parts | 655 → 1,750 parts |\n| Qwen3 tokens total / p90 / max | 27,018,900 / 540 / 8,119 | 26,976,581 / 539 / 8,119 |\n| cl100k tokens total / max | 25,761,563 / 7,895 | 25,725,279 / 7,895 |\n| Rows outside the Constitution | — | **identical** (every column, same order) |\n| `groupings_over_limit.csv` | — | same rows; only the Constitution URNs changed |\n\n- **Every Constitution row changed** in `Texto`, `texto_sha256`, the token counts, `urn` and\n `doc_urn`. The new prefix is about 14 Qwen3 tokens shorter.\n- **The one row fewer is Art. 144.** Before, at 876 + 230 tokens, it was split into `parte 1/2`\n and `parte 2/2`. With the shorter prefix the whole article is **1,014 tokens**, below the\n 1,024 cap, so it is now a single `ART` row. This is the cap rule working as designed, not a\n regression.\n- `chunk_id`s of Constitution rows after Art. 144 shift by one sequence number\n (e.g. `constituição_1988_19881005#1318` no longer exists). Nothing has been built on the old\n ids yet (no embeddings), so no mapping is needed.\n\n### 3.2 Output files changed\n\n`segmented/chunks_all.csv(.gz)`, `segmented/statutory/constituição_1988_19881005.{csv,prov.jsonl}`,\n`segmented/groupings_over_limit.csv`, `segmented/run_info.json`,\n`segmented/segmentation_report.{md,json}`. New `chunks_all.csv.gz` SHA-256:\n`c296dc219bb396a8bf9509c3d60db07addf4720c44f5d53b81a33ce940e168d8`\n(`chunks_all.csv`: `5add6d424fd2e6d224623d2b3038b55591102f2a301d367b6dfef116d47a1eba`).\n\n### 3.3 Gemini `countTokens` check not re-run\n\nThe report's Gemini sample check ran in the previous frozen output. This time it shows\n`status: not run` because no `GEMINI_API_KEY` / `GOOGLE_API_KEY` was set. Chunk text only got\n**shorter**, so the earlier result (max 7,253 Gemini tokens in the largest-chunk sample, none over\n8,192) still holds. To restore the check in the report, run the validator alone with the key set:\n\n```bash\nGEMINI_API_KEY=… .venv/bin/python scripts/segmentation/validate_segments.py\n```\n\n## 4. Follow-ups (from the manual step; see §5 for their outcome)\n\n- **Commit** the XML fix together with the re-frozen outputs. For a clean `run_info.json`\n (`dirty: false`), commit the XML first, then re-run `segment_all.py` (outputs are\n deterministic) and commit the outputs.\n- **Other documents with the same bug.** A first check for `;1` URNs found `mp_2228-1_20010906`.\n (`adi_rfb_1_20160118` is really nº 1, so it is correct.) Comparing every parse command's `-n`\n with the filename number then found **four MPs** in total. All were fixed in §5.\n\n## 5. Parser fix, re-parse and second segmentation run (2026-09-25)\n\n### 5.1 Root cause and fix (statutory parser, `../lexml-parser-projeto-lei`)\n\n| Document | Parse command before | Metadata before | After |\n|---|---|---|---|\n| `constituição_1988_19881005` | no `-n` (parser default 1) | `;1` / `CONSTITUICAO Nº 1, DE 5 DE OUTUBRO DE 1988` | `;1988` / `Constituição da República Federativa do Brasil` |\n| `mp_2158-35_20010824` | `-n 35` | `;35` / `Nº 35` | `;2158-35` / `MEDIDA PROVISÓRIA Nº 2.158-35, DE 24 DE AGOSTO DE 2001` |\n| `mp_2159-70_20010824` | `-n 70` | `;70` / `Nº 70` | `;2159-70` / `Nº 2.159-70` |\n| `mp_2189-49_20010823` | `-n 49` | `;49` / `Nº 49` | `;2189-49` / `Nº 2.189-49` |\n| `mp_2228-1_20010906` | `-n 1` | `;1` / `Nº 1` | `;2228-1` / `Nº 2.228-1` |\n\n- **Batch driver (`scripts/batch_parse.py`):**\n - it could not read a number with a complement (`2.228-1`), neither from the DOCX epígrafe nor\n from the filename, where `2228` was taken as a year. It now passes\n `-n 2228 --complemento 1`;\n - a constitution gets its year as its number (`-n 1988`).\n- **Scala (`DocumentProfileOverride`):** it dropped the profiles' own epígrafe templates. The\n registered Constitution template (`Constituição da República Federativa do Brasil`, with its\n trailing period removed) is now used.\n\n### 5.2 Re-parse\n\n- The full `original/articulados` was re-parsed with the fixed parser: 225 converted, 0 failed.\n- **42 of 468 XML files changed** and were promoted into `lexml/articulados`. The other 426 are\n byte-identical, so `lexml/articulados` now equals the fixed parser's output exactly. The\n changes:\n - **the 4 MPs** (7 files with their annexes): URN and epígrafe as in the table;\n - **the Constitution:** identical to the manual edit of §2; only its `.err.log` header is new;\n - **34 `decreto_*`:** the epígrafe lost a trailing space. The chunk text is unchanged because\n segmentation normalizes whitespace;\n - **`decreto_legislativo_92_19751105`:** the epígrafe is now `DECRETO LEGISLATIVO Nº 92, DE 1975`\n (was `…, DE 5 DE NOVEMBRO DE 1975`), which is **exactly the title in its DOCX**.\n\n### 5.3 Segmentation re-run\n\n```bash\n.venv/bin/python scripts/segmentation/segment_all.py --jobs 16 --overwrite\n```\n\nThe run took 89 s and all validation checks passed. The comparison is with the output of §3:\n\n| Item | After §3 (Constitution only) | **After §5** |\n|---|---|---|\n| `chunks_all.csv` rows | 87,703 | **87,702** |\n| Unique texts | 84,569 | **84,568** |\n| Rows per strategy S1 / S2 / S3 | 26,251 / 82,643 / 87,703 | **26,250 / 82,642 / 87,702** |\n| Qwen3 tokens total / max | 26,976,581 / 8,119 | **26,979,867 / 8,119** |\n| cl100k tokens total / max | 25,725,279 / 7,895 | **25,726,989 / 7,895** |\n| Files whose rows changed | — | 9 (listed below); all other files identical |\n\n- **Changed files:**\n - `mp_2158-35` (+ `anexo1`), `mp_2159-70`, `mp_2189-49`, `mp_2228-1` (+ `anexo1`, `anexo2`): new\n `Texto` prefix, `texto_sha256`, token counts, `urn` / `doc_urn` / `anexo_urn`;\n - `decreto_legislativo_92` (+ `anexo1`): new `Texto` prefix (the shorter epígrafe).\n- **The one row fewer:** in `mp_2228-1_20010906.anexo1`, the third `Art. 33.` got a slightly\n longer prefix, and the oversize-article splitter now packs it into **2 parts\n (1,021 + 1,019 tokens) instead of 3 (160 + 1,021 + 1,002)**. It is still under the cap.\n- **References now match:**\n\n | `doc_urn` | Chunks | Linker references in `lexml/` |\n |---|---|---|\n | `…:2001-08-24;2158-35` | 295 | 148 |\n | `…:2001-08-24;2159-70` | 27 | 4 |\n | `…:2001-08-23;2189-49` | 54 | 25 |\n | `…:2001-09-06;2228-1` | 412 | 79 |\n | `…constituicao:1988-10-05;1988` | 3,017 | 1,303 |\n\n- **Checksums:** `chunks_all.csv.gz`\n `f3db09046bb475bfcab1dfe84f4805a40a8fcd2629f252577c3aa492d1855f9b`, `chunks_all.csv`\n `fcacf9a46545f15a3e5cc682ae7d9b057f80c395944e523142d9dfb8055dde37`.\n- `run_info.json` is again `dirty: true` (uncommitted `lexml/` changes), and the Gemini\n `countTokens` check was again not run (§3.3).\n\n### 5.4 Remaining steps\n\n1. **Commit**, in this order:\n - `../lexml-parser-projeto-lei`: the parser fix (code, tests, `CLAUDE.md`, work_history note);\n - here: `lexml/articulados` (42 XML + 40 `.err.log`) and the docs;\n - then re-run `segment_all.py` (deterministic) so `run_info.json` is clean, and commit\n `segmented/`.\n2. Optionally re-run the Gemini check:\n `GEMINI_API_KEY=\"$(cat ~/keys/gemini_api_key)\" .venv/bin/python scripts/segmentation/validate_segments.py`.\n\n### 5.5 Outcome of §5.4 (2026-09-25)\n\n- **Step 1 (commits).** The parser fix was committed in `../lexml-parser-projeto-lei`\n (`ebf6567`) and the re-parsed `lexml/articulados` here (`ecd68e5`). `segment_all.py` was then\n re-run on `ecd68e5` with clean inputs: 99 s, all validation checks passed, and\n `run_info.json` now records **`dirty: false`**. The output is **byte-identical** to §5.3\n (same `chunks_all.csv.gz` and `chunks_all.csv` SHA-256), confirming the run is deterministic.\n `segmented/` and these docs were committed together.\n- **Step 2 (Gemini `countTokens`, `gemini-embedding-2`).** Re-run with the key; 0 errors, all\n checks still OK, and the result is now in `segmentation_report.{md,json}`:\n\n | Sample | n | Gemini > reference | Gemini/reference p50 / p99 / max | Max Gemini tokens | Over 8,192 |\n |---|---|---|---|---|---|\n | Random | 500 | 2 (max excess 61) | 0.886 / 0.960 / 1.101 | 6,220 | 0 |\n | 100 largest | 100 | 0 | 0.878 / 0.926 / 0.929 | 7,253 | 0 |\n\n The largest-chunk maximum (7,253) is the same as before the fix, as §3.3 expected.\n","20260926_092524_parity_check_jua_4b_mixed.md":"# Parity check: `jua-4b-mixed` (TEI endpoint vs sentence-transformers reference)\n\n**Date:** 2026-09-26 (run finished 03:14 UTC)\n**Plan reference:** `docs/20260925_122058_embedding_implementation_plan.md` §5.4 (method), §3.8 (fallbacks)\n**Result file:** `embeddings/jua-4b-mixed/parity.json` (versioned)\n**Verdict:** **PASSED** on all three thresholds (D7). The endpoint can be used for the corpus run.\n\n## 1. What was compared\n\n| Side | Setup |\n|---|---|\n| **Served** | HF Inference Endpoint `jua-4b-mixed-bgc` (L4, custom container `ghcr.io/huggingface/text-embeddings-inference:89-1.9.4`), repository `ufca-llms/jua-4B-mixed` @ `57f491c1718171c0ad71d723c4f6b2030684c4eb`, TEI dtype **float16**, pooling `last_token`, `AUTO_TRUNCATE=false` |\n| **Reference** | sentence-transformers 6.1.0, transformers 5.17.0, torch 2.11.0+cpu, same model and revision loaded in **bfloat16** on CPU (i7-12700F, no native bf16), pooled output cast to float32 and L2-normalized |\n\n- **Sample:** `scripts/embedding/parity_sample.json`: 64 corpus texts (the 5 longest, 8,061–8,119\n Qwen3 tokens, and 59 spread over the 16 `Tipo`s by length) plus 16 queries (001, 045, …, 671).\n- **Query prompt:** instruction `irpf` (the default, D1) with jua's template\n `Instruct: {instruction}\\nQuery: {text}`. Documents are sent as they are.\n- Both sides receive exactly the same strings, with the templates already applied.\n\n## 2. Results\n\n| Metric | Value | Threshold |\n|---|---|---|\n| Cosine served↔reference, median (80 items) | **0.99979** | ≥ 0.999 |\n| Cosine, minimum | **0.99919** | ≥ 0.995 |\n| Cosine, p1 | 0.99928 | — |\n| Cosine, min over the 64 texts / 16 queries | 0.99919 / 0.99976 | — |\n| Top-1 agreement (16 queries × 64 texts) | **16/16** | all |\n| Kendall τ of the full ranking, min / median | 0.978 / 0.990 | reported only |\n\n- **Where the gap is:** the lowest cosines are on the long chunks. Three of the five ~8k-token texts\n are among the four lowest (`ada0911a5dca724f` 0.99919, `4d415d8efbaac288` 0.99930,\n `be45a84194816150` 0.99948). This fits fp16 (server) vs bf16 (reference) rounding building up\n over long sequences. Queries, which are short, all score ≥ 0.99976.\n- **Ranking changes:** Kendall τ < 1 comes from swaps between texts with nearly equal scores. The\n top-1 text is the same for every query.\n- **Conclusion:** fp16 serving in TEI reproduces the published bf16 checkpoint closely, so neither\n `DTYPE=float32` nor the vLLM fallback (§3.8) is needed for this model.\n\n## 3. Execution notes\n\n- **Environment:** a fresh machine; a Python 3.12 `.venv` was created with conda and filled from\n `requirements-parity.txt`, with the CPU-only torch wheel. The 26 tests passed before the run.\n- **Commands:**\n ```bash\n .venv/bin/python scripts/embedding/embed.py parity --model jua-4b-mixed --reference-only # local CPU\n .venv/bin/python scripts/embedding/embed.py parity --model jua-4b-mixed --resume --pause-after\n ```\n- **Reference time:** 2 h 11 min on CPU for 80 texts. Nearly all of it went to the 5 long texts,\n at about 12 min each; sentence-transformers encodes the longest first. The vectors are cached in\n `embeddings/jua-4b-mixed/parity_reference.npz` plus a `.json`. They are **not versioned**; keep\n them to avoid recomputing.\n- **Served side:** the endpoint was resumed (running in 45 s), the 80 embeddings took about 25 s,\n and the endpoint was then paused. It was metered at **2 replica-minutes ≈ $0.03** in\n `embeddings/costs.csv` (run `20260926T031250-04e63b`). The CPU reference has no cost row.\n- **Gate:** `parity.json` stores the server fingerprint (repository, revision, image, TEI version,\n dtype, pooling). `embed.py corpus` will accept this endpoint without `--skip-parity` as long as\n that fingerprint does not change.\n- **Earlier query run:** the queries (`embeddings/jua-4b-mixed/queries/irpf/`, 2026-09-25) were\n embedded with `--skip-parity` before this check, and their manifest records the gate as skipped.\n They came from the same server configuration that now passes; re-run `queries` (≈ $0.05) if the\n manifest should show a pass.\n","20260926_112714_gold_answer_nuggetization_plan.md":"# Gold-Answer Nuggetization and Nugget-Based Answer Evaluation — Plan\n\n**Generated:** 2026-09-26 11:27:14 (local time, from `date +%Y%m%d_%H%M%S`)\n**Status:** plan only. Nothing has been implemented or run.\n**Superseded by** `docs/20261011_224049_gold_answer_nuggetization_plan_v2.md` (2026-10-11).\n**Goal:** turn the 715 gold answers of BR-TaxQA-R into **legal nuggets** (short, self-contained,\natomic statements), and define how the answers of the RAG aggregator LLM are scored against them.\nThe segmentation experiment (`docs/20260923_193852_segmentation_strategies_for_rag_experiments.md`)\nneeds this to compare S1 / S2 / S3.\n**Deliverables:** code in `scripts/nuggets/`, outputs in `nuggets/`. The code will be **released with\nthe research**, so clear design, reproducibility and short usage instructions are requirements (§7).\n\n---\n\n## 0. Decisions (these override the sections below where they differ)\n\nDecisions from 2026-09-26, revised on 2026-09-27:\n\n| # | Topic | Decision |\n|---|---|---|\n| D1 | Aggregator (generator) LLMs | **OpenAI**, **Maritaca Sabiá and Sabiazinho**, and **DeepSeek** (revised 2026-09-27: Qwen is no longer a generator) |\n| D2 | Judge | Families excluded as judge: OpenAI, Maritaca, DeepSeek. **Candidates: Gemini** (key now in `.env` as `GEMINI_API_KEY`) **and an open-weight Qwen model**. Both are calibrated against the human labels (§4.4). If Qwen's agreement is within about 0.05 κ of Gemini's, **Qwen is the primary judge**: pinned weights make the scoring exactly reproducible by anyone. Otherwise Gemini is primary and Qwen is reported as the second judge. An **OpenAI judge on a subset** measures self-preference directly (does it rate the OpenAI generator higher than the neutral judges do?) |\n| D3 | Nugget creator | Computed from scratch with a **strong model**. The [LN] nuggets file is **not** requested. The pilot compares the strongest available OpenAI model and Gemini, and the audit picks one. The [LN] prompt + `gpt-5.4-nano` stays only as a cheap optional pilot baseline |\n| D4 | GPU endpoints | **Needed only if Qwen is served ourselves** (revised 2026-09-27). The HF Inference Endpoint set up for the embeddings can run the Qwen judge with vLLM at a pinned revision. A hosted Qwen API with a pinned model version is an alternative for calibration. The model size is chosen at implementation, balancing judge quality against the endpoint's GPU cost |\n| D5 | Human audit | Kept. **Annotators: the user and another research team member.** The full protocol is in §3.4 |\n| D6 | Legal-provision score | **Wanted**, as a **secondary** metric. The main metric stays nugget recall (§4.3). The design is in §4.5 |\n| D7 | `contradicts` label | **Kept** (2026-09-27), §4.2. Calibration only reports its κ; it no longer decides whether the label is kept |\n| D8 | Nugget-set robustness | **New (2026-09-27):** a second full nugget set is made with the other creator model, and all runs are scored with both sets (§3.4, last part) |\n\n---\n\n## 1. Sources and what each one contributes\n\n| Ref | Work | What we take from it |\n|---|---|---|\n| **[LN]** | Pereira, Brito, Lotufo, Pereira — *Legal Nugget Extraction for Granular Retrieval over Long Jurisprudential Texts*, arXiv:2607.22479 (2026). Code: `github.com/ufca-llms/nuggets-search` | The **legal-nugget definition** (\"short, self-contained statement that captures an atomic legal argument or thesis\"; no party names, procedural history or generic text), an extraction prompt **already adapted to BR-TaxQA** (§1.1), and the generator it used (**GPT-5.4-nano**) |\n| **[AN]** | Pradeep et al. — *Initial Nugget Evaluation Results for the TREC 2024 RAG Track with the AutoNuggetizer Framework*, arXiv:2411.09607. Code: `github.com/castorini/nuggetizer` (Apache-2.0) | The **evaluation protocol**: importance labels (`vital` / `okay`), assignment labels (`support` / `partial_support` / `not_support`) and the scores (§4.3) |\n| **[GR]** | Pradeep et al. — *The Great Nugget Recall*, arXiv:2504.15068 | Evidence that fully automatic nuggets give run rankings that agree well with manual ones. This supports automatic creation followed by a **sampled** human audit instead of full manual annotation |\n| **[CA]** | Sharifymoghaddam et al. — *Chatbot Arena Meets Nuggets*, arXiv:2504.20006 (suggested in the 2026-06 meeting) | Nugget scores correlate with human preferences. It also notes that nugget generation is hard, especially in pt-BR and in the legal domain |\n\n### 1.1 What [LN] does and does not give us\n\n[LN] uses nuggets for **retrieval**: it indexes nuggets instead of documents. It does **not** score\ngenerated answers. Two facts matter here:\n\n- Its BR-TaxQA run (`runs/brtaxqa_openai_nuggets.json`) already nuggetized **the Q&A answers\n themselves**. That means the same gold text we have. It used `gpt-5.4-nano`,\n `response_format=json_object`, no explicit temperature, and this prompt:\n > *\"Voce e um contador especialista. Sua tarefa e extrair fatos atomicos (nuggets) de um conjunto\n > de perguntas e respostas juridicas. O texto analisado e a resposta de uma duvida frequente.\n > Transforme-a em fatos independentes que poderiam ser uteis para responder perguntas futuras. O\n > nugget deve ser direto em se tratando de prazos e obrigacoes. Nao invente fatos. Retorne\n > estritamente JSON no formato {\"nuggets\": [\"Fato 1\", \"Fato 2\"]}.\"*\n- The paper reports that on BR-TaxQA the nuggets **underperformed** full answers for retrieval\n (*\"tax questions and answers often depend on complete explanatory context\"*). For **evaluation**\n this is a warning: a nugget that drops its condition (\"desde que…\", \"exceto…\") or its subject\n cannot be judged on its own. That is why the prompt in §3.2 is **question-conditioned** and keeps\n each condition attached to the rule it limits.\n\n**Decision:** take the nugget **definition and domain framing** from [LN]; take the **scoring\nprotocol** from [AN]. The [LN] prompt + `gpt-5.4-nano` is kept as a **baseline configuration**, so the\npaper can report how its nuggets compare with the adapted ones (§5, pilot).\n\nThe generated nuggets file from [LN] (`data/brtaxqa/nuggets_report.json`) is not in the public repo.\n**It will not be requested (D3):** we recompute the nuggets with a stronger model.\n\n---\n\n## 2. Input: the gold answers\n\n- **Source of truth:** HF `unicamp-dl/BR-TaxQA-R`, file `questions_QA_2024_v1.0.json` (715\n questions), downloaded at a **pinned revision** with its SHA-256 recorded. On 2026-09-26 I checked\n the local copies: `question_text` and `answer_cleaned` are identical in v1.0, v1.1 (used for the\n query embeddings) and v1.1_manual_fix. So nuggets and queries share the same text.\n- **Field used:** `answer_cleaned` (the list of PDF lines with the external-reference block and\n \"Consulte a pergunta N\" lines removed), always **together with `question_text`**. Lines are joined\n with `\\n` so list items (\"1 -\", \"a)\") stay visible. Nothing else is rewritten. The prepared text and\n its hash are stored.\n- **Profile** (measured 2026-09-26): 698,724 characters in total; median 84 words; p90 316 words;\n max 3,316 words.\n- **Cases the prompt and validation must handle:**\n - **20 answers are shorter than 80 characters** (\"Não há limitação quanto à idade.\", \"Não, por falta\n de previsão legal.\"). They only make sense with the question, so conditioning on the question is\n required.\n - **Long enumerations** (e.g. Q001, 11 obligation criteria plus exemptions) should give one nugget\n per item, with the item's own values.\n - **50 answers still mention another question** in the cleaned text. **66 answers** refer to the\n declaration program, e.g. \"ficha\", \"PGD\". These are procedural instructions, not law, and the\n legal corpus cannot support them. They get a category tag (§3.1) so results can be reported with\n and without them.\n - **Embedded legal citations** (\"nos termos do art. 39 da Lei nº 11.196…\") stay in the text. They\n go into a separate `legal_basis` field, not into nugget text (§3.1).\n - We do **not** expand `linked_questions`. The gold answer is only what the answer itself says.\n- **Scope:** all 715 questions are prose (open-ended) questions. We nuggetize all of them, and the\n flags let each experiment choose a subset.\n\n---\n\n## 3. Nugget creation\n\n### 3.1 Nugget schema (one JSON object per nugget)\n\n```json\n{\n \"nugget_id\": \"Q001_N03\",\n \"question_number\": \"001\",\n \"text\": \"Está obrigada a apresentar a DAA de 2024 a pessoa física residente que, em 2023, recebeu rendimentos tributáveis sujeitos ao ajuste cuja soma foi superior a R$ 30.639,90.\",\n \"importance\": \"vital\",\n \"category\": \"condicao\",\n \"legal_basis\": [],\n \"source_span\": \"1 - recebeu rendimentos tributáveis, sujeitos ao ajuste na declaração, cuja soma foi superior a R$ 30.639,90\",\n \"ordinal\": 3\n}\n```\n\n- `category` ∈ `resposta_direta` (the Sim/Não or one-line verdict) · `regra` · `condicao` (condition,\n exception or requirement) · `valor_prazo` (amounts, limits, rates, deadlines) · `procedimento_pgd`\n (program/filling instructions) · `definicao`.\n- `importance` ∈ `vital` / `okay`, as in [AN]. A nugget is `vital` if a correct answer to **this\n question** must contain it.\n- `legal_basis`: citations taken from the nugget's own span, verbatim. They are kept for an optional\n \"cites the right legal basis\" score. They do not count in the main score, because the aggregator\n is not required to cite.\n- `source_span`: the verbatim sentence or line the nugget comes from. It makes the grounding check\n and the human audit fast.\n\n### 3.2 Prompt design (pt-BR, versioned files in `scripts/nuggets/prompts/`)\n\nThe prompt starts from [LN]'s BR-TaxQA prompt, adds [AN]'s importance step, and adds these rules for\nevaluation use:\n\n1. The input is the question **and** the answer. Each nugget must be understandable **without either\n of them**: name the subject, the tax year and the declaration. Resolve pronouns and \"esse/tal\".\n2. **Atomic, but not cut apart:** one fact per nugget. A condition or exception stays in the same\n nugget as the rule it limits.\n3. **Keep exact values** (R$, %, dates, deadlines, counts) **and technical terms** (\"rendimentos\n tributáveis sujeitos ao ajuste\", \"ganho de capital\"…) as written. Do not round or paraphrase them\n (§3.4.2).\n4. **Always emit the verdict nugget** (`resposta_direta`) when the answer starts with Sim/Não or\n gives a one-line conclusion.\n5. **Nothing outside the answer:** no facts from the model's own knowledge, and no nuggets made from\n the question alone.\n6. Citations go in `legal_basis`, not in `text`.\n7. Output must follow the JSON schema. Where the provider supports it, use structured output / JSON\n schema mode, and validate the result with pydantic in any case.\n\n**Importance in the same call or a second call?** [AN] creates nuggets and then scores importance in\na separate call. With a single short gold answer as the source, one call is enough and cheaper. The\npilot (§5) compares one call with two calls on 30 questions. We use two calls only if importance\nlabels in the single call are clearly worse.\n\n**Long answers:** no chunking is needed. The longest answer is about 5k tokens. We do not copy\n[AN]'s cap of 30 nuggets (that cap exists to limit pooled web documents). We **flag** answers with\nmore than 40 nuggets for human review.\n\n### 3.3 Automatic validation (`validate` step, no LLM)\n\n- The JSON is valid against the schema, and ids are unique and contiguous.\n- **Grounding of numbers:** every number, amount, percentage and date in `text` must also appear in\n the answer (normalized: `R$ 30.639,90` ≡ `30.639,90`). A mismatch is a hard error, because it is\n the most harmful hallucination in tax answers.\n- `source_span` is found in the answer, allowing whitespace and hyphenation differences.\n- Duplicates are removed after normalization (casefold, whitespace), as `dedupe_texts` does in [LN].\n- Coverage check: each answer sentence or list item should map to at least one `source_span`.\n Uncovered lines go to review.\n- Every question has at least one `vital` nugget. Answers under 80 characters have at least one.\n- Output: `validation.json`, with per-question issues and totals.\n\n### 3.4 Human audit\n\n**Why an audit is needed.** Every system is measured against the gold nuggets, so an error in them\nis a **systematic** error for all runs. Typical LLM errors are:\n- a changed value or deadline;\n- a condition dropped from its rule, which makes the nugget false in general;\n- a list item that disappeared;\n- a nugget that only makes sense next to the answer;\n- a wrong vital/okay label, which changes V_strict directly.\n\nThe validator (§3.3) catches only mechanical errors. [GR] validates automatic nuggets on English\nweb QA, not on pt-BR tax law.\n\n#### 3.4.1 What the audit checks, and what it does not\n\nThe **gold answer is the ground truth by definition**: the Receita Federal wrote it. Annotators check\nthe nuggets **against the answer text, never against the law**.\n- They do **not** judge whether the P&R is legally right.\n- \"Missing information\" means missing **from the answer**, not missing from the legislation.\n\nSo the task is careful reading plus a textual-entailment judgment. It is not legal analysis.\n\nChecks per nugget. Each is yes/no, with a decision rule:\n\n| Check | The annotator asks | It fails when |\n|---|---|---|\n| **C1 Faithful** | Does the answer (read with the question) say this, with nothing added, removed or changed? | A value, date or rate differs; Sim↔Não is flipped; a quantifier or scope changes (\"somente\", \"até\", \"qualquer\", \"todos\"); a technical term is swapped for a near-synonym (\"rendimentos tributáveis\" for \"rendimentos tributáveis sujeitos ao ajuste\"); a condition or exception from the same sentence is dropped; it states something the answer does not say |\n| **C2 Self-contained** | Could someone who never saw the question or the answer understand it and check it? | It has an unresolved \"esse\", \"tal\" or \"o contribuinte\" where the question limits who is meant; the tax year or declaration is missing when the rule depends on it |\n| **C3 One unit** | Can a system answer get it **entirely right or entirely wrong**? | It joins two independent facts (split it), or it is a fragment with no meaning alone (merge it). A rule together with its own condition is **one** unit |\n| **C4 Importance** | Would an answer to *this question* without this fact be wrong or misleading? Yes = `vital`, no = `okay` | The label is the other one |\n\nChecks per answer:\n\n| Check | How |\n|---|---|\n| **C5 Complete** | Every factual statement in the answer is covered by at least one nugget. The review sheet **highlights answer lines that no `source_span` covers**, so only those lines need a close reading. Each missing fact is written as a new nugget |\n| **C6 Not redundant** | No two nuggets carry the same fact |\n\n**Guideline rules for recurring cases:**\n- Worked numerical examples: no nugget, unless the example states a rule.\n- \"Atenção\" notes: they get nuggets, usually `okay`.\n- Program or screen instructions: `procedimento_pgd` nuggets, with importance set by C4.\n- Pointers to other questions: no nugget.\n\nEach item gets one outcome: **pass**, **fix** (the annotator writes the corrected text or label), or\n**escalate** (unsure about the legal meaning).\n\n#### 3.4.2 Is legal expertise required?\n\n**Mostly not.** C1–C3, C5 and C6 are reading tasks, as long as the nuggets keep technical terms\n**verbatim** (rule 3 in §3.2 is extended to terms, not only values). The annotator then never has to\ndecide whether a paraphrase of a legal term keeps its meaning.\n\nExpertise matters in two places:\n1. **A remaining paraphrase that might change legal scope.** Such items are escalated.\n2. **C4 on long, multi-part answers** (e.g. Q001). Here \"vital\" is partly a judgment call even for\n experts, and it is expected to be the least reliable label. The robustness check in §3.4.4 covers\n it.\n\nEscalated items (a few % expected) go to a tax or legal specialist in **one short session**. A\nspecialist does not have to review everything.\n\nAnnotators are **the user and another research team member** (D5). A team member without\nspecialist training works well with the guideline and the calibration round below. Record both\nannotators' backgrounds for the paper.\n\n#### 3.4.3 Process\n\n1. **Guideline v1** (pt-BR, one worked example per check), written from the pilot outputs.\n2. **Calibration round:** both annotators label the same **10 answers**, discuss every\n disagreement, and refine the guideline to **v2**. This round is not counted.\n3. **Main audit:** a **stratified sample of 60 questions**:\n - stratified by answer length (tertiles), P&R chapter and flags (short answer, long\n enumeration, `procedimento_pgd`);\n - plus every question the validator flagged.\n\n Annotator A labels all 60 answers. Annotator B labels 12 of them independently (20 %). An\n **adjudication** step resolves their disagreements.\n4. **Specialist session** for the escalated items.\n5. **Report:**\n - pass rate per check with a 95 % CI (this gives the estimated error rate of the full set);\n - Cohen's κ per check between A and B;\n - a table of error types.\n6. **Freeze gate:** C1 ≥ 95 %, and ≥ 90 % of answers with no missing vital fact (C5). If the gate\n fails, change the prompt or model and repeat the pilot. The fixed set is frozen as\n `nuggets/gold/v1/` (SHA-256). The corrections are released as a patch.\n\nTools: `review export` writes one XLSX per annotator. It has one row per nugget, with the answer\nshown and uncovered lines highlighted. `review import` validates the labels and builds the patch.\n\nEffort: about 500 nugget judgments for A (3–5 h) and about 100 for B (1 h), plus the calibration\nround. Judge-calibration labels (§4.4) are the bigger task, about 1,200 labels and 8–12 h. They can\ndrop to 100 pairs (about 800 labels) if needed.\n\n#### 3.4.4 Is there a creation method good enough to skip the audit?\n\n**No published nugget-creation method has been validated for pt-BR tax Q&A:**\n- [LN] reports no human check of its nuggets.\n- TREC uses human assessors as the reference, and [GR] is itself a measurement of automatic nuggets\n **against** that reference.\n\nWhat the literature offers is **design guidance**, which the prompt in §3.2 already follows:\n- **atomic-fact decomposition**: FActScore, Min et al., EMNLP 2023;\n- **decontextualization / \"molecular facts\"**: a fact should be as small as possible but still carry\n enough context to be checked alone. See Gunjal & Durrett, *Molecular Facts*, Findings of EMNLP\n 2024, arXiv:2406.20079. This is the rule behind C2 and C3;\n- **scores depend on the decomposition method**: Wanner et al., *A Closer Look at Claim\n Decomposition*, *SEM 2024, arXiv:2403.11903. This is the reason to measure the audit rather than\n assume quality.\n\nSo the method **reduces** errors, and the audit **measures** what is left. Two cheap additions make\nthe result stronger without more human work:\n\n- **LLM cross-check over all 715 answers:** the model *not* chosen as creator runs C1–C3 and C5. Its\n flags are added to the human queue. The flags are **not** labels: the error estimate comes only\n from the random sample, so it stays unbiased.\n- **Nugget-set robustness (D8):** make a second full nugget set with the other creator model (about\n 715 calls), and score every RAG run with **both** sets. The paper's claim is a **comparison**\n (S1 vs S2 vs S3), not an absolute score. If the ranking of strategies agrees under both sets\n (Kendall τ, and the same sign in the paired tests), the conclusion does not depend on the choice of\n nuggets. This is the most direct answer to \"are the nuggets good enough?\". The extra cost is one\n more assignment pass per run, so it can be limited to the main comparisons.\n\n---\n\n## 4. Scoring system answers against the nuggets (assignment)\n\n### 4.1 Input contract\n\nAny RAG run is one JSONL file with one line per question:\n`{\"run_id\": \"...\", \"question_number\": \"001\", \"answer\": \"...\"}`. The run metadata (strategy S1/S2/S3,\nembedding model, top-k/context size, aggregator LLM) goes in a sidecar `run.json`. This keeps the\nevaluator independent of the RAG code.\n\n### 4.2 Assignment call\n\nFor each (question, system answer), the judge LLM gets the question, the system answer and **all\nnuggets of that question in one call** (they are few; [AN] batches 10), and labels each nugget\n`support` / `partial_support` / `not_support`, with a short justification.\n\n**4th label, `contradicts`.** Take the gold nugget *\"As despesas com instrução estão sujeitas ao\nlimite individual anual de R$ 3.561,50\"* (Q400).\n- Answer A does not mention the limit. [AN] labels this `not_support`.\n- Answer B says the limit is R$ 5.000,00, or that there is no limit. [AN] also labels this\n `not_support`.\n\nBoth score 0, yet A is incomplete and B is wrong in a way that would mislead a taxpayer. A verdict\nreversal (\"Sim\" instead of \"Não\") is the same kind of case. With `contradicts`, the judge labels B\nseparately:\n- It scores 0 like `not_support`, so V_strict / A stay comparable with TREC. Mapping\n `contradicts` → `not_support` gives [AN]'s 3 labels back exactly.\n- A **contradiction rate** per run is reported. This matters for the segmentation question: a\n retriever that brings in the wrong or outdated provision should show more contradictions, not\n just fewer supported nuggets.\n\nIt adds no extra call, only one more option in the same assignment prompt. The risk is that the\njudge confuses \"not mentioned\" with \"contradicted\". The label is **kept** (D7). Calibration (§4.4)\nreports its κ, so readers know how far to trust the contradiction rate.\n\n### 4.3 Scores (from [AN], computed without an LLM)\n\nPer question, with s(support)=1, s(partial)=0.5, s(not/contradicts)=0:\n\n- **V_strict** = support-only credit over `vital` nuggets (main metric, as in TREC RAG 2024);\n- **V** = vital nuggets, partial credit 0.5; **A_strict**, **A** = the same over all nuggets;\n- **W** (weighted) = (Σ vital s + 0.5·Σ okay s) / (#vital + 0.5·#okay);\n- optional: contradiction rate; legal-basis recall (§3.1).\n\nRun score = mean over questions. Slices: with and without `procedimento_pgd`, and by chapter and by\nanswer length. Paired comparisons between strategies (S1 vs S2, same generator and k) use a paired\nbootstrap or a permutation test over questions.\n\n**Known limit:** nugget recall does not penalize extra wrong content. Nugget **precision** would\ncover that: nuggetize the system answer too and check each of its nuggets against the gold answer.\nIt is left as an optional extension. It doubles the judge cost, and hallucinations are partly\ncovered by `contradicts`.\n\n### 4.4 Judge calibration\n\n- **Human labels** on 150 (question, answer) pairs: 50 questions × 3 systems of different quality,\n drawn from the first real RAG runs.\n- Report nugget-level agreement (Cohen's κ, 3 or 4 labels) and **run-level ranking agreement**\n (Kendall τ) for each candidate judge. The judge used for the paper is the candidate with the best\n agreement within budget.\n- **The judge must not be from the same model family as the aggregator LLM**, to avoid\n self-preference bias. If several aggregators from different families are tested, the judge is\n fixed and from a family not among them, or a second judge is reported as a robustness check.\n\n### 4.5 Legal-provision score (secondary, D6)\n\n> **Update 2026-09-27 (later):** `references.jsonl` provisions are now parsed from the citation\n> text, with nested LexML `fragment_id`s (`art12_par1_inc2`) and the file that holds them\n> (`docs/20260927_213420_reference_provisions_from_citation_text.md`). The dispositivo level below\n> can match against these ids directly.\n>\n> **Update 2026-09-27:** the gold citations now come from `dataset/references.jsonl` (v2.0).\n> It has one row per (question, cited act), resolved to a corpus `document_id` / `document_urn`\n> with LexML `article_ids`, and the v1.1 reference errors are corrected. 42 references whose act is\n> not in the corpus are marked `not_in_corpus`. See\n> `docs/20260927_180401_dataset_v2_format_and_reference_fixes.md`. The v1.1 fields named below\n> are superseded.\n\n- **Gold citations** per question come from the dataset itself. `references` and\n `formatted_references` hold the reference block that `answer_cleaned` removed, and\n `formatted_embedded_references` holds the citations inside the answer text (569 questions have\n explicit references).\n- **System citations** are extracted from the generated answer.\n- Both sides are normalized to **LexML URNs with `../lexml-linker/`** (the same tool that produced\n the `Remissao` elements). Matching is then deterministic, with no LLM, at two levels: **document**\n (right law or IN) and **dispositivo** (right article, or §/inciso when both sides give one).\n- Report citation precision / recall / F1 per level. This fits the segmentation question well: S2\n chunks carry the exact inciso path, so they should raise dispositivo-level precision.\n- Per-nugget `legal_basis` (§3.1) stays as a finer, optional view: does the answer cite the right\n provision *for this fact*?\n\n---\n\n## 5. Which LLMs: options and recommendation\n\n**Is an LLM needed?** For **creation**, the only alternatives are rule-based splitting (sentences or\nlist items) or full manual annotation. Rule-based pieces are not self-contained (\"Não há limitação\nquanto à idade\"), and manual annotation of about 700k characters is too expensive. So an LLM with\nhuman audit is the practical choice. For **assignment**, cheap non-LLM baselines exist: NLI\ncross-encoders for pt-BR, and embedding similarity. They handle negation and numeric mismatch badly,\nand those are exactly what tax answers depend on. They are worth running **once as a sanity\nbaseline** only.\n\nThe two roles have very different cost profiles:\n\n| Role | Calls | Tokens (estimate) | What matters |\n|---|---|---|---|\n| Creation | 715, **once** | ≈ 1.3 M in / 0.3 M out | Quality. Cost is negligible, so use the strongest model |\n| Assignment | 715 **per RAG run** | ≈ 1.8 M in / 0.15 M out per run | Cost × number of runs, determinism, agreement with humans. The grid of 3 strategies × embedding models × k × generators can reach 50–100 runs, about 100–180 M input tokens |\n\nCandidates (versions and prices must be checked and pinned when implementing, as in the embedding\nplan):\n\n| Option | Examples | For | Against |\n|---|---|---|---|\n| A. [LN] setup | `gpt-5.4-nano` + [LN] prompt | Same setup as the reference paper; very cheap | Smallest model; [LN] itself reports context loss on BR-TaxQA |\n| B. Frontier API | Claude Opus 5.5 / Sonnet 5, a larger GPT-5.x, Gemini (Pro/Flash) | Best pt-BR reasoning; structured outputs; batch APIs (≈50 % cheaper) and prompt caching for assignment | Closed; the model can change or be retired, so reruns are not guaranteed; cost grows with the number of runs |\n| C. Open weights (vLLM) | A recent large Qwen3-family instruct model, gpt-oss, Llama | **Pinned weights = exactly reproducible** by anyone using the released code; no per-token cost | Needs GPU endpoints (the HF Endpoint setup from the embedding work can be reused); may lag B on legal nuance and needs calibration |\n| D. Brazilian model | Sabiá (Maritaca AI) | Trained for pt-BR, including legal text | API only; smaller ecosystem; check structured-output support |\n\n**Recommendation**\n\n- **Creation:** a strong **option B** model as the main nuggetizer. A **second family** (another B,\n or C) runs on the pilot only, to measure nugget-set agreement. Option A runs as the paper baseline.\n The nuggets are then **frozen and released**, so later readers do not need that model at all: the\n gold nuggets become part of the dataset.\n- **Assignment (D2, revised 2026-09-27):** calibrate **Gemini** (B) and an open-weight **Qwen** (C)\n against the human labels (§4.4). If Qwen's agreement is within about 0.05 κ of Gemini's, Qwen is\n primary (reproducible, and no per-token cost over many runs) and Gemini is the second judge.\n Otherwise the roles swap. An OpenAI judge on a subset measures self-preference.\n- In all cases, set temperature 0 where the API allows it (otherwise record the reasoning-effort\n setting and seed), and **cache every raw response** keyed by hash(model, prompt version, input),\n so reruns are free and the raw outputs can be released.\n\n**Using `castorini/nuggetizer` directly or reimplementing?** nuggetizer is Apache-2.0 and supports\nOpenAI, OpenRouter and vLLM. But its prompts are in English, its creation step iterates over a pool\nof retrieved documents, and it uses TREC input formats. We **reimplement the protocol** with pt-BR\nlegal prompts and a gold-answer source. We also write an **exporter to nuggetizer's JSONL format**\nand run the original tool on a sample as a cross-check. The exporter also lets others use our\nnuggets with their existing tooling.\n\n---\n\n## 6. Phases and gates\n\n| # | Phase | Output | Gate |\n|---|---|---|---|\n| 0 | Scaffold: package, providers (`openai`, `anthropic`, `gemini`, `openai_compat` for vLLM/Maritaca, `fake`), `prepare` | `nuggets/gold/input/questions.jsonl` + manifest | Tests pass with the `fake` provider |\n| 1 | **Pilot creation:** 30 stratified questions × {OpenAI, Gemini, optional [LN] baseline} × {1 call, 2 calls}; guideline v1 + calibration round (§3.4.3) | `nuggets/pilot/…` + comparison report | A human reviews the pilot and picks model + prompt |\n| 2 | **Full creation** + `validate` + LLM cross-check; second nugget set with the other model (D8) | `nuggets/gold/v0/`, `nuggets/alt/v0/` | 0 hard validation errors |\n| 3 | **Human audit** (§3.4) + corrections | `nuggets/gold/v1/` (frozen) | Audit gate met |\n| 4 | **Judge calibration** (§4.4) on the first RAG runs: Gemini vs Qwen (+ OpenAI subset) | `nuggets/calibration/` + report | Primary judge chosen; κ reported, including for `contradicts` |\n| 5 | **Scoring** of all RAG runs | `nuggets/assignments/<run_id>/<judge>/`, `nuggets/scores.csv` | — |\n| 6 | **Release:** code + gold nuggets + human labels + raw responses | HF dataset v2.0 (nuggets config) + repo | README quick start works in a clean venv |\n\nA dated `docs/` note records the decisions and results at the end of each phase.\n\n---\n\n## 7. Code design (`scripts/nuggets/`)\n\nThis mirrors `scripts/embedding/`: one CLI, one YAML registry, provenance manifests and a `fake`\nprovider for tests.\n\n```\nscripts/nuggets/\n README.md quick start, formats, costs, reproducing the paper\n nuggets.py CLI entry point (argparse subcommands)\n models.yaml LLM registry: provider, model id/snapshot, params, price, api_key_env\n prompts/ create_v1.pt.md, importance_v1.pt.md, assign_v1.pt.md, ln_baseline.pt.md\n nuggetizer/\n data.py load/prepare questions (HF pinned revision or local JSON)\n schema.py pydantic models + exported JSON Schemas (nugget, assignment, run)\n providers/ base.py (one `complete_json(messages, schema)` interface), openai.py,\n anthropic.py, gemini.py, openai_compat.py, fake.py\n cache.py content-addressed raw-response cache (JSONL)\n create.py, validate.py, review.py, assign.py, metrics.py, export.py (nuggetizer format)\n tests/ pytest: schema, validation rules, metrics math, fake-provider end-to-end\n```\n\n**CLI (target usage for the README):**\n\n```bash\nN=scripts/nuggets/nuggets.py\n.venv/bin/python $N prepare # fetch + clean the 715 gold answers\n.venv/bin/python $N create --model <slug> [--questions 001,002] [--limit 30]\n.venv/bin/python $N validate --nuggets nuggets/gold/v0\n.venv/bin/python $N review export|import ...\n.venv/bin/python $N assign --nuggets nuggets/gold/v1 --answers runs/<run>.jsonl --judge <slug>\n.venv/bin/python $N metrics --assignments nuggets/assignments/<run>/<judge>\n```\n\n**Output layout:**\n\n```\nnuggets/\n gold/input/questions.jsonl, manifest.json\n gold/v1/nuggets.jsonl, manifest.json, validation.json, audit/ (sample, labels, patch)\n raw/<step>/<model>/responses.jsonl every raw LLM response (released)\n assignments/<run_id>/<judge>/assignments.jsonl, manifest.json\n scores.csv one row per run × judge × metric × slice\n```\n\n**Manifests** record the git commit and dirty flag, the input SHA-256, the prompt file SHA-256,\nmodel id/snapshot and parameters, token usage and cost, timings and error counts. Cost goes into a\nledger like `embeddings/costs.csv`. **Resumable:** questions already in the cache or output are\nskipped. **Concurrency** is bounded, with retry and backoff. **Batch API** mode is optional for\n`assign`.\n\n**Documentation for release:** the README gives a 3-command quick start (prepare → assign → metrics\nwith the released gold nuggets, so users need no creation step), every file format with an example,\nhow to add a provider, and cost tables. Docstrings go on the public functions.\n\n---\n\n## 8. Open questions\n\nAnswered on 2026-09-26 and 2026-09-27: see §0 (D1–D8). Still open:\n\n1. **How Qwen is run for the judge:** our own HF endpoint (vLLM, pinned revision) or a hosted API\n with a pinned version, and which model size (D4).\n2. **Name and background of the second annotator** (for the guideline round and the paper, §3.4.2).\n3. **Tax/legal specialist** for the escalation session (§3.4.2): who is available?\n","20260927_180401_dataset_v2_format_and_reference_fixes.md":"# BR-TaxQA-R v2.0 — New Dataset Format and Reference Fixes\n\n**Generated:** 2026-09-27 18:04:01 (local time, from `date +%Y%m%d_%H%M%S`)\n**Status:** implemented and run. Outputs are in `dataset/`, code and hand-verified data in `scripts/dataset/`.\n**Context:** the legal-provision score (`docs/20260926_112714_gold_answer_nuggetization_plan.md`, §4.5)\ntakes its gold citations from the dataset. v1.1 references point at `.txt` file names of the v1\ncorpus, some of which are duplicated or wrong. The v2.0 corpus (`original/` → `lexml/` → `segmented/`)\nuses different names. So the references had to be re-keyed to v2.0 documents and corrected.\n\n> **Update 2026-10-08:** the 26 wrong acts of §5.2a are now in the corpus and resolve automatically\n> through the fetcher's corrected canonical list (`not_in_corpus` 42 → 0). Q313 \"Parecer Cosit nº\n> 30/2001\" and Q187 \"SCI Cosit nº 27/2008\" were dropped, and Q249 points at Nota PGFN/CRJ nº\n> 981/2015. §7 items 1 (documents without chunks), 2 (missing articles; only treaty articles remain,\n> as `unmatchable`), 3 (missing acts, fetched by the user), 4 (the Nota-981 duplicate, removed),\n> 5 (URNs, now declared) and 6 (canonical list) are done; item 7 is still open. See `docs/20261007_180833_corpus_fixes_and_full_rebuild_plan.md` and\n> `docs/20261008_010441_corpus_rebuild_results.md`. The §5.2a table and §6 counts below are kept as written on 2026-09-27.\n\n---\n\n## 1. Request\n\nThe user asked for:\n\n1. Three specific fixes:\n - **Q277:** remove the \"Solução de Consulta Interna Cosit nº 5, de 28 de março de 2006\" reference.\n The act does not exist; v1 downloaded the unrelated *Ato Declaratório Executivo Cosit nº 5, de\n 24/02/2006*.\n - **Q150:** \"Convenção Postal Universal.txt\" is the *Decreto nº 9.358, de 30 de abril de 2018*.\n - **Q141:** the Brazil–Germany double-taxation accord is the *Decreto Legislativo nº 92, de 1975*.\n2. All referred-document file names updated to the v2.0 corpus, for every question.\n3. A new JSON file for the updated references, in a format that is easy to store and load on the\n HF Hub. The v1 format does not have to be kept.\n4. A proposal for a whole new dataset format holding the questions, references and ground truth.\n5. This note, recording the discussion and the execution.\n\n## 2. Sources used\n\n| Input | Path | Notes |\n|---|---|---|\n| v1.1 questions | `../questions_QA_2024_v1.1_manual_fix.json` | same MD5 (`339dc9ca…`) as HF `questions_QA_2024_v1.1.json` in the local HF clone `/work/doutorado/datasets_creation/legal/BR-TaxQA-R/`. SHA-256 `097abfc4…` in `build_report.json` |\n| v1.1 corpus | `…/BR-TaxQA-R/referred_legal_documents_QA_2024_v1.1.json` | used only to see what v1 actually held for a file name |\n| canonical list | `../br-taxqa-document-fetcher/output_canonical/canonical_referred_documents.json` | 478 records, one per v1.1 file name: act type, number, date |\n| v2.0 corpus | `original/{articulados,nao_articulados}/*.docx` (225 + 234 = 459) and `lexml/` | the corpus is now flat, not split into per-type sub-folders as in the 2026-09-13 audit |\n| chunks | `segmented/chunks_all.csv.gz` | used to check that every cited document can be retrieved |\n\n## 3. Format decision\n\n### 3.1 Problems with v1.1\n\n- A single questions file holds nested reference lists with **irregular schemas**: 5 key sets for\n reference entries and 5 for article entries (`alíneas`, `itens`, `detalhes` appear only\n sometimes), two empty `{\"anexos\": []}` entries, and `null` instead of `[]`.\n- The custom loader script (`BR-TaxQA-R.py`) declares `Sequence(dict)`. HF turns that into a\n **dict of lists** and stringifies the article dicts. The v1 README admits this.\n- `all_formatted_references` is a dict keyed by title that just concatenates the two lists.\n- References point at `.txt` file names. Several file names are the same act, and some point at the\n wrong act (§5).\n- Loader scripts are deprecated on the Hub (`datasets` ≥ 4 no longer runs them).\n\n### 3.2 Chosen format: three JSON Lines configs, no loader script\n\nThree flat tables joined by keys, declared in the dataset card's YAML `configs:` block\n(`dataset/README.md`). The Hub and `load_dataset(path, config)` read them directly. Every row has\nevery key (`[]`/`null` when empty), so Arrow infers one schema. `provisions` loads as a **list of\nstructs**, not as the v1 dict-of-lists (verified with `datasets` 2.19.2).\n\n| Config | Rows | Key | Role |\n|---|---:|---|---|\n| `questions` | 715 | `question_number` | question, full answer, **gold answer** (`answer_cleaned`), raw reference text, cited `document_ids` |\n| `references` | 1,919 | `reference_id` = `<question_number>-<nn>` | one row per cited act per question: origin (`explicit`/`embedded`), cited title, `document_id` + `document_urn`, how it was resolved, structured provisions with LexML article ids, the v1.1 file name |\n| `documents` | 459 | `document_id` = `original/` stem | URN, title, statutory flag, number, date, `original/` and `lexml/` paths (including annex files), v1.1 file names that resolve to it, number of citing questions |\n\nThe field-by-field schema is in `dataset/README.md`. Design choices:\n\n- **JSON Lines, not one JSON array.** It is the Hub's standard for the `json` builder: it streams,\n diffs line by line and needs no custom code. Parquet can be produced from it on upload if needed.\n- **References in their own table.** The legal-provision score (§4.5 of the nuggetization plan)\n works on (question, document, provision) rows. A flat table filters and joins directly, with no\n nested parsing. `questions.document_ids` is a convenience for document-level scoring.\n- **`document_urn`** equals `doc_urn` in `segmented/chunks_all.csv.gz`. Gold citations therefore\n match retrieved chunks with no extra mapping, and match `lexml-linker` URNs on the system side.\n- **`article_ids`** follow the LexML `id` convention of the XMLs (`art25`, `art12-1` for art. 12-A).\n Ranges (`\"10 a 13\"`) are expanded up to 300 articles. Unparseable strings (roman numerals of\n treaties, `\"Capítulo III\"`, `\"item 4\"`) give `[]`, and the raw string stays in `article`.\n Paragraph/inciso/alínea lists are kept as v1.1 had them, only trimmed of `§`. v1.1 lost which\n inciso belongs to which paragraph, and that cannot be recovered reliably. Provision-level URNs\n are left to the §4.5 implementation (`lexml-linker` on `references_text`).\n\n > **Correction (2026-09-27, `docs/20260927_213420_reference_provisions_from_citation_text.md`):**\n > the paragraph above was wrong. The nesting is in the citation text, which v1.1 keeps, and\n > `lexml-linker` has no role in the gold references. The provisions are now parsed from the\n > text (`scripts/dataset/citations.py`) into nested LexML `fragment_id`s. The same fix restores\n > article ranges that v1.1 cut short and drops articles v1.1 invented. The `provisions` schema\n > above is replaced; see `dataset/README.md`.\n- **Answers as strings** (lines joined with `\\n`), as the nuggetization plan §2 prepares them.\n- **Traceability:** each reference keeps `v1_file`, `resolution` and `resolution_note`. Every\n hand decision is in `scripts/dataset/reference_overrides.json`, with a reason.\n- **Room for ground truth:** the gold nuggets planned in `scripts/nuggets/` can be added as a fourth\n config, `nuggets` (one row per nugget, keyed by `question_number`), with no change to the others.\n\nDropped from v1.1: `all_formatted_references` (redundant) and the `.txt` file names as keys\n(they survive only as `v1_file`/`v1_files`).\n\n## 4. Execution\n\n### 4.1 Mapping non-statutory `.docx` to their XML\n\n`lexml/nao_articulados/*.xml` are named after their URN, so the `.docx` stem does not appear in the\nname, and no stored map existed. I re-parsed each of the 234 `.docx` with\n`../lexml_parser_non_statutory` (`python -m lexml_nonstat parse`) and matched the URN it printed.\n214 matched directly. For the other 20, the current parser leaves the date as `0000`, while the\ncommitted XMLs carry it. Those 20 paired one-to-one by authority, type and number. The result is\ncommitted as `scripts/dataset/nonstat_lexml_map.tsv` (234 stems → 234 distinct XMLs), so the build\ndoes not re-run the parser.\n\n### 4.2 Resolving v1.1 file names to v2.0 documents\n\n`scripts/dataset/build_v2_dataset.py` resolves each v1.1 `file` value through its canonical\nrecord, in this order:\n\n1. **Hand-verified override** (`reference_overrides.json`): `files` (per file name), `drop` (one\n question's reference) or `reassign` (one question's reference moved to another document).\n2. **`auto_exact`**: stem prefix + number + date of the canonical record.\n3. **`auto_undated`**: prefix + number, when the canonical record has no date.\n\nAny v1.1 file name left unresolved makes the build **fail**. Date-tolerant matching is not\nautomatic. The 2026-09-13 audit's rule 5 and its per-type \"hand map\" hid real errors (§5.2).\n\n### 4.3 Checks, and how they surfaced the errors\n\n- **Coverage:** all 478 canonical file names resolve or are explicitly marked.\n- **Article existence:** every `article_id` is looked up in the document's LexML ids (main XML, then\n annex XMLs). This found the RIR/2018 articles in `decreto_9580…anexo1.xml`.\n- **Cited number vs document number**, and **cited date vs document date**: these found the\n wrong-act matches in §5.2. For every cross-year mismatch I compared the question's subject with\n the corpus document's *assunto*/ementa.\n- **Titles without an act number** (RIR, CF, treaties): listed title → document pairs by hand. This\n found `160-02` and `362-07`.\n- **Citation present in the source text**: each reference's act number or keywords must appear in\n `references_text` (explicit) or in `answer` (embedded). This found Q025 and Q081.\n\n## 5. Corrections applied\n\n### 5.1 The three requested fixes\n\n| Question | v1.1 reference (file) | v2.0 |\n|---|---|---|\n| 277 | Solução de Consulta Interna Cosit nº 5, de 28/03/2006 | **removed** (listed in `build_report.json → dropped_references`) |\n| 150 | Convenção Postal Universal | `decreto_9358_20180430` (`urn:lex:br:federal:decreto:2018-04-30;9358`) |\n| 141 | Acordo … Brasil e a Alemanha | `decreto_legislativo_92_19751105` (`urn:lex:br:congresso.nacional:decreto.legislativo:1975-11-05;92`) |\n\n**Q150 also has a second UPU entry**, \"Convenção de Berna da União Postal Universal (UPU).txt\". Its\nraw reference text is just \"UPU\", and v1 held a Wikipedia article for it. It is the same convention,\nso it is also mapped to `decreto_9358_20180430`. This is **my inference** from the user's fix, and it\nis easy to revert in `reference_overrides.json`.\n\n### 5.2 Additional errors found and fixed\n\nThese fall under the user's note that the first version had inconsistencies. **Please review them.**\n\n**a) The canonical list, and v1, matched the wrong act.** Cosit numbers its Soluções de Consulta per\nyear. The fetcher therefore matched a same-numbered SC from another year (v1's `.txt` names had no\ndate). A few other acts had the same problem. In every case below, the corpus document is on an\nunrelated subject. The reference is kept, with `document_id = null` and `resolution =\nnot_in_corpus`, so no wrong document is used as gold:\n\n| Cited act | Questions | Corpus holds instead |\n|---|---|---|\n| SC Cosit nº 50, de 22/06/2020 | 097, 645 | SC 50/2024 (IRPJ, Sociedades de Crédito Direto) |\n| SC Cosit nº 69, de 30/12/2013 | 129 | SC 69/2020 (IRPJ, prizes) |\n| SC Cosit nº 64, de 07/03/2014 | 148, 149 | SC 64/2024 (interval between shifts) |\n| SC Cosit nº 194, de 05/08/2015 | 148, 149, 150 | SC 194/2023 (PIS, cerealistas) |\n| SC Cosit nº 140, de 21/09/2021 | 180 | SC 140/2023 (IRPJ, ICMS-DIFAL) |\n| SCI Cosit nº 27, de 07/07/2008 | 187 | Solução de Divergência 27/2008 (IRRF/Cide) |\n| Decreto-Lei nº 8.794, de 23/01/1946 | 188 | Lei 8.794/1993 (budget credit) |\n| AD PGFN nº 2, de 10/03/2016 | 230, 316 | AD PGFN 2/2018 |\n| SC Cosit nº 179, de 16/08/2023 | 234, 282 | SC 179/2024 (compensatory alimony) |\n| AD PGFN nº 3, de 30/03/2016 | 280 | AD PGFN 3/2008 |\n| SC Cosit nº 75, de 25/06/2020 | 280, 281 | SC 75/2023 (software royalties) |\n| SC Cosit nº 123, de 13/09/2021 | 305, 306 | SC 123/2023 (Cofins) |\n| SC Cosit nº 7, de 13/01/2017 | 307 | SC 7/2021 (IRPJ, real estate) |\n| Parecer Cosit nº 30, de 28/09/2001 | 313 | ADE Cosit 30/2001 (dollar rate) |\n| SC Cosit nº 354, de 17/12/2014 | 356 | SC 354/2017 (pension-plan contributions) |\n| SC Cosit nº 173, de 03/07/2015 | 361, 375 | SC 173/2023 (PIS credits) |\n| SC Cosit nº 214, de 20/12/2021 | 460, 627 | SC 214/2024 (real-estate rights) |\n| ADI RFB nº 3, de 27/04/2016 | 559, 627 | ADE RFB 3/2024 (TIPI) |\n| SC Cosit nº 211, de 24/06/2019 | 560, 562 | SC 211/2024 (Simples Nacional) |\n| SC Cosit nº 183, de 25/06/2014 | 580 | SC 134/2014 (CIDE); v1 already held this text |\n| SC Cosit nº 166, de 28/05/2019 | 610, 611, 614 | SC 166/2023 (residential-property exemption) |\n| PN CST nº 38, de 1975 | 253, 255 | PN CST 38/1980 (cooperatives) |\n| PN CST nº 72, de 1979 | 607 | PN CST 72/1975 (pre-operating expenses) |\n| Resolução TSE nº 22.250, de 2006 (art. 14) | 438 | Res. TSE 22.205/2006 (no art. 14) |\n| Parecer PGFN/CAT nº 815/2010 | 249 | `parecer_pgfncat_815_2010_nota_pgfn_crj_981_2015.docx` holds **Nota PGFN/CRJ 981/2015**, a duplicate of `nota_pgfn_981_20151104` |\n| Documento de Informação e Apuração do ITR (Diat) | 634 | not in `original/`. It was fetched (`../br-taxqa-document-fetcher/output_manual/documents/documento_de_informacao_e_apuracao_do_ITR_DIAT.docx`) but never copied |\n\nThat is 26 acts and 42 references. 37 questions have at least one unresolved reference; for 2 of\nthem, none of their references resolves.\n\n**Which of these were already in v1.0** (checked on 2026-09-27). I traced each act through the\nreleased v1.0 files (`../questions_QA_2024_v1.0.json` and `../referred_legal_documents_QA_2024_v1.0.json`,\nbyte-identical to HF commits `52ec296` / LFS oid `4c5ed205…`). For every act, v1.0 used the same\nfile name as v1.1, and the text of that file is the same in v1.0 and v1.1.\n\n- **Already wrong in v1.0 (23 acts):** the 21 same-number acts from another year or of another\n type, the \"Parecer PGFN/CAT 815/2010\" file (already holds Nota PGFN/CRJ 981/2015) and SC Cosit\n 183/2014 (already holds SC 134/2014). Resolução TSE 22.250 was also wrong in v1.0, in a different\n way. v1.0 held a TSE *index page* that lists resolutions 22.205, 22.249, 22.250… with one-line\n summaries, not the text of 22.250 (no art. 14). v2.0 fetched 22.205, the first entry of that list.\n- **Correct in v1.0, broken in v2.0 (3 acts):**\n - **PN CST nº 38, de 24/03/1975** (Q253, Q255): the v1.0 text is the right opinion, on\n professional services by individuals. The v2.0 fetch got PN CST 38/1980.\n - **PN CST nº 72, de 18/12/1979** (Q607): the v1.0 text is the right opinion, on inherited\n property cost. The v2.0 fetch got PN CST 72/1975.\n - **Diat** (Q634): v1.0 held Receita Federal's Diat service page. It is the same kind of source as\n the DBF/Dmed/DOI pages that v2.0 kept, and it was lost only because the fetched `.docx` was never\n copied to `original/`.\n\nThe v1.0 texts of PN CST 38/1975 and 72/1979 can be used to recover these two acts in v2.0.\n\nSame-year date differences were checked and kept, because the act is the right one: IN RFB 1.131\n(20 vs 21/02/2011), IN RFB 1.585 (cited \"31/12/2015\", act of 31/08/2015), SC Cosit 125/2014,\nSC Cosit 264/2019, IN SRF 83 and 118, PN CST 6 and 66, Lei 9.718, and the typo'd years of Lei\n9.250 / Lei 7.713 / Decreto 9.580. PDF typos resolved correctly: \"Lei nº 8.891\" → Lei 8.981/1995\n(Q176); \"Lei nº 1.535\" → Decreto-Lei 1.535/1977.\n\n**b) The canonical list mapped to the wrong document of the corpus:**\n\n| File (v1.1) | Canonical said | v2.0 |\n|---|---|---|\n| Convenção sobre Privilégios e Imunidades das Nações Unidas (Q150) | Decreto 52.288/1963 (the *Agências Especializadas* convention) | `decreto_27784_19500216`, which promulgates the UN convention and which Q150's own answer cites next to it |\n| IN RFB nº 1.997/2019 (Q025) | IN RFB 1.911/2019 | not in corpus (and the reference is dropped, see d) |\n\n**c) v1.1 attached the wrong file to one citation** (`reassign`, per question):\n\n| Reference | Cited | v1.1 file | v2.0 |\n|---|---|---|---|\n| 160-02 | Acordo sobre o Novo Banco de Desenvolvimento, art. 34 | Convenção de Viena sobre o Direito dos Tratados | `decreto_8624_20151229` (annex 1 is the NDB agreement) |\n| 362-07 | art. 66 do RIR/2018 | Circular BCB 3.432/2009 | `decreto_9580_20181122` |\n\n**d) Hallucinated embedded references (dropped).** Q025 (\"Não é devida a multa…\") and Q081\n(\"Apresenta declaração de acordo com as instruções para contribuinte casado.\") cite nothing. Yet\nv1.0 and v1.1 list three \"embedded\" references for each: Lei 9.532, IN RFB 1.997, CTN, Decreto\n3.000 and IN RFB 1.505 \"de 05/08/2014\". This is an artefact of the LLM extraction. These 6 references\nare removed. Together with Q277 that makes 7 dropped references. No other reference failed the\nsource-text check.\n\n## 6. Results\n\n`python3 scripts/dataset/build_v2_dataset.py` (about 2 s):\n\n| | Count |\n|---|---:|\n| Questions | 715 |\n| Questions with ≥ 1 reference | 596 |\n| References | 1,919 (1,475 explicit, 444 embedded) |\n| — `auto_exact` / `auto_undated` | 1,776 / 30 |\n| — `override` (hand-verified) | 71 |\n| — `not_in_corpus` | 42 |\n| Dropped references | 7 (Q277 ×1, Q025 ×3, Q081 ×3) |\n| Corpus documents | 459; 424 cited by some question |\n| Cited article ids found in the LexML | 1,792 / 1,811 (1,385 main XML, 407 only in an annex XML) |\n\nThe 35 uncited documents (listed in `build_report.json`) are the wrong-year acts above, the\nNota-981 duplicate, Lei 3.071 and Lei 5.869 (known extras), and a few acts v1.1 never cited:\nthe DBF/Dimob/Dmed/DOI/Carnê-Leão pages, Parecer Cosit 26/2000 and SC Cosit 153/2014.\n\n## 7. Open issues found along the way (not fixed here)\n\n1. **11 cited documents have no chunks.** Their statutory LexML has an empty `<Articulacao>`, so\n the XSL produced 0 rows. They cannot be retrieved, although 16 references in 6 questions (Q149,\n Q150, Q154, Q158, Q159, Q666; mostly treaty decrees) cite them: `decreto_27784`, `decreto_59308`, `decreto_59309`,\n `decreto_62125`, `decreto_63151`, `decreto_85801`, `decreto_86006`, `decreto_86084`,\n `decreto_93153`, `in_srf_23_19830325` and `in_srf_67_19880421`. The earlier segmentation notes\n do not mention this. Fix it in parsing (for example, re-route them to the non-statutory parser,\n as was done for `in_srf_84_19791220`).\n2. **Articles present in the `.docx` but missing from the XML:** MP 2.158-35 art. 24 (8\n references), Lei 6.404 art. 252, Lei 11.941 art. 56, Decreto 59.566 art. 3 (\"Art 3º\" without a\n period). Lei 13.043 art. 16 appears in the `.docx` only as a dotted placeholder. Decreto 361 art.\n 13 and IN SRF 107 art. 1 are not in the `.docx` at all. `build_report.json →\n validation.article_ids_missing` lists all 19.\n3. **Fetch the missing acts** in §5.2a (21 SC/AD/Parecer/DL acts, PN CST 38/1975, PN CST 72/1979, Res.\n TSE 22.250/2006, Parecer PGFN/CAT 815/2010) and copy the Diat `.docx` into `original/`. Then\n replace their overrides with the new stems and rebuild. Until then, report the legal-provision\n score over resolved references, or count unresolved ones as unmatchable gold.\n4. **Duplicate in the corpus:** `parecer_pgfncat_815_2010_nota_pgfn_crj_981_2015` repeats Nota 981/2015.\n It is harmless for scoring (nothing cites it now), but it adds a duplicate to retrieval.\n5. **Non-statutory URN quality:** some committed URNs have the wrong authority or type, for example\n `nota_sei_48_2018` → `…procuradoria.geral.fazenda.nacional:nota.pgfn:2018;48`,\n `nota_pgfn_crj_1104_2017` → `…superior.tribunal.justica:solucao.consulta…`, and\n `parecer_pgfncat_815…` → `…:sumula:2015;981`. `document_urn` copies what the corpus has, so gold\n and chunks agree. Matching them against `lexml-linker` URNs of generated answers, however, will\n miss these. The §4.5 implementation should match at `document_id` level, or normalize both sides.\n6. The fetcher's `canonical_referred_documents.json` still carries the errors in §5.2a–b. The\n corrections live only in `reference_overrides.json`.\n7. Not verified: any remaining v1.1 extraction errors in provision details (paragraph/inciso lists),\n beyond the article-existence check. **Resolved 2026-09-27:** provisions are now parsed from the\n citation text and cross-checked against v1.1\n (`docs/20260927_213420_reference_provisions_from_citation_text.md`).\n\n## 8. Files\n\n| Path | Content |\n|---|---|\n| `dataset/questions.jsonl`, `references.jsonl`, `documents.jsonl` | the v2.0 dataset |\n| `dataset/README.md` | HF dataset card with the `configs:` block and the schema |\n| `dataset/build_report.json` | counts, dropped/unresolved references, validation, input hashes, git commit |\n| `scripts/dataset/build_v2_dataset.py` | the builder |\n| `scripts/dataset/reference_overrides.json` | every hand decision, with its reason |\n| `scripts/dataset/nonstat_lexml_map.tsv` | non-statutory `.docx` stem → LexML file |\n| `scripts/dataset/README.md` | how to run it |\n","20260927_204356_rag_pipeline_implementation_plan.md":"# RAG Pipeline Implementation Plan (retrieval first)\n\n**Generated:** 2026-09-27 20:43:56 (local time, from `date +%Y%m%d_%H%M%S`)\n**Status:** Phase 1 (retrieval + legal-provision test) implemented and run: `docs/20260927_222210_retrieval_legal_provision_test_jua.md`. Phases 2–5 are still plans.\n**Goal:** build the full RAG pipeline for the segmentation experiment (retrieval → context\nselection → answer generation → hand-off to nugget evaluation), but implement and run **only the\nretrieval stage first**. The first run is a **legal-provision retrieval test** with the existing\n`jua-4b-mixed` embeddings. It gives an early view of how the segmentation strategies (S1 / S2 / S3)\naffect retrieval, before any LLM money is spent.\n**Deliverables:** code in `scripts/rag/`, outputs in `runs/`. The code will be **released with the\nresearch**, so clean design, documentation and ease of use are requirements, not extras (§8).\n\n**Background (read first):**\n\n- `docs/20260923_193852_segmentation_strategies_for_rag_experiments.md` — the strategies, and §7\n (token budget instead of raw k, containment de-duplication). Referred to below as **the strategy\n doc**.\n- `docs/20260925_122058_embedding_implementation_plan.md` — the embedding release format (§4.2) this\n pipeline reads. Referred to below as **the embedding plan**.\n- `docs/20260926_112714_gold_answer_nuggetization_plan.md` — the answer-evaluation side: the input\n contract for system answers (§4.1), the generator LLMs (D1) and the legal-provision score (§4.5).\n Referred to below as **the nugget plan**.\n- `docs/20260927_180401_dataset_v2_format_and_reference_fixes.md` — the v2.0 `references` config,\n which is the gold standard for retrieval, and its open issues (§7).\n\n---\n\n## 1. Scope and staging\n\n| Stage | What it does | LLM? | Implemented in |\n|---|---|---|---|\n| **R — Retrieve** | Rank the chunks of each strategy for each question, using stored query and corpus vectors | no | **Phase 1 (now)** |\n| **RE — Retrieval evaluation** | Score the rankings against the gold references at document, article and provision level (the \"legal-provision test\") | no | **Phase 1 (now)** |\n| C — Context selection | De-duplicate and cut a ranking to k chunks or a token budget, then format the context | no | Phase 2 |\n| G — Generate (aggregation) | Answer each question from its context with an LLM | yes | Phase 3 |\n| E — Answer evaluation | Nugget scoring and the legal-provision score of the answers | yes | nugget plan (`scripts/nuggets/`) |\n\nThe stages talk to each other **only through files** with documented formats (§5). Each stage can\nbe rerun, replaced or released on its own. For example, a reranker could later be added between R and\nC without touching the other stages. Stage E stays in `scripts/nuggets/`, as the nugget plan\ndecided: it reads the answer files that stage G writes and knows nothing about retrieval.\n\nPhase 1 must still be **designed for the whole pipeline**. The run layout, the manifests, the\nstrategy definitions and the relevance matcher are used by all later stages, so they are built\nproperly now, not as throw-away scripts.\n\n---\n\n## 2. Facts this plan relies on (checked 2026-09-27)\n\n| Item | Value |\n|---|---|\n| Chunks | `segmented/chunks_all.csv.gz`, 87,702 rows / 84,568 unique texts, SHA-256 `f3db0904…55f9b`. This is the same file the `jua-4b-mixed` corpus manifest records |\n| Corpus vectors | `embeddings/jua-4b-mixed/corpus/vectors.npy`, float32 [84,568 × 2,560], rows in `text_id` order; `chunk_map.csv.gz` maps `chunk_id → text_id` |\n| Query vectors | `embeddings/jua-4b-mixed/queries/irpf/vectors.npy`, 715 rows. The query text inside `text_sent` equals `dataset/questions.jsonl` `question_text` for **all 715** questions |\n| Chunk rows by `Tipo` | PAR 21,511 · INC 20,617 · ART 20,477 · CPT 8,084 · ALI 4,878 · TXT 3,545 · SEC 2,106 · CAP 1,843 · DSP 1,522 · ITE 1,302 · SSC 714 · TAB 706 · TIT 326 · LIV 45 · SBT 21 · PRT 5 |\n| Provenance columns | `arquivo`, `categoria` (`main`/`A`/`B`/`C`/`nao_articulado`), `doc_urn`, `anexo_urn`, `unidade_id`, `artigo_id`, `agrupadores_ids`, `citacao`, `parte`/`n_partes`, `cobre_ids`, `parcial_ids`, `id_ambiguo`, `n_tokens_qwen3`, `Num_Inicio`/`Num_Final` |\n| Gold | `dataset/references.jsonl`: 1,919 references; **594 questions** have at least one reference resolved to a corpus document, **550** have at least one cited article id |\n| Hardware | 20 cores, 62 GB RAM. Exact brute-force search is enough: Q·Vᵀ for 715 × 84,568 × 2,560 takes seconds in numpy. No ANN index (FAISS etc.) is needed, so there is no approximation error to report |\n\n### 2.1 Known issues that affect the first run (\"despite the remaining issues\")\n\nThe first run uses the corpus and gold as they are now. These issues put an upper limit on the\nscores. The evaluator **measures the limit** instead of hiding it:\n\n1. **11 cited documents have no chunks** (empty `<Articulacao>`; 16 references in 6 questions).\n2. **19 cited article ids are missing from the LexML** (`build_report.json →\n validation.article_ids_missing`).\n3. **42 references are `not_in_corpus`** (acts never fetched).\n4. **RIR/2018-style ambiguity:** a citation of Decreto 9.580/2018 art. N may mean the decree's own\n article or the article of its annex (the RIR). The same holds for any document whose annex has\n articles (categoria `A`). See rule G3 in §4.2.\n5. `id_ambiguo = 1` on 1,802 rows (the same id occurs more than once in one file).\n\nEach gold item is tagged as **reachable** (at least one chunk in the strategy can match it) or\n**unreachable**. Metrics are reported (a) over all resolved gold, with the **oracle ceiling**\n(the best possible value) shown next to them, and (b) over reachable gold only. Retrieval is cheap,\nso the whole test is simply rerun once these issues are fixed. The report records the chunk and\ndataset hashes, so results from different fix levels are never mixed up.\n\n---\n\n## 3. Stage R — retrieval\n\n### 3.1 Strategies as configuration\n\n`scripts/rag/strategies.yaml` defines each strategy as the set of `Tipo`s it indexes. It follows the\nstrategy doc (§5) and the segmentation results:\n\n```yaml\nstrategies:\n S1: {tipos: [ART, DSP, TXT, TAB], description: \"Article (or top-level dispositivo) + non-statutory units\"}\n S2: {tipos: [ART, DSP, TXT, TAB, CPT, PAR, INC, ALI, ITE], description: \"S1 + sub-article units with ancestor path\"}\n S3: {tipos: [ART, DSP, TXT, TAB, CPT, PAR, INC, ALI, ITE, PRT, LIV, TIT, SBT, CAP, SEC, SSC], description: \"S2 + grouping chunks\"}\n# Coarse-to-fine order, used when one text belongs to several chunks (§3.3)\nunit_precedence: [PRT, LIV, TIT, SBT, CAP, SEC, SSC, ART, DSP, TXT, TAB, CPT, PAR, INC, ALI, ITE]\n```\n\nNew strategies (for example \"leaves only\", which the strategy doc mentions as an extra) are added\nwith a YAML entry and no code change. At load time the code checks that the S1/S2/S3 row counts\nmatch the segmentation results (S1 = 26,252, S2 = 82,644, S3 = 87,947 after the 2026-09-25\nre-run; the expected counts are stored in the YAML and checked with a warning, not an error).\n\n### 3.2 Retriever interface\n\n```python\nclass Retriever(Protocol):\n name: str\n def info(self) -> dict: ... # goes into the manifest\n def search(self, query_ids: list[str], candidate_text_ids: np.ndarray,\n top_n: int) -> list[list[tuple[str, float]]]: ... # (text_id, score), best first\n```\n\n- **`dense`** (Phase 1): loads `vectors.npy` with `mmap_mode=\"r\"`, restricts it to the\n strategy's candidate rows, and computes exact cosine scores (the vectors are L2-normalized, so\n this is a dot product). It works in query blocks to keep memory bounded. Ties are broken by\n `text_id`, so the output is deterministic.\n- **`bm25`** (optional, cheap): a lexical baseline over the same `Texto`, useful to check that\n strategy effects are not an artifact of one embedding model. It is listed here so the interface\n is not built around dense retrieval only. It is not needed for the first run.\n- Retrieval works on **texts**, not chunks, because vectors are stored per unique text. Each strategy\n is searched separately (S1, S2 and S3 have different candidate sets), but **all strategies share\n one scoring pass**: scores are computed once over all 84,568 texts and then filtered per strategy.\n The result is the same, and it costs less.\n\n### 3.3 From texts back to chunks\n\nSeveral chunks can share one text (for example an `ART` whose only content is one inciso has the\nsame text as that `INC` chunk). Inside one strategy they would get the same score and fill several\nranks with the same content. So each ranked item is **one text**, represented by its coarsest chunk\n(by `unit_precedence`). The other chunks with that text are kept as `alias_chunk_ids`. The relevance\nmatcher uses the union of the provenance of the chunk and its aliases.\n\n### 3.4 Output\n\nRetrieval keeps the **top-N = 1,000** texts per question and strategy (configurable). That is deep\nenough for Recall@1000 and for any token budget up to 16k tokens, even after de-duplication.\nContext selection and generation then read the stored ranking and never search again. §5 gives the\nfile layout.\n\n---\n\n## 4. Stage RE — retrieval evaluation (the legal-provision test)\n\n### 4.1 Gold items\n\nFrom `dataset/references.jsonl`, rows with `document_id` not null, per question:\n\n- **Document level:** the set of cited `document_id`s.\n- **Article level:** the set of `(document_id, article_id)` from the row-level `article_ids`.\n References without article ids (for example non-statutory acts cited as a whole) take part only\n at document level.\n- **Provision level:** `(lexml_file, fragment_id)` from `provisions[]`, the nested LexML ids parsed\n from the citation text (`art1_cpt_inc10`, `art12_par1_inc2`;\n `docs/20260927_213420_reference_provisions_from_citation_text.md`). Units with `fragment_id` or\n `lexml_file` `null` (41 not in the XML, 36 without an id form) are unreachable gold at this\n level.\n\n`origin` (`explicit` / `embedded`) is kept on each gold item so results can be sliced by it.\n\n### 4.2 Matching gold to chunks (`relevance.py`)\n\nThe matcher is **shared** with the later legal-provision score of the answers (nugget plan §4.5),\nso both use one definition of \"the right provision\".\n\n- **G1. Chunk → document.** `arquivo` → `document_id` through `documents.jsonl` (`lexml_file` and\n `lexml_annex_files`). This uses the file, not the URN, so the URN-quality issues of the\n non-statutory documents (dataset doc §7.5) do not affect it.\n- **G2. Chunk → article.** `(document_id, artigo_id)`. Any chunk of an article counts as an article\n hit, including a single inciso, a paragraph or an article part (`parte`/`n_partes`). For the\n **grouping** chunks of S3, an article is hit when the grouping contains it (interval containment\n through `Num_Inicio`/`Num_Final` within the same `arquivo`).\n- **G3. Main or annex (RIR/2018 case).** The gold says \"document D, article N\". Default rule: it\n matches article N in **the main file or in any annex file of D**. The number of gold items where\n both exist is reported, and the stricter \"main first, annex only if the main file lacks it\" rule\n (the one the dataset builder uses to validate article ids) is a switch\n (`--annex-rule {either,main_first}`), so its effect can be shown.\n- **G4.** A match that goes only through an `id_ambiguo = 1` chunk is counted, but also reported\n separately.\n- **G5. Chunk → provision.** A gold unit is **fully hit** by a chunk of the same `lexml_file` when\n an id in the chunk's `cobre_ids` equals the `fragment_id` or is its ancestor (prefix up to a\n `_`): the chunk holds the whole unit. It is **partly hit** when the `fragment_id` is an ancestor\n of a `cobre_ids` id, or appears in `parcial_ids`: the chunk holds only part of it (e.g. one inciso\n of a cited paragraph). Recall counts full hits; partial hits are reported next to them.\n- **Relevance is binary** (gain 1 for nDCG) at document and article level: a hit on the right\n inciso counts as much as a hit on the whole article. At provision level the full/partial split\n above is what measures \"which part\".\n\n### 4.3 Making strategies comparable\n\nThe strategy doc (§7) warns that raw k is not comparable: an S1 chunk is a whole article, an S2\nchunk may be one inciso. Three views are therefore reported, and **the token-budget view is the\nheadline**, because it matches what the LLM will get:\n\n| View | Ranked list | Cutoffs | Question it answers |\n|---|---|---|---|\n| **Token budget** (headline) | Texts in rank order after containment de-duplication (§6.1), taken while they fit in the budget, counted in `n_tokens_qwen3` | B ∈ {1k, 2k, 4k, 8k, 16k} | \"With the same amount of context, which strategy brings more of the cited provisions?\" |\n| **Unit projection** | Chunk ranking projected to distinct gold units (first rank at which each document / article appears) | k ∈ {1, 3, 5, 10, 20, 50, 100} | \"How high does the right article or document rank?\" This is the one that can be compared with other retrieval papers |\n| Raw chunk rank | Texts as retrieved | k ∈ {1, 5, 10, 20, 50, 100, 1000} | Diagnostic only |\n\nThe token-budget view uses **the same selection code as stage C** (§6.1), so the retrieval numbers\ndescribe exactly the contexts the generator will see.\n\n### 4.4 Metrics\n\nPer question, then averaged over questions that have at least one gold item at that level\n(document, article, provision):\n\n- **Recall** (fraction of gold items hit), **Hit** (at least one gold item hit), **Full recall** (all\n gold items hit);\n- **MRR** and **nDCG@10** on the unit-projection view;\n- **Context precision** on the token-budget view: the fraction of context tokens that come from\n gold documents / gold articles. This shows the \"less noise\" part of the S2 hypothesis (strategy doc\n §5.1);\n- the **oracle ceiling** per level and the counts of reachable and unreachable gold (§2.1).\n\n**Slices:** `origin` (explicit / embedded), statutory vs non-statutory gold, category-A annex gold,\nand the chapter of the Q&A document.\n\n**Paired comparison** S1 vs S2 and S2 vs S3: per-question differences with a **paired bootstrap**\n(10,000 resamples, fixed seed) 95 % CI and a **permutation test** p-value. The per-question table\nis saved, so other tests can be run later.\n\n### 4.5 Output of the first run\n\nA dated `docs/…_retrieval_legal_provision_test_jua.md` note with:\n\n1. the headline table: S1 / S2 / S3 × {document, article, provision} × token budget (recall, hit,\n context precision), with the oracle ceiling;\n2. the unit-projection table (Recall@k, MRR, nDCG@10);\n3. the paired-difference CIs;\n4. the reachability counts and the list of the known issues (§2.1) in force at run time;\n5. a few worked examples (questions where S2 finds the cited inciso and S1 misses it, and the\n reverse).\n\nThis test is **provisional**. It uses one embedding model and a corpus with known gaps. It is meant\nto see whether segmentation moves retrieval at all and in which direction, and to size the budgets\nfor the generation grid. It is not a paper result.\n\n---\n\n## 5. Run layout and formats\n\n```\nruns/\n retrieval/<embedding>/<instruction>/ e.g. jua-4b-mixed/irpf/\n manifest.json provenance (§8.3)\n <strategy>/rankings.csv.gz question_number, rank, text_id, chunk_id, alias_chunk_ids, score\n eval/<eval_id>/metrics.csv long format: strategy, level, view, cutoff, metric, value, n_questions\n eval/<eval_id>/per_question.csv.gz one row per question × strategy × level × view × cutoff (for paired tests)\n eval/<eval_id>/report.md generated tables\n eval/<eval_id>/manifest.json gold file hash, matcher rules (annex rule, gains), cutoffs\n contexts/<context_id>/contexts.jsonl + manifest.json Phase 2 (§6)\n answers/<run_id>/answers.jsonl + run.json + raw/ Phase 3 (§7); answers.jsonl follows nugget plan §4.1\n```\n\n- **Ids are readable and deterministic.** `context_id` = `<embedding>__<instruction>__<strategy>__<budget or k>__<dedup>`\n and `run_id` = `<context_id>__<llm>__<prompt version>`. The full config of each run is also hashed\n into the manifest, so two runs with the same id and different settings are detected.\n- **Versioned in git:** manifests, `metrics.csv`, `report.md`, the experiment YAML files, and\n `answers.jsonl` + `run.json` (small text). **Not versioned** (released on the HF Hub with the\n vectors): `rankings.csv.gz`, `per_question.csv.gz`, `contexts.jsonl` and the raw LLM responses.\n `.gitignore` gets rules like the ones for `embeddings/`.\n\n---\n\n## 6. Stage C — context selection (Phase 2)\n\n### 6.1 Selection\n\nInput: a stored ranking. Parameters (all recorded in the manifest):\n\n| Parameter | Values | Default |\n|---|---|---|\n| `cutoff` | `k=<n>` or `budget=<tokens>` | `budget=4000` (to be revisited after §4.5) |\n| `dedup` | `none`, `containment` | `containment` |\n| `overflow` | `skip` (skip a text that does not fit and keep filling), `stop` | `skip` |\n| `order` | `score`, `document` (group by document and sort by position in the document, a common option for legal text) | `score` |\n| `token_counter` | `qwen3` (the `n_tokens_qwen3` column) | `qwen3` |\n\n- **Containment de-duplication** (strategy doc §7, [L] §4.2): drop a text whose chunk interval\n `[Num_Inicio, Num_Final]` is inside the interval of a higher-ranked chunk **of the same\n `arquivo`**. The reverse case (a lower-ranked parent after a child) is kept by default, since the\n parent adds text. A `containment_merge` option that replaces the child with the parent is left for\n later.\n- **The budget is counted in one fixed tokenizer** (Qwen3, already in the chunk CSV) for every\n generator, so \"4k context\" means the same text for all LLMs. The generator's own count is checked\n in stage G against its context window.\n\n### 6.2 Formatting\n\nEach selected chunk is rendered with a short header built from provenance, then its `Texto`\n(which already starts with the `[ Epígrafe | Ementa ]` prefix):\n\n```\n[Documento 3] Lei nº 9.250, de 26 de dezembro de 1995 — Art. 8º, caput, II, b, 10\n<Texto>\n```\n\nThe template is a versioned file (`prompts/context_v1.pt.md`), so the header can change without\ncode changes. The citation-style path (`citacao`) is in the header so the generator can cite\nprovisions in a form the legal-provision score can parse later (nugget plan §4.5).\n\n### 6.3 Reference contexts\n\nTwo special context sets bound the results and use the same format:\n\n- **closed-book** (`k=0`): no context. It measures what the LLM knows without retrieval.\n- **oracle**: the gold articles of each question (by the §4.2 rules), in the same format and budget.\n It measures the best a retriever can do for this generator.\n\n---\n\n## 7. Stage G — generation / aggregation (Phase 3)\n\n### 7.1 Design goal: cheap experiments over LLMs and context size\n\nThe parameters most likely to change (LLM, number or budget of retrieved chunks, prompt version,\ndecoding settings) are **configuration, not code**. There are three ways to set them, from quick to\nreproducible:\n\n```bash\nR=scripts/rag/rag.py\n# 1. One run from the command line\n.venv/bin/python $R generate --retrieval runs/retrieval/jua-4b-mixed/irpf --strategy S2 \\\n --budget 4000 --llm sabia-3.1\n# 2. A small sweep from the command line (comma lists expand to the product)\n.venv/bin/python $R generate --retrieval runs/retrieval/jua-4b-mixed/irpf --strategy S1,S2 \\\n --budget 2000,4000,8000 --llm sabiazinho-3,deepseek-chat --limit 30\n# 3. A versioned experiment file (the form used for the paper runs)\n.venv/bin/python $R run --experiment scripts/rag/experiments/pilot.yaml [--dry-run]\n```\n\n```yaml\n# scripts/rag/experiments/pilot.yaml\nname: pilot\nquestions: {sample: stratified_30, seed: 13} # or \"all\", or a list\nretrieval: [runs/retrieval/jua-4b-mixed/irpf]\ngrid:\n strategy: [S1, S2]\n context: [{budget: 2000}, {budget: 4000}, {budget: 8000}, {k: 0}, {oracle: true}]\n llm: [gpt-5.x-mini, sabiazinho-3, deepseek-chat]\n prompt: [answer_v1]\nfixed: {dedup: containment, order: score, temperature: 0}\n```\n\n- `--dry-run` prints the expanded grid, the number of calls and an **estimated cost** (input tokens\n from the contexts × the prices in `llms.yaml`), and sends nothing. The grid grows fast (strategy ×\n embedding × budget × LLM), so every sweep should be sized before it runs.\n- `--limit` / `questions.sample` run a subset (pilot runs), using the same stratified sample as the\n nugget plan so pilot answers can be scored.\n\n### 7.2 LLM registry (`scripts/rag/llms.yaml`)\n\nThe code has no model-specific settings; adding a model means adding a YAML entry:\n\n```yaml\nllms:\n sabia-3.1:\n provider: openai_compat\n base_url: https://chat.maritaca.ai/api\n model_id: sabia-3.1 # pin the dated snapshot where the API offers one\n api_key_env: MARITACA_API_KEY\n context_window: 128000\n params: {temperature: 0, max_tokens: 1500}\n price: {usd_per_million_input: null, usd_per_million_output: null, checked: null}\n deepseek-chat:\n provider: openai_compat\n base_url: https://api.deepseek.com\n model_id: deepseek-chat\n api_key_env: DEEPSEEK_API_KEY\n # …\n gpt-5.x-mini:\n provider: openai\n model_id: <pinned snapshot>\n api_key_env: OPENAI_API_KEY\n # …\n```\n\nGenerators follow nugget plan D1: **OpenAI, Maritaca Sabiá and Sabiazinho, DeepSeek**. Maritaca and\nDeepSeek both offer OpenAI-compatible APIs, so **two providers (`openai`, `openai_compat`) cover all\nfour**, plus `fake` for tests. Model ids, snapshots, limits and prices are checked against the\nproviders' current documentation at implementation time and pinned in the YAML, as in the embedding\nplan.\n\n### 7.3 Prompt\n\n- A versioned pt-BR prompt file (`prompts/answer_v1.pt.md`) with a system part and a user part\n (`{question}`, `{context}`). It asks the model to answer from the given provisions, to say so\n when they are not enough, and to **cite the provisions it used** in standard Brazilian form\n (\"art. 8º, II, b, da Lei nº 9.250, de 1995\"), so the legal-provision score (nugget plan §4.5) can\n extract them. Note for that score: `lexml-linker` recognises this \"provision da Lei\" order, but\n not the act-first order of the Q&A document (\"Lei nº 11.482, de 2007, art. 1º, inciso X\" gives no\n URN; checked 2026-09-27). `scripts/dataset/citations.py`, which parses the gold, handles both\n orders and can be used on the answers too.\n- The prompt file's SHA-256 goes into `run.json`. Changing the prompt means a new version file, never\n an edit of a released one.\n- Answer length is not capped in the prompt beyond `max_tokens`. Length is reported per run, since\n nugget recall rewards longer answers (nugget plan §4.3, \"known limit\").\n\n### 7.4 Execution\n\n- **Cache** every raw response, keyed by hash(provider, model id, params, rendered messages). Reruns\n are free and the raw outputs can be released. This is the same scheme as the nugget plan (§5).\n- **Resumable:** questions already answered in a run are skipped.\n- **Bounded concurrency**, with retry and exponential backoff on 429/5xx; errors are recorded per\n question and never silently dropped (a failed question is marked in `answers.jsonl` with\n `\"error\"`, and `run.json` counts them).\n- **Outputs:** `answers.jsonl` in the nugget plan's input contract\n (`{\"run_id\", \"question_number\", \"answer\"}`) plus `context_id` and token usage per line, and\n `run.json` with the full config, the context manifest pointer, token totals and cost. Cost rows\n also go into a ledger `runs/costs.csv`, like `embeddings/costs.csv`.\n\n### 7.5 Shared LLM client (decision to confirm)\n\nStage G and the nugget scripts both need the same providers, cache, retry and cost accounting.\nRecommendation: **one small shared package** (for example `scripts/llm_client/`) used by both\n`scripts/rag/` and `scripts/nuggets/`, instead of two copies. Whichever of the two is implemented\nfirst creates it. The alternative (a copy in each, as self-contained as `scripts/embedding/`) is\nsimpler to release one piece at a time, but the two copies would drift.\n\n---\n\n## 8. Code design and release quality\n\n### 8.1 Files\n\n```\nscripts/rag/\n README.md quick start, formats, reproducing the paper runs (§8.4)\n rag.py CLI entry point (argparse subcommands)\n strategies.yaml strategy → Tipo sets, unit precedence, expected counts (§3.1)\n llms.yaml generator registry (§7.2) [Phase 3]\n prompts/ context_v1.pt.md, answer_v1.pt.md [Phase 2–3]\n experiments/ versioned experiment grids (§7.1) [Phase 3]\n requirements.txt pinned: numpy, pandas, pyyaml, tqdm (+ openai, python-dotenv in Phase 3)\n .env.example OPENAI_API_KEY=, MARITACA_API_KEY=, DEEPSEEK_API_KEY= [Phase 3]\n ragpipe/\n data.py load chunks, the v2.0 dataset configs and embedding outputs; all input checks (§8.3)\n strategies.py strategy filters, text ↔ chunk aliasing (§3.3)\n retrievers/ base.py (Retriever protocol), dense.py, [bm25.py]\n relevance.py gold items and the gold ↔ chunk matcher (§4.2); shared with answer evaluation\n context.py de-duplication, k / budget selection, formatting (§6) [selection used in Phase 1]\n metrics.py IR metrics, paired bootstrap / permutation (§4.4)\n generation.py prompt rendering, run loop [Phase 3]\n runs.py run ids, layout, manifests, config hashing (§5)\n report.py metrics.csv → markdown tables\n tests/ pytest; tiny fixture corpus, random vectors, fake LLM; no network, no GPU\n```\n\nThe embedding code is **not imported**. `ragpipe` reads only the documented embedding output format\n(embedding plan §4.2), so the vectors released on the Hub are enough to run retrieval without the\nembedding scripts.\n\n### 8.2 CLI\n\n```bash\nR=scripts/rag/rag.py\n.venv/bin/python $R check --embedding jua-4b-mixed # input checks only (§8.3)\n.venv/bin/python $R retrieve --embedding jua-4b-mixed [--instruction irpf] [--strategies S1,S2,S3] [--top-n 1000]\n.venv/bin/python $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf [--annex-rule either] [--budgets 1000,2000,4000,8000,16000]\n.venv/bin/python $R compare --retrieval runs/retrieval/jua-4b-mixed/irpf --a S1 --b S2 # paired CIs\n.venv/bin/python $R context --retrieval … --strategy S2 --budget 4000 # Phase 2\n.venv/bin/python $R llms # Phase 3: registry + env check\n.venv/bin/python $R generate … | run --experiment … # Phase 3 (§7.1)\n```\n\n- Every subcommand works with only its required option, using the repo's default paths.\n- `--help` shows an example for each subcommand. Errors say what to do (for example \"no query\n vectors for instruction 'jua_legal'; run `embed.py queries --model jua-4b-mixed\n --instruction-name jua_legal`\").\n- Phase 1 is just `retrieve` then `evaluate`, and together they should take well under a minute.\n\n### 8.3 Input checks and provenance\n\n`check` (and the start of every stage) fails loudly when:\n\n- the chunk file's SHA-256 differs from `input.sha256` of the embedding corpus manifest (the vectors\n would belong to other chunks);\n- `chunk_map.csv.gz` does not cover every `chunk_id`, or `texts.csv` does not match the vector rows;\n- query ids or texts differ from `dataset/questions.jsonl` (the text after the instruction prefix\n in `queries.csv → text_sent` must equal `question_text`);\n- a gold `document_id` is not in `documents.jsonl`, or a `documents.jsonl` file path does not\n appear in the chunks (reported as \"document without chunks\", not an error; §2.1).\n\nEvery manifest records: git commit + dirty flag, the command line, SHA-256 of every input (chunks,\nvectors, query vectors, `references.jsonl`, `strategies.yaml`, prompts), the resolved parameters, the\ncounts, and timings. This is the same scheme as the segmentation and embedding steps.\n\n### 8.4 README (for release)\n\n1. What the pipeline does, the stage diagram (§1) and the run layout (§5).\n2. Install (venv + `pip install -r requirements.txt`).\n3. **Quick start with released data:** download the dataset, chunks and vectors from the Hub, then\n `retrieve` → `evaluate` in two commands.\n4. Every file format with an example line.\n5. How to add a strategy (YAML), a retriever (one class), a generator LLM (YAML) and a prompt\n version (a file).\n6. Reproducing the paper runs: the exact experiment files and commands.\n7. License and citation.\n\n### 8.5 Code quality\n\n- Type hints; one docstring per module stating its responsibility; docstrings on public functions;\n small functions; no global state apart from the loaded configs.\n- **Deterministic:** stable tie-breaking, fixed seeds, sorted outputs, gzip with `mtime=0`; the same\n inputs give byte-identical rankings and metrics.\n- **Tests** (pytest, fixture corpus of a few documents with nested articles, an annex and a\n non-statutory file, with random normalized vectors):\n - strategy filtering and text aliasing;\n - the gold matcher: document, article, annex rule, grouping containment, split article parts;\n - containment de-duplication and budget selection (`skip` / `stop`);\n - metrics against hand-computed values (recall, MRR, nDCG, context precision);\n - input checks (hash mismatch, query text mismatch);\n - Phase 3: generation with the `fake` provider, cache hits, resume after a simulated crash, grid\n expansion and `--dry-run` cost estimate.\n- **No secrets** in logs, manifests or cached responses.\n\n---\n\n## 9. Phases and gates\n\n| # | Phase | Output | Gate |\n|---|---|---|---|\n| 1 | **Retrieval + legal-provision test** with `jua-4b-mixed`: scaffold, `data`, `strategies`, `dense` retriever, `relevance`, `context` selection (needed for the budget view), `metrics`, `report`, tests | `runs/retrieval/jua-4b-mixed/irpf/…` + dated `docs/` note (§4.5) | Tests pass; `check` passes; the report shows reachability and ceilings |\n| 1b | Optional: `bm25` baseline, instruction ablation (needs `embed.py queries` only) | extra eval ids | — |\n| 2 | Context formatting, closed-book and oracle contexts | `runs/contexts/…` | Contexts of a pilot sample reviewed by hand |\n| 3 | Generation: LLM registry, prompt v1, cache, run loop; pilot on 30 questions | `runs/answers/<run_id>/…` | Pilot answers read by hand; cost per full run estimated |\n| 4 | Full grid (sized with the Phase 1 results and the Phase 3 cost estimate), scoring in `scripts/nuggets/` | answer runs + nugget scores | Nugget plan phases 4–5 |\n| 5 | Release: code, rankings, contexts, answers, raw responses | HF dataset files + repo | README quick start works in a clean venv |\n\nEach phase ends with a dated `docs/` note (decisions, results, deviations), and `CLAUDE.md` gets the\n`runs/` folder once Phase 1 creates it.\n\n---\n\n## 10. Decisions to confirm (defaults chosen)\n\n1. **Annex rule** (§4.2 G3): `either` by default, `main_first` reported as a variant.\n2. **Headline budgets:** 1k / 2k / 4k / 8k / 16k Qwen3 tokens; the generation default (4k) is\n revisited after the Phase 1 results.\n3. **Top-N stored:** 1,000 per question and strategy.\n4. **Shared LLM client** for `scripts/rag/` and `scripts/nuggets/` (§7.5): recommended.\n5. **Package name** `ragpipe` and outputs under `runs/`.\n6. **Provision-level retrieval gold** (§4.1): part of Phase 1, now that `references.jsonl` carries\n nested `fragment_id`s (fixed 2026-09-27).\n","20260927_213420_reference_provisions_from_citation_text.md":"# Reference Provisions Parsed from the Citation Text (fix of `references.jsonl`)\n\n**Generated:** 2026-09-27 21:34:20 (local time, from `date +%Y%m%d_%H%M%S`)\n**Status:** implemented and run. `dataset/references.jsonl` and `dataset/build_report.json` rebuilt.\n**Corrects:** `docs/20260927_180401_dataset_v2_format_and_reference_fixes.md` §3.2 (the\n`provisions` design) and its schema in `dataset/README.md`.\n\n---\n\n## 1. The error\n\nThe v2.0 `references` rows stored each cited article with **flat lists** of paragraphs, incisos,\nalíneas and items, copied from v1.1's LLM-extracted `formatted_references`. The flat lists lose the\nnesting, so two different citations got the same shape:\n\n| Citation in the Q&A document | v2.0 (before) | Meaning |\n|---|---|---|\n| Q001: \"Lei nº 11.482/2007, art. 1º, **inciso X e parágrafo único**\" | `paragraphs: [\"único\"], incisos: [\"X\"]` | two sibling units: `art1_cpt_inc10` and `art1_par1u` |\n| Q051: \"IN RFB nº 2.178/2024, art. 12, **§ 1º, inciso II**\" | `paragraphs: [\"1º\"], incisos: [\"II\"]` | one unit: `art12_par1_inc2` |\n\n575 rows had such lists. Of the 140 (article, paragraph, inciso) combinations, the LexML alone\nsettles 95. In 38, both readings exist in the XML (for example `art12_cpt_inc2` and\n`art12_par1_inc2`), and in 7 neither does.\n\n**How it happened.** The dataset note (§3.2) said: *\"v1.1 lost which inciso belongs to which\nparagraph, and that cannot be recovered reliably\"*, and deferred provision-level ids to\n`lexml-linker`. Both parts were wrong:\n\n- The nesting is in the **citation text itself**, which v1.1 keeps (`references`,\n `embedded_references`, carried into v2.0 as `references_text` / `embedded_references_text`).\n Word order gives it: \"art. 12, § 1º, inciso II\" is a path, \"inciso X e parágrafo único\" is a\n list of siblings, and \"inciso II do § 1º do art. 162\" is a path written in reverse.\n- `lexml-linker` is unrelated to the gold references. It is for citations in *generated* answers,\n and it does not even recognise the Q&A style, where the act comes first\n (\"Lei nº 11.482, de 31 de maio de 2007, art. 1º, …\" gives no URN).\n\nThe builder simply never parsed the text. It also inherited two other v1.1 extraction errors, found\nby the fix below: **ranges cut short** (\"arts. 128 a 153\" was stored as art. 128 only), which\ntogether with a few treaty articles left 262 article ids missing from 33 rows, and **invented articles** for acts cited without any article (11\narticle ids in 5 rows).\n\n## 2. The fix\n\n### 2.1 Parser (`scripts/dataset/citations.py`)\n\nA parser for the citation style of the Q&A document:\n\n1. **Chains.** `find_chains` finds each run of provision tokens: `art.`/`arts.`/`artigo`, `§`/`§§`/\n `parágrafo`, `caput`, `inciso`, `alínea`/quoted letters, `item`/`itens`, `Anexo`, `Capítulo`/\n `Seção`/`Título`. The values can be ordinals, thousands (`1.042`), suffixes (`12-A` → `art12-1`),\n `único`, roman numerals, letters and decimals (`item 19.1`). The joins are `,`, `e`, `, e`, ranges\n (`a`/`ao`/`até`, expanded up to 300), and the genitive `do`/`da`/`de seu`.\n2. **Reverse order.** A genitive link (\"inciso II do § 1º do art. 162\") is rewritten into a forward\n path (`art162_par1_inc2`).\n3. **Nesting.** A stack puts each unit under the nearest open unit of a higher level. An\n inciso, alínea or item with no paragraph above it belongs to the caput (`_cpt_`). A unit is\n cited when nothing is attached under it, or when a child follows it with \"e\" (\"art. 26 e\n parágrafo único\" cites both).\n4. **Values without a keyword.** A roman numeral is an inciso and a letter is an alínea. A bare\n arabic number continues the last open plural list (\"arts. 2º, inciso IV, 4º e 6º\" → articles). A\n list closed by \"e\" takes no more values (\"§§ 1º e 4º, e 7º\" → art. 7º). A number followed by\n `caput`/`§` is an article (\"§§ 2º a 4º, 16, caput\" → art. 16).\n5. **Attribution to the cited acts** (`attribute`):\n - Each v1.1 reference is found in the text by its number (`nº 9.250`); the RIR/2018 by its name;\n unnumbered acts (Constituição, conventions) by the head of the title.\n - A chain followed by \"do/da <act>\" goes to the next act mention. Any other chain goes to the\n closest mention before it. In the explicit block, \"…; e art. 6º\" continues the previous act.\n - Mentions that are not the cited act are skipped: \"aprovado pelo Decreto nº 9.580\",\n \"alterada pela Lei nº …\".\n - Mentions of acts that no v1.1 reference claims become anonymous anchors, so their provisions\n are not given to a neighbour. The build **fails** if any chain is left without a reference.\n\n### 2.2 New `references` fields\n\n`provisions` is now **one row per cited unit**, with the nesting in the LexML id (the same scheme\nas the chunks' `unidade_id` / `cobre_ids`):\n\n```json\n\"citation_text\": [\"Lei nº 11.482, de 31 de maio de 2007, art. 1º, inciso X e parágrafo único\"],\n\"article_ids\": [\"art1\"],\n\"provisions\": [\n {\"label\": \"art. 1º, inciso X\", \"article_id\": \"art1\", \"fragment_id\": \"art1_cpt_inc10\",\n \"annex\": null, \"lexml_file\": \"lexml/articulados/lei_11482_20070531.xml\"},\n {\"label\": \"art. 1º, parágrafo único\", \"article_id\": \"art1\", \"fragment_id\": \"art1_par1u\",\n \"annex\": null, \"lexml_file\": \"lexml/articulados/lei_11482_20070531.xml\"}],\n\"provisions_note\": null\n```\n\n| Field | Content |\n|---|---|\n| `citation_text` | the source text the provisions were parsed from (the `;`-pieces of the reference block, or the embedded citation strings), so the gold can always be checked against the source |\n| `article_ids` | distinct cited articles (row level; replaces `provisions[].article_ids`) |\n| `provisions[].label` | canonical citation path (\"art. 736, parágrafo único, inciso II\") |\n| `provisions[].fragment_id` | LexML id with the full path; `null` when the unit has no id form (annex items, chapters, numbered items of pareceres, \"inciso 1.8\") |\n| `provisions[].annex` | \"Anexo II\" etc., when the unit is in an annex |\n| `provisions[].lexml_file` | the LexML file holding `fragment_id`: the main file or an annex file (for the RIR/2018 and \"do Anexo\" citations the annex files are searched first); `null` when not found |\n| `provisions_note` | the reason, when the provisions come from a hand override (§2.3) |\n\nRemoved: `provisions[].article`, `.article_ids`, `.paragraphs`, `.incisos`, `.alineas`, `.items`.\n`annexes` stays (v1.1 annex labels plus annex-only units from the text).\n\n### 2.3 Hand overrides (`reference_overrides.json → citations`)\n\nFor 5 references the text can't be parsed as written. Each entry gives the source wording, the\ncitation parsed in its place, and the reason:\n\n| Ref | Source | Parsed as | Why |\n|---|---|---|---|\n| Q143, Q144 Convenção de Viena | \"art. 37, 2\" / \"art. 37, 2 e 4\" | \"art. 37, caput, item(s) 2 (e 4)\" | treaty numbering; the LexML holds the numbered paragraphs as `art37_cpt_ite2` |\n| Q154 Decreto 86.084 | \"art. IX, 2\" | \"art. IX, item 2\" | same treaty numbering |\n| Q511 IN SRF 83 | \"art. 5º; § 2º, inciso III\" | \"art. 5º e § 2º, inciso III\" | `;` typo for `,`; both readings kept |\n| Q517 Lei 11.524 (embedded) | \"o artigo 3º da referida lei … o inciso III do § 1º do mesmo artigo\" | \"art. 3º; inciso III do § 1º do art. 3º\" | the law is named elsewhere in the answer |\n\n## 3. Cross-check against v1.1\n\nPer reference, the articles found in the text were compared with v1.1's article lists before the\nlists were dropped:\n\n| Result | References |\n|---|---:|\n| Same articles | 1,326 with articles + 520 citing the whole act |\n| Text has more articles (262 article ids, almost all from ranges v1.1 cut short) | 33 |\n| v1.1 has articles the text does not (`build_report.json → validation.v1_article_ids_not_in_citation_text`) | 5 |\n\nThe 5 v1.1-only cases were checked against the whole answer text. None of those articles appears\nanywhere, so they are LLM inventions and are dropped:\n\n- Q150 UPU (art. 1 and art. 10): the source cites only \"UPU\".\n- Q239 FGTS (7 articles): the source is \"Lei do Fundo de Garantia do Tempo de Serviço (FGTS)\".\n- Q652 Lei 9.615 (art. 1): the act is cited without articles.\n- Q611 IN SRF 107 (art. 1): the source cites \"inciso 1.8\". The unit is kept with its label and no\n id.\n\n## 4. Results\n\n`python3 scripts/dataset/build_v2_dataset.py`:\n\n| | Count |\n|---|---:|\n| References (unchanged) | 1,919 |\n| References with provisions | 1,349 (2,319 units) |\n| Units by depth: article / § or caput / inciso / alínea / item | 1,445 / 392 / 375 / 65 / 6 |\n| References with sub-article units | 567, in 366 questions |\n| Cited article ids | 2,052 (was 1,801) |\n| Units found in the main LexML file / in an annex file | 1,626 / 615 |\n| Units without an id form | 36 |\n| Units whose `fragment_id` is not in the LexML | 41 (`validation.fragment_ids_missing`) |\n\nThe 41 missing fragments are XML or source issues, not parser errors:\n\n- **Known gaps** (dataset note §7.1–7.2): the treaty decrees with an empty `<Articulacao>` (Q149–159),\n MP 2.158-35 art. 24, Lei 13.043 art. 16, Lei 11.941 art. 56, Lei 6.404 art. 252 and\n Decreto 59.566 art. 3.\n- **New, seen at provision level:**\n - Lei 9.250 art. 10: the XML has incisos I–IX only, but Q018 cites inciso X.\n - Lei 6.015 art. 167, I: the numbered items were parsed as alíneas (`ali24`); Q093 and Q209 cite\n items.\n - IN RFB 2.178 art. 11, § 2º: the XML has no incisos (Q460).\n - Lei 11.033 art. 3º: the XML (current text) has §§ 1º–4º, but Q708 cites a \"parágrafo único\".\n - Lei 12.350 art. 45, § 3º: the § 3º is inside an amendment block\n (`art45_cpt_alt1_art8_par3`).\n\nTests: `scripts/dataset/tests/test_citations.py` (36 cases taken from the Q&A document), run with\n`python3 -m pytest scripts/dataset/tests`.\n\n## 5. Consequences\n\n- **Provision-level retrieval gold is available now.** A retrieved chunk hits a gold unit when some\n id in its `cobre_ids` equals the `fragment_id` or is its ancestor (prefix up to a `_`), within\n the same `lexml_file`. The RAG plan (`docs/20260927_204356_rag_pipeline_implementation_plan.md`\n §4.1) no longer defers this level.\n- The legal-provision score of the answers (nugget plan §4.5) gets nested gold fragment ids, and\n the matcher can use the same file-level match.\n","20260927_222210_retrieval_legal_provision_test_jua.md":"# Retrieval Legal-Provision Test with `jua-4b-mixed` (RAG pipeline Phase 1)\n\n**Generated:** 2026-09-27 22:22:10 (local time, from `date +%Y%m%d_%H%M%S`)\n**Status:** implemented and run. Provisional result (one embedding model, corpus with known gaps).\n**Plan:** `docs/20260927_204356_rag_pipeline_implementation_plan.md` (Phase 1: stages R and RE).\n**Code:** `scripts/rag/` (usage and formats in `scripts/rag/README.md`).\n**Outputs:** `runs/retrieval/jua-4b-mixed/irpf/` (rankings) and\n`runs/retrieval/jua-4b-mixed/irpf/eval/either_containment_skip/` (`report.md` has every table).\n\n> **Note (2026-10-08):** this test ran on the **old corpus** (chunk file `f3db0904…`). By the\n> definitions of `docs/20261005_184116_*`, its S2/S3 are **S2c/S4**: the paragraph chunks carried the\n> caput sentence. The corpus was rebuilt on 2026-10-08 and the retrieval re-run with S1/S2/S3/S2c/S4;\n> see `docs/20261008_010441_corpus_rebuild_results.md`. The rankings under `runs/retrieval/jua-4b-mixed/irpf/S*/` now belong to the new run.\n> This evaluation's `report.md`/`metrics.csv` are kept as they were.\n\n---\n\n## 1. What was run\n\n```bash\nR=scripts/rag/rag.py\n.venv/bin/python $R check --embedding jua-4b-mixed\n.venv/bin/python $R retrieve --embedding jua-4b-mixed # 11 s\n.venv/bin/python $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf # 15 s\n```\n\n- **Inputs:** chunks `segmented/chunks_all.csv.gz` (SHA-256 `f3db0904…`, the file the\n `jua-4b-mixed` corpus manifest records), corpus vectors [84,568 × 2,560], query vectors of\n instruction `irpf` [715 × 2,560], dataset v2.0 after the provision fix\n (`docs/20260927_213420_reference_provisions_from_citation_text.md`). `check` passes. Its only\n warning is the 11 cited documents without chunks (§4).\n- **Retrieval:** exact cosine, top-1,000 texts per question and strategy, S1 / S2 / S3 as in\n `scripts/rag/strategies.yaml`.\n\n | | Chunks | Texts |\n |---|---:|---:|\n | S1 | 26,250 | 26,208 |\n | S2 | 82,642 | 79,508 |\n | S3 | 87,702 | 84,568 |\n\n- **Evaluation:** annex rule `either`, containment de-duplication, overflow `skip`, budgets\n 1k–16k Qwen3 tokens, paired bootstrap (10,000 resamples, seed 13) and sign-flip permutation\n tests.\n- **Determinism:** a second run of both stages gave byte-identical rankings, `metrics.csv`,\n `per_question.csv.gz` and `comparisons.csv`.\n- **Tests:** 23 pytest tests on a fixture corpus pass (`scripts/rag/tests`).\n\n## 2. Headline: token-budget view, all resolved gold\n\nRecall of the gold items of each question, averaged over questions. \"Oracle\" is the ceiling given\nthe corpus gaps (§4).\n\n| Level (questions) | Strategy | 1k | 2k | 4k | 8k | 16k | Oracle |\n|---|---|---:|---:|---:|---:|---:|---:|\n| Document (594) | S1 | 0.378 | 0.495 | 0.613 | 0.718 | 0.796 | 0.993 |\n| | S2 | **0.453** | **0.548** | **0.635** | **0.727** | **0.804** | 0.993 |\n| | S3 | 0.450 | 0.543 | 0.630 | 0.716 | 0.794 | 0.993 |\n| Article (553) | S1 | 0.170 | 0.270 | 0.388 | 0.491 | 0.576 | 0.985 |\n| | S2 | **0.278** | **0.354** | **0.435** | 0.530 | 0.617 | 0.985 |\n| | S3 | 0.273 | **0.354** | 0.430 | **0.532** | **0.631** | 0.985 |\n| Provision, full (558) | S1 | 0.157 | **0.243** | **0.358** | **0.462** | 0.540 | 0.961 |\n| | S2 | 0.165 | 0.228 | 0.327 | 0.439 | 0.541 | 0.961 |\n| | S3 | **0.170** | 0.232 | 0.337 | 0.447 | **0.559** | 0.961 |\n| Provision, full or partial | S1 | 0.166 | 0.261 | 0.370 | 0.474 | 0.558 | 0.961 |\n| | S2 | **0.249** | 0.315 | 0.398 | 0.501 | 0.589 | 0.961 |\n| | S3 | 0.245 | **0.317** | **0.399** | **0.502** | **0.601** | 0.961 |\n\nContext precision is the share of context tokens that come from texts hitting a gold article:\n\n| | 1k | 2k | 4k | 8k | 16k |\n|---|---:|---:|---:|---:|---:|\n| S1 | 0.145 | 0.141 | 0.126 | 0.089 | 0.057 |\n| S2 | 0.223 | 0.204 | 0.184 | 0.148 | 0.106 |\n| S3 | 0.221 | 0.211 | 0.194 | 0.170 | 0.142 |\n\nThe budgets are filled: the mean selected context is 983–985 tokens at 1k and 15,982–15,985 at 16k,\nwith 4–49 texts.\n\n## 3. Findings\n\n1. **S2 beats S1 at document and article level at every budget.** Article recall S2 − S1:\n **+10.8 pts at 1k** [+8.3, +13.4], +8.4 at 2k, +4.7 at 4k, +3.9 at 8k, +4.1 at 16k (all p ≤ 0.0002).\n Context precision is higher at every budget (+4.9 to +7.8 pts, p = 0.0001). The same holds in\n the unit projection, which compares with other retrieval papers: article R@10 is 0.505 → 0.543,\n nDCG@10 0.397 → 0.427. **S2 finds the cited articles with less noise.**\n2. **At provision level the effect depends on what the gold cites.**\n\n | 4k budget, provision recall | S1 | S2 | S3 |\n |---|---:|---:|---:|\n | Sub-article gold (caput / § / inciso / alínea / item; 366 questions) | 0.328 | **0.376** | 0.369 |\n | Whole-article gold (\"art. 2º\"; 429 questions) | **0.345** | 0.243 | 0.260 |\n | Whole-article gold, full or partial | 0.359 | 0.358 | 0.358 |\n\n On **sub-article** gold, S2 gains +4.8 to +8.4 pts at every budget, which is the S2 hypothesis\n of the strategy doc (§5.1). On **whole-article** gold, S2 retrieves *a part* of the cited\n article as often as S1 retrieves the whole (partial recall is equal), but it puts the whole\n `ART` chunk in the context less often, so full recall drops by 6–10 pts. Overall provision\n recall is therefore not significantly different at 1k, 2k and 16k, and S1 is ahead at 4k\n (−3.1 pts [−5.6, −0.7], p = 0.010) and 8k (−2.4 pts, p = 0.028). Whether a part of an article\n is enough to answer is exactly what the nugget evaluation will decide. The retrieval test\n cannot.\n3. **S3 (groupings) adds little.** S3 − S2 is within ±1 pt at document level and on article\n recall up to 8k. S3 is slightly better on provision full recall at 4k and 16k (+1.8 / +2.5 pts,\n p ≈ 0.01–0.02), because chapter chunks hold whole articles. It is worse on the article unit\n projection (R@10 −2.8 pts, p = 0.001), because a grouping chunk takes many unit positions.\n This matches the strategy doc's expectation: keep **S1 vs S2** as the main comparison.\n4. **Embedded references are hard:** at 4k, article recall is 0.13 for embedded gold vs 0.42–0.48\n for explicit gold. Embedded references are the acts cited *inside* the answer text, often\n side remarks.\n5. **Budgets for the generation grid:** the S1–S2 gap is largest at 1k–2k and the recall curves\n are still rising at 16k (article recall 0.62 for S2). The 4k default of plan §6.1 is a\n reasonable middle point. 2k and 8k bracket it.\n\n## 4. Reachability and known issues in force\n\nFrom `reachability.csv` (gold items, identical across strategies after the split-article rule, §5):\n\n| Level | Gold items | Reachable | Unreachable | Reason |\n|---|---:|---:|---:|---|\n| Document | 1,687 | 1,673 | 14 | 11 cited documents without chunks (empty `<Articulacao>`) |\n| Article | 1,957 | 1,933 | 24 | 8 in documents without chunks, 16 article ids missing from the LexML |\n| Provision | 2,229 | 2,160 | 69 | gold units without a LexML id (annex-only citations, \"item 9\" of pareceres, ids not in the XML) |\n\n- 42 references are `not_in_corpus` and are not counted as gold.\n- **G3 (main/annex):** the main file and an annex both have the cited article in only 3 article\n items (4 provision items), so `either` vs `main_first` hardly matters for this run.\n- **G4:** no gold item is reachable only through `id_ambiguo = 1` chunks.\n- **Non-statutory provisions** (10 questions, \"item 18\" of a Parecer Normativo, etc.) have no\n LexML id and are all unreachable. Non-statutory gold counts only at document level.\n- `strategies.yaml` records the chunk counts of the current chunk file. The plan quotes 26,252 /\n 82,644 / 87,947 from the 2026-09-24 run, before the over-limit grouping chunks\n (`segmented/groupings_over_limit.csv`) were dropped.\n\n## 5. Deviations from the plan\n\n1. **Split articles in G5 (provision matching).** The plan's rule is per chunk: a unit is fully hit\n when one chunk holds it. An article long enough to be split into `parte 1..n` ART chunks is then\n never fully hit in S1/S2 when it is cited as a whole. That made 108 (S1) and 98 (S2) provision\n items unreachable while S3 reached them through grouping chunks, and 65 more were unreachable in\n every strategy. The matcher now also counts a unit as fully hit once **all the parts of the\n split article that hold it** are retrieved (rank = the rank of the last part). The budget view\n checks that all those parts are in the context. After the change the provision oracle is 0.961\n for all three strategies. `reachability.csv` counts the items that only this rule makes\n reachable (`reachable_by_split_parts_only`: 173 / 163 / 65).\n2. **Extra columns** `gold` (`all` / `reachable`) and `slice` in `metrics.csv` and\n `per_question.csv.gz`. Plan §5 lists only `strategy, level, view, cutoff, metric, value,\n n_questions`.\n3. **Extra outputs:** `per_item.csv.gz` (per gold item, used for the examples below),\n `reachability.csv`, `comparisons.csv`, `metrics_by_chapter.csv.gz`. `per_item`,\n `per_question` and the per-chapter file are not versioned (size).\n4. **Module layout:** the stage drivers are in `ragpipe/retrieval.py` and `ragpipe/evaluation.py`,\n so `rag.py` only parses arguments. There is also a `report` subcommand that regenerates\n `report.md`.\n5. **Chapter slice:** the dataset has no chapter field. The ranges were taken from the table of\n contents of the P&R PDF (48 chapters) and stored in `scripts/rag/data/pr_irpf_2024_chapters.csv`.\n They could become a `chapter` field of the `questions` config in a later dataset build.\n6. **Unit projection:** a grouping chunk (S3) stands for every article it contains, in document\n order. Positions beyond 1,000 distinct units count as not retrieved (this bounds the work for\n `PARTE`/`LIVRO` chunks). MRR and nDCG@10 are reported at cutoff `-` of the `unit` view.\n Provision level has no unit projection.\n7. **Evaluation needs no vectors:** `evaluate` reads the rankings (representative chunk + aliases),\n the chunks and the dataset. It checks that the chunk file and the ranking files match the\n retrieval manifest.\n\n## 6. Worked examples (4k budget, provision level)\n\n**S2 finds the cited unit, S1 misses it** (83 sub-article gold items; the reverse happens for 59):\n\n| Q | Gold | S1 full rank | S2 full rank |\n|---|---|---:|---:|\n| 128 \"Como são tributados os rendimentos recebidos no Brasil por não residente?\" | IN RFB 1.500/2014, art. 19, inciso XVI | 590 | **1** |\n| 124 \"…deduções de pagamentos efetuados em moeda estrangeira na Declaração de Saída Definitiva…\" | IN SRF 208/2002, art. 9º, § 7º | 15 | **1** |\n| 120 | IN SRF 208/2002, art. 2º, inciso IV | 15 | **3** |\n| 179 | IN RFB 1.500/2014, art. 62, caput, inciso XIII | 620 | **7** |\n\nIn Q128 the whole IN 1.500 art. 19 is a long list of incisos. Its S1 vector is diluted and ranks\n590th, while S2 matches the one inciso at rank 1. This is the S2 case of the strategy doc (§5.1).\n\n**S1 has the whole cited article, S2 only a part** (107 whole-article gold items; the reverse\nhappens for 2):\n\n| Q | Gold | S1 full rank | S2 first part | S2 whole article |\n|---|---|---:|---:|---:|\n| 001 \"Quem está obrigado a apresentar a Declaração de Ajuste Anual…?\" | IN RFB 2.178/2024, art. 2º | 4 | 2 | 37 |\n| 005 (CNPJ of associations) | IN RFB 2.178/2024, art. 2º | 4 | 1 | 41 |\n| 031 (\"Meu Imposto de Renda\") | IN RFB 2.178/2024, art. 5º | 2 | 1 | 26 |\n\nHere S2 shows its failure mode. In Q005 its top text is art. 2º, § 3º (a taxpayer may not appear\nin more than one return). That is a sibling unit of the cited article, but not the provision that\nanswers the CNPJ question, and the whole article that holds the answer only comes at rank 41. S1\nranks the whole article 4th. A matching fragment can crowd out the article that holds the answer.\nThe nugget evaluation will show how often a partial hit is still enough.\n\n## 7. Next steps\n\n- Phase 1b (optional): BM25 baseline and the instruction ablation, to check that the S1/S2\n pattern is not specific to this embedding model.\n- Phase 2: context formatting (`prompts/context_v1.pt.md`), closed-book and oracle contexts.\n Selection is already implemented and tested (`ragpipe/context.py`).\n- Rerun `retrieve` + `evaluate` whenever the corpus gaps of §4 are fixed. The manifests record\n the chunk and dataset hashes, so results of different fix levels cannot be mixed up.\n","20260929_111356_fiscalqa_pro_temporal_misgrounding_comparison.md":"# FiscalQA Pro (arXiv:2608.09393) vs. our research: temporal grounding and deterministic nuggets\n\n**Generated:** 2026-09-29 11:13:56 (local time, from `date +%Y%m%d_%H%M%S`)\n**Paper:** Cymbler, Guez, Fabre — *Temporal Misgrounding in Legal RAG: A Versioned-Corpus Benchmark\nfor French Tax Law*, arXiv:2608.09393v1 (10 Aug 2026), ICML 2026 Workshop AI4Law. Code and data:\n`github.com/rosecymbler/fiscal-fr-bench`. Referred to below as **[FQ]**.\n**Goal:** (1) explain the temporal problem [FQ] studies, (2) explain how its deterministic nuggets\nscore answers, (3) compare both with our goals (hierarchical segmentation for RAG over the P&R IRPF\n2024, scored with nuggets), and (4) list what we should adopt. Section 4 includes measurements on\nour own data taken for this note.\n\n---\n\n## 0. Summary\n\n- [FQ] asks a **different question** from ours. It studies **which version** of a legal article\n must be retrieved (time). We study **which unit** of a legal document should be retrieved\n (structure). The two axes are orthogonal, but they meet in our corpus (§4).\n- **Temporal misgrounding** = retrieving and citing the version of an article that is in force\n **now**, when the question needs the version that applied at an earlier (or later) date. [FQ]\n shows that with a current-only corpus it is almost total (2.7 % strict), and that indexing all\n versions and selecting one by the question's date almost removes it (98.3 %).\n- **Deterministic nuggets:** each question has **two** hand-written nuggets: a **regex** on the\n article number and a **numeric match with tolerance** on the value at the question's date. No\n LLM judge is used. Their reason: an LLM judge shares the same recency bias it is supposed to\n measure.\n- **For us:** our corpus is the **current consolidated text** (*vigente* view, fetched in 2026),\n while the gold answers are anchored in **exercício 2024 / ano-calendário 2023** (P&R published\n 2024-05-03). In [FQ]'s terms, every run we make is their **Condition B** (static current\n corpus), and our \"oracle\" context is B with the gold article, not their version oracle.\n Brazilian consolidated texts soften the problem: annual values are often **added as new items**\n inside the same article, so older values stay in the text. But wording that was **rewritten in\n place** is lost.\n- **Exposure (measured, §4.3):** 33 of the 218 referenced statutory documents carry amendment notes\n dated after May 2024. 116 of the 596 questions with resolved references cite at least one of\n them. Only 77 answers contain R$ amounts and 86 contain percentages, so a numbers-only scheme\n like [FQ]'s could cover only a small part of our 715 prose answers.\n- **Recommendation (§5):** keep the LLM-judge nugget protocol for rules and conditions. Add\n [FQ]-style **deterministic value checks** for `valor_prazo` nuggets, a **temporal slice** in the\n reports, a **reference date in the generation prompt**, and a year-aware reading of the\n `contradicts` label.\n\n---\n\n## 1. The paper in brief\n\n| Item | [FQ] |\n|---|---|\n| Domain | French tax law: CGI (+ 4 annexes) and LPF |\n| Corpus | **32,436 article-versions** over 8,076 articles (4.02 versions per article; CGI art. 81 has 94). Span 1938–2031, including **future-effective** versions. Built from Légifrance `getArticleByCid`, which returns the full version history with `date_debut` / `date_fin` / `etat` per version |\n| Auxiliary resource | 69,208 version-aware links from court decisions to the article version in force at the decision date (regex extractor, 98–99 % precision). Not used in the main experiment |\n| Benchmark | Four regimes: R1 citation extraction, R2 computation, **R3 temporal reasoning** (the main track), R4 multi-document synthesis. R3 has 221 questions (209 scored) over 33 CGI articles |\n| Question creation | A script finds value changes between consecutive versions (\"drift points\"). The authors write each question, its date anchor, the answer and the nuggets. A French tax professional reviews them |\n| Filters | (a) **Parametric filter:** a question is dropped if any of the 11 models gives the gold value closed-book in any of 4 draws (\"all-model-hard\"). (b) **Divergence filter:** a question is dropped if the gold value still appears in the current version of the article |\n| Conditions | **A** LLM only · **B** RAG over the current corpus, **given the gold article** · **C_or** gold article, version chosen by date (oracle) · **C_prod** end-to-end: dense (domain-adapted encoder) + BM25 with RRF over a multi-version index (3 versions per article), top-5 articles, then a version layer picks each article's version by date |\n| Models | 11: Opus 4.7/4.8, Sonnet 4.6, GPT-5.4/5.5, Gemini 2.5 Pro, Mistral Large, Llama 4 Maverick, Qwen 3 235B, Gemma 3 27B, GLM 5.2 |\n| Main results (mean strict) | A 3.0 %, B 2.7 %, C_or 99.1 %, C_prod 98.3 %. Provenance (gold version retrieved): B 0 %, C_or 100 %, C_prod 99 % |\n| Statistics | Cluster bootstrap over articles (33 clusters, 10k iterations), McNemar per model, Wilcoxon on coverage, leave-one-article-out |\n\n---\n\n## 2. The temporal discussion, clarified\n\n### 2.1 What \"temporal misgrounding\" is\n\nTax statutes are **amended in place**: the article keeps its number, but its text (a rate, a\nthreshold) changes every year or so through finance laws. A question such as \"what was the\ncorporate tax rate for fiscal years opening on or after 1 Jan 2018?\" has one correct answer\n(33⅓ %, the 2018 version of CGI art. 219), which is not the current value (25 %). **Temporal\nmisgrounding** is the failure in which the system retrieves, uses and cites the **currently in\nforce** version instead. The answer is then wrong **and** looks well grounded: the article exists,\nand the citation is real.\n\n[FQ] names three causes that act together:\n\n1. **Parametric recency bias.** Training data over-represents current law, so the LLM's prior is\n the current value.\n2. **No temporal conditioning in retrieval.** Dense retrievers rank by meaning and ignore the date\n in the query.\n3. **Article-number aliasing.** \"Art. 219\" names every version, so the identifier does not say\n which one is meant.\n\nAnd three properties of legal corpora explain why static retrieval cannot fix it:\n\n- **(P1) Same identifier, different content.** The (article, version) pair, not the article,\n carries the content. A single-snapshot index keeps one point per article.\n- **(P2) Date-dependent correctness.** Each version has an explicit validity interval. For a given\n date exactly one version is right. A \"nearly right\" version is simply wrong.\n- **(P3) Cross-version similarity.** Consecutive versions often differ by one number, so their\n embeddings are nearest neighbours. Similarity alone cannot tell them apart.\n\n### 2.2 Failure modes (taxonomy)\n\n| Mode | What happens | Evaluated in [FQ]? |\n|---|---|---|\n| **Current-law substitution** | The in-force version is returned whatever the query date | **Yes** (the only one; all B errors are of this type) |\n| Future-law leakage | A version that is enacted but not yet in force is returned for a present-tense question | No (future work; the corpus has such versions up to 2031) |\n| Wrong-amendment resolution | \"Art. X in the wording before Law Y\" returns the current or an arbitrary version | No |\n| Multi-version confusion | A before/after comparison collapses to one version | No |\n\n### 2.3 How they condition on time\n\n- **Index:** all versions are kept, each with its validity interval. For first-stage retrieval,\n the dense/BM25 index holds 3 versions per article (first, median and last by `date_debut`), so\n the article can be found whichever wording the query resembles.\n- **Version layer:** after the top-5 **articles** are found, a deterministic step picks, for each\n article, the version whose `[date_debut, date_fin)` contains the question's date. **Time is a\n metadata filter applied after retrieval, not a feature learned by the retriever.**\n- **Where the date comes from:** every R3 question carries an explicit date anchor (\"for fiscal\n years opening on or after 1 January 2018\"). The paper does not describe how the date is\n extracted from the query in C_prod. The retriever code and encoder weights are proprietary and\n not released, so C_prod cannot be reproduced; only its per-question responses are published.\n- **Context:** every condition gets the same prompt with at most 8,000 characters per article,\n windowed around the query. They checked that the gold value is inside the window for all 209\n questions. Full-article prompting made long articles worse (long-context distraction).\n\n### 2.4 How to read the results (caveats)\n\n- **B fails partly by construction.** The divergence filter keeps only questions whose gold value\n is absent from the current text. B's 2.7 % therefore shows that the filter works more than it\n measures anything. The informative parts are B's **0 % provenance** (a single-version index\n cannot hold the right version) and the gap between B and C_or, where only the version served\n changes.\n- **C is near the ceiling because the task is well specified.** The date is explicit, and the\n article number appears in the question text in **83.7 %** of the questions. Once the right\n version is in the context, reading the value is easy (99 % for every model). The remaining\n 0.8-point gap between C_or and C_prod is article recall (one article, art. 1417), not version\n selection.\n- **Scope is narrow on purpose:** single-date questions, one article, one value. It does not show\n how temporal errors behave in open prose questions with several conditions, which is our\n setting.\n\n---\n\n## 3. How their deterministic nuggets work\n\n### 3.1 Definition and scoring\n\n- A **nugget** is an atomic claim that a program can check. It has one of three types:\n - **article identifier** → **regex**, e.g. `\\b219\\b`;\n - **numeric value** → **numeric match with tolerance**, after normalizing French number formats\n (thousands separators, decimal comma) and simple arithmetic forms (33⅓ % ≡ 33.333 %);\n - **exact string** match.\n- Each R3 question has **two required nuggets**: the article and the value at the question's date.\n (The appendix example lists 4 nuggets for the art. 219 case study, including the version and the\n regime. The scored R3 protocol states two.)\n- Scores per question:\n - **coverage** = fraction of nuggets matched (Σ 1[nᵢ ∈ r] / |N|);\n - **strict** = all required nuggets matched (right article **and** right value): the headline\n metric;\n - **value-only coverage**, because the article nugget is mostly given away by the question\n (83.7 %). Value-only tracks strict within 1 point;\n - **provenance** (retrieval side, not answer side): the gold version is among the retrieved\n versions (the single article for B/C_or, the top 5 for C_prod).\n- Aggregation: mean over the 209 questions per model, with cluster bootstrap over articles.\n\n### 3.2 Why no LLM judge\n\nTheir argument is specific to time. An LLM judge has the same recency prior as the systems under\ntest, so it may accept a fluent answer that states the **current** value, because that value\nagrees with what the judge \"knows\". A regex or a numeric comparison has no prior. All the\njudgement (which article, which value, what tolerance) is made **once, at annotation time**, and\nchecked against the primary source. Disagreements are settled by reading the versioned text again,\nnot by prompting a model again. They take the nugget idea from KARL (Databricks) and note that\nKARL's nugget scoring is still an LLM-as-judge variant. They also criticize Prior et al. (2026),\nconcurrent German work on the same problem, for using an LLM judge.\n\n### 3.3 Limits of the scheme (our reading; not all are discussed in [FQ])\n\n1. **Expressivity.** Only identifiers and numbers can be checked. Conditions, exceptions, verdicts\n (Sim/Não) and procedures cannot. This works for R3 because the questions were **written** so\n that a single number answers them.\n2. **Recall only; no penalty for extra claims.** An answer that lists the values of several years\n (\"33⅓ % in 2018, 31 % in 2019, 25 % since 2022\") matches the value nugget and gets strict = 1\n while still hedging. The paper does not mention this.\n3. **Short regexes over-match.** `\\b219\\b` also fires on \"R$ 219\" or \"item 219\". This is harmless\n when the question already names the article, but not in general.\n4. **Tolerance is a judgement call** made per question. A tolerance too wide would accept a\n neighbouring year's value when two versions differ slightly.\n5. **Leakage.** The question text gives the article in 83.7 % of the questions (they report\n value-only coverage for this reason).\n\n### 3.4 Why their scheme works for them and cannot be our main metric\n\nDeterministic scoring works in [FQ] because of how the **questions were written**, not because\nof a general property of legal QA. Each R3 question is built from one value change in one article.\nIt asks for one number on one date, and its complete correct answer is \"article X, value V\". So\nthe whole meaning of the answer fits into two checkable tokens. Because the article is usually\nnamed in the question, the score depends almost entirely on the **value**.\n\nOur situation is the reverse. The questions and gold answers are Receita Federal's own prose\n(median 84 words, up to 3,316), and most of what a correct answer must contain is rules,\nconditions, exceptions, verdicts (Sim/Não) and procedures. None of these can be checked with a\nregex or a number. Only a minority of answers contain values at all (77 with R$ amounts, 86 with\npercentages; §4.3), and even there the value is usually one part of a longer answer. So [FQ]'s\napproach cannot be our main metric. It can still serve as an extra check on the value-bearing\nnuggets (§5, item 1).\n\n---\n\n## 4. Comparison with our research\n\n### 4.1 Goals and setup side by side\n\n| Aspect | [FQ] | Ours (BR-TaxQA-R v2.0) |\n|---|---|---|\n| Research question | Is **version selection by date** the bottleneck of legal RAG? | Does **hierarchical segmentation** (S1 article vs. S2 article + sub-article units with ancestor path, optional S3 groupings) give better chunks for answering prose tax questions? |\n| Axis | Time (which version) | Structure (which unit) |\n| Questions | 209 author-written, single-date, single-value, filtered to be hard for all models | 715 existing questions from Receita Federal's P&R IRPF 2024. Open prose, many conditions, no filtering |\n| Gold answers | One value + one article per question | Official prose answers (median 84 words, up to 3,316) |\n| Corpus | 32k versions of 2 codes, with validity intervals | 459 documents of many kinds (laws, decrees, INs, ADEs, pareceres, soluções de consulta, court decisions) as LexML, **one version each**: the current consolidated text |\n| Retrieval unit | Article (chunked), then version | S1 article / S2 caput-§-inciso-alínea-item with ancestor path / S3 groupings |\n| Retriever | Proprietary dense + BM25 + RRF | Dense embedding models (Juá and others) under token-budget control and containment de-duplication |\n| Conditions | A closed-book, B current corpus + gold article, C_or version oracle, C_prod end-to-end | closed-book (`k=0`), **oracle** = gold articles of the current text, retrieval by strategy × budget (`docs/20260927_204356_rag_pipeline_implementation_plan.md` §5) |\n| Answer scoring | Deterministic nuggets (regex / numeric), 2 per question | LLM-created legal nuggets from the gold answers, human audit, LLM judge (Gemini / Qwen) with `support` / `partial` / `not_support` / `contradicts`, metrics V_strict etc. from AutoNuggetizer (`docs/20260926_112714_gold_answer_nuggetization_plan.md`) |\n| Citation scoring | Article regex nugget + retrieval provenance | Secondary legal-provision score, deterministic after URN normalization with `lexml-linker` (D6) |\n| Statistics | Cluster bootstrap by article, McNemar | Paired bootstrap / permutation over questions |\n\nConditions A and C_or map onto our plan, but **our oracle is their B, not their C_or**: it serves\nthe gold article in its **current** wording. A gap between our oracle and 100 % can therefore\ncome partly from time drift, not only from the reader LLM. It is worth reporting it that way.\n\n### 4.2 Time in our corpus: how the Brazilian case differs\n\n**Our time situation.** The gold answers describe the law for **ano-calendário 2023 / exercício\n2024**, as of 2024-05-03. The corpus holds the **current consolidated text**: the document fetcher\nrenders the *vigente* view (`../br-taxqa-document-fetcher/20260729_171931_receita_federal_rendering_fidelity_plan.md`,\nissue 3: \"keep `omitir === false` segments, emit `ancorasDestino[].texto` as annotations, no\nstrikethrough\"). The texts cite amending acts up to Lei nº 15.371, de 31.3.2026 (82 chunks). The\nsnapshot dates also **differ between documents**: e.g. the `.docx` files of Lei 9.250 and Lei\n11.482 are dated 2026-03-15 (file mtime), while other documents already include later changes. The\ncorpus is therefore about two years **after** the question date and is not one single point in\ntime.\n\nBrazilian consolidated texts store history differently from Légifrance, in three ways:\n\n1. **Values added as new items (history kept inside one article).** Laws that update annual\n values often **add a new item** rather than rewrite the old one, so the older values stay in the\n current text:\n - Lei 9.250, art. 8º, II, b: items 1–10 give the education-deduction limit per year, ending\n with \"10. R$ 3.561,50 …, a partir do ano-calendário de 2015\";\n - Lei 11.482, art. 1º: one inciso per period of the monthly progressive table, up to\n \"XII – a partir do mês de maio do ano-calendário de 2025 (Inciso acrescido pela Lei nº\n 15.191, de 11.8.2025)\" (exemption band up to R$ 2.428,80). The 2023 table (up to R$\n 2.112,00) is still there.\n\n Here [FQ]'s (P1)/(P3) happen **inside one chunk** instead of across versions. The right value is\n retrieved, but next to near-identical values for other years, and **the reader LLM must choose\n by year**. This ties time to **our** research question: an S2 inciso chunk isolates one\n period's table together with its year label. S1 gives the whole article with every year. S2\n should therefore produce fewer wrong-year values, if the retriever ranks the right inciso first.\n\n2. **Wording rewritten in place (history lost).** When the wording itself is replaced, the\n *vigente* view keeps only the new text plus a note \"(Redação dada pela Lei X, de …)\". The\n wording that applied in 2023 is gone. This is [FQ]'s **current-law substitution** in its pure\n form. Example: the inciso of Lei 11.482, art. 1º for the May-2023 table carries \"(Inciso\n acrescido pela Lei nº 14.663, de 28.8.2023, e com nova redação dada pela Lei nº 14.848, de\n 1º/5/2024)\". Revoked provisions keep only the note \"(Revogado pela …)\".\n\n3. **Acts tied to one year.** Many answers rely on acts that are themselves bound to one year,\n such as **IN RFB nº 2.178/2024**, the DAA 2024 instruction, which contains the R$ 30.639,90\n filing threshold of Q001. These act as correctly dated documents even in a current-only\n corpus. The risk comes back when a newer act on the same subject is also in the corpus. We have\n not measured this.\n\nThere is also a **future-law** risk relative to the question date: the corpus contains rules made\nafter 2024 (e.g. the 2025 table of Lei 11.482, and Lei 15.270/2025 inside Lei 9.249). An LLM given\nthese may answer an AC-2023 question with the 2025 value, which is [FQ]'s current-law substitution.\n\n### 4.3 Measurements on our data (2026-09-29, rough, for sizing only)\n\nComputed over `dataset/questions.jsonl`, `dataset/references.jsonl`, `lexml/articulados/` and\n`segmented/chunks_all.csv.gz`. The patterns are rough; treat the numbers as orders of magnitude.\n\n| Measure | Value |\n|---|---|\n| Answers with at least one R$ amount | **77** of 715 |\n| Answers with at least one percentage | **86** of 715 |\n| Questions or answers naming \"ano-calendário de YYYY\" / \"exercício de YYYY\" | 66 |\n| (question, distinct R$ amount) pairs | 279. Of these, **184** appear verbatim somewhere in the corpus. Most of the others are computed figures in worked examples (e.g. Q620, Q617), not values stated in the law |\n| Questions that cite an article in the question text | **3** (vs. 83.7 % in [FQ]), so our provision score is not given away by the question |\n| Referenced statutory documents with amendment notes dated after 2024-05 | **33** of 218 (most notes: LC 123/2006 198, Lei 11.196 67, Lei 9.394 46, Lei 10.833 37, Lei 10.865 37) |\n| Questions citing at least one of those documents | **116** of 596 questions with resolved references |\n| Examples of AC-2023 values in the corpus | 30.639,90 (4 chunks), 2.112,00 (5), 16.754,34 (18). Checked but not found: 564,80, 528,00, 2.824,00 |\n\nThe last two exposure rows are an **upper bound**: an amendment note on the document does not\nmean that the cited provision, or the answer, changed. Measuring the true set needs\nprovision-level matching (the `provisions` / `fragment_id` of `references.jsonl` against the notes\nof that fragment).\n\n---\n\n## 5. What to adopt, adapt or skip\n\n**Adopt**\n\n1. **Deterministic value checks alongside the LLM judge.** For every nugget in the `valor_prazo`\n category, pull its amounts, rates and dates out with pt-BR normalization (`30.639,90` ≡\n `30639.90`, `7,5 %`, dates). Then check the system answer with a regex / numeric match with\n tolerance, as [FQ] does. Report it as a separate **value-hit** score and use it to **audit the\n judge**: agreement between the judge's `support` and the value hit on these nuggets gives a\n free, bias-free check of the judge. This extends the grounding check already in the nugget\n validator (§3.3 of the nuggetization plan) from creation time to scoring time.\n2. **Year-aware `contradicts`.** When the answer states a **different** value of the same kind\n (another R$ amount in the same slot), mark it as a deterministic *contradiction candidate*. When\n that value appears in the corpus as a value of **another period** of the same provision (e.g.\n the 2025 table of Lei 11.482), mark it as **temporal substitution**. This gives our\n `contradicts` rate a temporal part and directly tests the S1 vs. S2 hypothesis in §4.2.1.\n3. **Temporal slice in every report.** Tag the questions that (a) have `valor_prazo` nuggets, or\n (b) cite a provision amended after 2024-05-03 (at provision level, §4.3). Report all metrics on\n this slice and on the rest.\n4. **Reference date in the generation prompt.** Add a fixed line to `prompts/answer_v1.pt.md`\n (exercício 2024, ano-calendário 2023). This is [FQ]'s date conditioning applied to the reader,\n at no cost. It helps with case 1 of §4.2 and does nothing for case 2. It must be the same for\n every strategy, so it does not bias the S1/S2/S3 comparison.\n5. **Cluster-aware statistics.** Questions that share cited documents or P&R chapters are not\n independent. Add a cluster bootstrap (by chapter or by main cited document) next to the paired\n bootstrap over questions.\n\n**Adapt**\n\n6. **Describe our oracle correctly** in the paper, as \"gold provisions, current wording\", and\n discuss the time gap between the question date and the corpus as a threat to validity. It is the\n same for every strategy, so it does not bias the **comparison**, but it lowers absolute scores.\n7. **Optional, later:** fetch the wording as of 2024-05-03 for the documents actually hit by\n in-place rewrites, if the source portals offer a multi-version or point-in-time view (to be\n checked in `../br-taxqa-document-fetcher`). This would allow a small version-oracle ablation\n like their C_or. It is out of scope for the segmentation paper unless the temporal slice turns\n out to be large.\n\n**Skip**\n\n8. **Numbers-only scoring as the main metric.** Most of our answers are rules, conditions and\n verdicts, so an LLM judge with human calibration remains the right main tool. [FQ]'s\n \"judge shares the recency bias\" argument is weaker for us, because our judge is **shown** the\n gold nugget, which states the dated value. The risk is still there when a nugget states a rule\n without its year, which is why item 1 is worth its low cost.\n9. **An all-model-hard parametric filter.** Our goal is to compare strategies on the official\n question set, not to build a benchmark that no model can answer closed-book. Our `k=0`\n condition already measures parametric knowledge.\n\n---\n\n## 6. References\n\n- [FQ] Cymbler, R., Guez, D., Fabre, L. *Temporal Misgrounding in Legal RAG: A Versioned-Corpus\n Benchmark for French Tax Law.* arXiv:2608.09393, 2026.\n- Opsahl-Ong, K. et al. *OfficeQA Pro.* arXiv:2603.08655, 2026. The deterministic grounded-scoring\n and parametric-filter methodology that [FQ] extends.\n- Databricks AI Research. *KARL: Knowledge Agents via Reinforcement Learning.* arXiv:2603.05218,\n 2026. The nugget decomposition that [FQ] uses, there with an LLM judge.\n- Prior, M., Schultz, A., Grabmair, M. *Asking for an Old Friend: Diagnosing and Mitigating Temporal\n Failure Modes in LLM-based Statutory QA.* arXiv:2605.23497, 2026. German statutes, LLM judge.\n- de Martim, H. *An Ontology-Driven Graph RAG for Legal Norms: A Structural, Temporal, and\n Deterministic Approach.* JURIX 2025. Point-in-time queries on the Brazilian Constitution; a\n co-author of our segmentation reference [F].\n- Our docs: `20260923_193852_segmentation_strategies_for_rag_experiments.md`,\n `20260926_112714_gold_answer_nuggetization_plan.md`,\n `20260927_204356_rag_pipeline_implementation_plan.md`.\n","20261005_184116_segmentation_s3_vs_lima_ementa_and_caput_strategy_plan.md":"# S3 vs. [L], Ementa Enrichment of S1/S2, and a Caput Strategy (S4) — Review and Plan\n\n**Generated:** 2026-10-05 18:41:16 (local time, from `date +%Y%m%d_%H%M%S`)\n**Revised:** 2026-10-05, after review with the user (§4 decisions D-A, D-B).\n**Builds on:** `docs/20260923_193852_segmentation_strategies_for_rag_experiments.md` (**the strategy\ndoc**), `docs/20260924_123747_segmentation_implementation_plan.md` (**the plan**; X1–X10, §2.3, §5b),\n`docs/20260924_175304_segmentation_execution_log.md` (**the log**; D1–D3, addenda),\n`docs/20260927_204356_rag_pipeline_implementation_plan.md` (**the RAG plan**) and\n`docs/20260927_222210_retrieval_legal_provision_test_jua.md` (**the first IR test**).\n**Sources:** [L] = Oliveira Lima, *Unlocking Legal Knowledge with Multi-Layered Embedding-Based\nRetrieval*, arXiv:2411.07739v1 (re-read from arXiv for this note); [F] = Fernandes, Lima, de Martim,\nOliveira, Lotufo, Pereira, *Structural Segmentation for Brazilian Legal Document Retrieval*\n(`../Artigo chunks legislação.pdf`).\n**Data checked:** `segmented/chunks_all.csv.gz` (87,702 rows, the frozen set used by the RAG runs).\n**Update 2026-10-08:** implemented in the corpus rebuild with the defaults Q1–Q3 (128-token ementa,\ncaput sentence kept in split-part HEADs, S5 later). C4, C5 and C9 were adapted to a changed corpus\n(`docs/20261007_180833_corpus_fixes_and_full_rebuild_plan.md` §4): fresh chunk ids (`#c<seq>` for\ncaput rows), `diff_vs_frozen` instead of the two invariants, and `embed.py corpus --extend` (embed by\ntext hash). Counts and IR results: `docs/20261008_010441_corpus_rebuild_results.md`.\n\n---\n\n## 0. Short answers and decisions\n\n1. **Does S3 match [L]?** It has the same four layers that [L] actually embeds (grouping, article,\n caput/§, enumeration) and uses [L]'s enumeration-context rule. It is **not identical**: it leaves\n out [L]'s document and document-component layers, adds [F]'s metadata prefix to every chunk,\n has no CPT chunk for caput-only articles, splits articles above 1,024 tokens, and drops groupings\n above 8,192 tokens. Today it also adds the caput sentence to paragraph chunks; decision D-A below\n removes that. The full list is in §1.\n2. **Ementa enrichment of S1 and S2 — already implemented.** Every chunk of every strategy already\n starts with `[ Epígrafe | Ementa ]`, which is exactly [F]'s \"document metadata\"\n (`[Bill No. x/xxxx | Summary of the bill.]`), in 100 % of the rows of every `Tipo` (checked). So\n **S1 already is [F]'s \"Core Chunks + Metadata\"**. The one remaining gap from [F] is that the ementa\n is **truncated to 128 tokens** in the prefix (9,318 rows). See §2.\n3. **Caput and paragraphs are siblings — correct** (§3). In the frozen chunk set, however, paragraph\n chunks (PAR, and the INC/ALI/ITE under a §) also carry the **article label and the caput's opening\n sentence** (plan X3b / strategy doc §6 item 2), in S2 and S3 alike, because S2 and S3 are filters\n over one chunk set.\n4. **Decisions (user, 2026-10-05):**\n - **D-A — S2 and S3 lose the caput sentence in paragraph chunks.** Paragraph-family chunks keep\n the article label + the paragraph subtree, and enumerations keep their ancestor path up to the\n §. This is [L]'s and [F]'s treatment (§1). S3 is still \"S2 + groupings\", so S2 vs S3 still tests\n one factor.\n - **D-B — S4 = S3 + the caput opening sentence in paragraph-family chunks**, i.e. exactly the\n texts the current chunk set holds. **S2c** (S2 + caput sentence) is the matching free filter.\n Adding the **full** caput (sentence + incisos/alíneas/itens) becomes the optional **S5**.\n5. **Consequence:** the current S2/S3 retrievals and the first IR test were run on texts that are,\n by these definitions, **S2c and S4**. Those results stay valid under the new names. S2 and S3 must\n be re-embedded (only the 29,876 changed paragraph-family texts) and re-run (§4.6).\n6. **Non-statutory documents:** no change (§5).\n\n---\n\n## 1. S3 compared with [L]\n\n[L] §4.1 defines six layers. Its worked example (Title I of the Constitution) yields 32 chunks: 1\ndocument + 1 document component + 4 articles + 25 article components (4 capita, 2 sole paragraphs,\n19 incisos) + 1 title. The only context [L] adds is the ancestor text of enumerations, up to the\ncaput or paragraph (footnote 7: \"[A República Federativa … tem como fundamentos:] dignidade da pessoa\nhumana\").\n\n| Aspect | [L] | S3 (after D-A) | Match? |\n|---|---|---|---|\n| Document layer | 1 chunk per document | not produced (strategy doc §5, \"Not included\") | **No.** Deliberate: whole documents exceed the embedding limits. [L]'s retrieved chunks never include one either |\n| Document-component layer (main text, justification, annexes, tables) | 1 chunk per component | not produced as one chunk. Annex content is segmented into ART/DSP/TXT/TAB units | **No.** Deliberate. Annex text is reachable, but not as one whole-component vector |\n| Basic unit hierarchy (parte … subseção) | 1 chunk per grouping | PRT…SSC = own label + name + all content below, **only if ≤ 8,192 tokens**. 243 groupings are left out (`segmented/groupings_over_limit.csv`), e.g. 5 of the Constitution's 9 títulos | **Partial.** Same unit; the largest groupings are missing |\n| Basic unit (article) | whole article | whole article; **articles above 1,024 tokens are split** into structural parts (647 articles → 1,752 parts) | **Partial** |\n| Basic unit component (caput, §) | caput **and** every paragraph, for every article (4 capita for 4 articles in the example) | CPT only when the article has ≥ 1 paragraph (plan X5/Q5; for caput-only articles the CPT text would equal the ART text); PAR for every paragraph | **Equivalent in content.** Only a duplicate vector is missing |\n| Enumeration (inciso, alínea, item) | own text + ancestor text up to the caput/§ | same rule (strategy doc §5.2), and it also includes the **article label** and any `TituloDispositivo` | **Yes** (plus the label) |\n| Paragraph context | paragraph text only (also [F] Fig. 3, chunk 6) | article label + paragraph subtree (**caput sentence removed by D-A**; it moves to S4) | **Yes** (plus the label) |\n| Document metadata | none | `[ Epígrafe \\| Ementa ]` on every chunk (ementa ≤ 128 tokens) | **No.** Taken from [F] |\n| Grouping titles (`NomeAgrupador`) in the context | none (in [L]) | dropped (X2), following [F]'s finding that they bring no clear gain | Yes, for [L] |\n| Remission text, tables, `TituloDispositivo`, orphan dispositivos (DSP), annexes, non-statutory TXT/TAB | not addressed | handled (X3, X4, X6, X8; plan §4–§5) | Extension |\n| Retrieval filter (§4.2): 2,500-token budget, drop hits more than 25 % below the top score, containment de-duplication, at least 7 chunks | — | not segmentation. The RAG pipeline uses a **token budget** and **containment de-duplication**, but not the 25 % cut or the minimum of 7 | Partial (retrieval side) |\n\nConstitution, for scale: [L] reports 2,954 chunks. S3 has **3,017** (ART 318 incl. split parts, CPT 195,\nPAR 803, INC 1,295, ALI 318, TIT 4, CAP 29, SEC 50, SSC 5). The two counts are not directly\ncomparable, because of the CPT rule, article splitting, the grouping limit and possibly a different\nADCT coverage.\n\n**Verdict:** after D-A, S3 is [L]'s multi-layer scheme restricted to its four embedded layers, with\n[F]'s metadata and structural splitting of oversize articles. In the paper, describe it as \"[L]'s\narticle-level-and-below layers plus groupings, with [F]'s metadata\". The remaining differences from a\nstrictly [L]-faithful scheme are the metadata prefix, the missing CPT for caput-only articles, and\narticle splitting. I do not recommend removing them: [F] shows that metadata helps dense retrieval,\nthe missing CPT chunks only duplicate article vectors, and splitting is needed for the 1,024 cap.\n\n**Not changed by D-A:** the HEAD of **split article parts** (plan §5b). A part that starts with a\nparagraph still repeats the article label + caput sentence, because it is a piece of the article\n(an ART unit in S1), not a paragraph chunk. S1 is therefore unchanged. If the user wants D-A applied\nthere too, it would change the 769 ART/DSP parts (of 1,749) whose first unit is a paragraph, and so the S1 baseline. I do not recommend it: without\nthe caput sentence, a part would not say what the article is about.\n\n---\n\n## 2. Ementa enrichment of S1 and S2 ([F] \"metadata\")\n\n### 2.1 Current state (verified 2026-10-05)\n\n```\nTexto = \"[ \" + Epígrafe + \" | \" + Ementa(≤128 tokens) [+ \" | \" + annex label] + \" ] \" + CAMINHO + CONTEUDO\n```\n\nExample: the S1 ART chunk and the S2 INC chunk of Lei 9.250, art. 8 both start with\n`[ LEI Nº 9.250, DE 26 DE DEZEMBRO DE 1995 | Altera a Legislação do Imposto de Renda das Pessoas\nFísicas e dá outras providências. ] Art. 8º …`.\n\n| Item | [F] | Ours |\n|---|---|---|\n| Fields | title + summary | Epígrafe + Ementa (cleaned of Planalto/Câmara page furniture, log step 2) |\n| Separator / brackets | `[Bill No. x/xxxx \\| Summary of the bill.]` | `[ <epígrafe> \\| <ementa> ]` |\n| Length | full summary (no limit stated) | ementa **truncated to 128 tokens** + ` …` |\n| Annexes | — | parent epígrafe + parent ementa + `Anexo N – <title>` |\n| Documents without an ementa | — | epígrafe only (e.g. `constituição_1988`) |\n| Levels enriched | all chunks in Hierarchical; core chunks in the Core strategies | **all chunks of all strategies**, S1–S5 and TXT/TAB |\n\nThe requested change is in place for S1 (ART/DSP) and S2 (CPT/PAR/INC/ALI/ITE), and D-A does not\ntouch the prefix.\n\n### 2.2 What is left (decisions and documentation only)\n\n| # | Item | Recommendation |\n|---|---|---|\n| E1 | **Ementa truncation.** 9,318 of 87,702 rows (S1: 3,219 of 26,250; S2: 8,923 of 82,642) carry a truncated ementa, from 33 main documents, 26 category-C annexes and 72 non-statutory documents. [F] uses the full summary. Removing the limit makes long ementas (up to 2,951 chars in main documents; soluções de consulta are longer) dominate short chunks (INC p50 = 193 tokens), and the rows would have to be re-embedded | **Keep 128** and state it in the paper as a deviation from [F]. If the user prefers [F]-exact, set `--ementa-max-tokens 0` (meaning: no limit; this needs a one-line change in `common.truncate_tokens`), and do it **in the same re-run as D-A** (§4.5), so that only one new chunk set is frozen and embedded. The ART/DSP cap of 1,024 still applies, so a longer prefix can create a few more article parts |\n| E2 | \"Core Chunks + No Context\" ablation ([F] Table 1) | **Do not run.** [F] already shows that it is worse. If a reviewer asks for it, strip the prefix with `^\\[ .*? \\] ` (no `]` can occur inside the prefix, because `metadata_for` replaces `[`/`]` with `(`/`)`) and embed the S1 texts once (≈ 26 k texts) |\n| E3 | Documentation | Record in the strategy doc that S1 = [F] Core + Metadata and S2 = [F] Hierarchical without hierarchy titles and groupings (§6) |\n\n---\n\n## 3. Caput and paragraphs: is the premise right?\n\nIn LexML, and in LC 95/1998, an article is `Artigo → Caput, Paragrafo*`. **The caput and its\nparagraphs are siblings**, and incisos/alíneas/itens hang under either of them. Checked: the corpus\n`id`s are hierarchical (`art8_cpt_inc2…`, `art8_par2_inc1`). Outside `Alteracao`, **no**\n`Paragrafo` lies under a `Caput` in `lexml/articulados`. The 1,596 that do are quoted amending text\n(\"Art. X passa a vigorar com …\"), which gets no rows of its own.\n\nParagraph-family texts per strategy, for Lei 9.250, art. 8 (text after the prefix):\n\n| Chunk | Frozen set today (= S2c/S4 after D-B) | S2/S3 after D-A | S5 (optional) |\n|---|---|---|---|\n| CPT `art8_cpt` | `Art. 8º A base de cálculo … somas: I – … II – das deduções relativas: a) … b) …` | unchanged | unchanged |\n| PAR `art8_par2` | `Art. 8º A base de cálculo … somas: § 2º O disposto na alínea a do inciso II: I – … II – …` | `Art. 8º § 2º O disposto na alínea a do inciso II: I – … II – …` | `Art. 8º A base de cálculo … somas: I – … II – das deduções relativas: a) … § 2º O disposto …` |\n| INC `art8_par2_inc1` | `Art. 8º A base de cálculo … somas: § 2º O disposto na alínea a do inciso II: I – aplica-se, também, …` | `Art. 8º § 2º O disposto na alínea a do inciso II: I – aplica-se, também, …` | full caput before `§ 2º` |\n| INC `art8_cpt_inc2` (caput side) | `Art. 8º A base de cálculo … somas: II – das deduções relativas: a) …` | unchanged (the caput is its ancestor, not a sibling) | unchanged |\n\nSo, after D-A:\n\n- \"caput and its components\" = CPT, **only for the 8,084 articles that have a paragraph** (for\n caput-only articles the ART chunk is the same text);\n- \"paragraph and its components\" = PAR, with only the article label as context;\n- the caput sentence in paragraph chunks belongs to S4, and the full caput to S5.\n\n---\n\n## 4. Plan: caput-free paragraphs in S2/S3, caput sentence in S4 (full caput in S5)\n\n### 4.1 Strategy definitions\n\n| ID | Indexed `Tipo`s | Paragraph-family text | Status |\n|---|---|---|---|\n| **S1** | ART, DSP, TXT, TAB | — (no paragraph chunks; ART parts keep their HEAD, §1) | Baseline, **unchanged** |\n| **S2** | S1 + CPT, PAR, INC, ALI, ITE | **article label + paragraph subtree** (D-A) | Main hypothesis, **re-built** |\n| S3 | S2 + PRT…SSC (≤ 8,192 tokens) | same as S2 | Optional, **re-built** |\n| **S4** | same `Tipo`s as S3 | article label + **caput sentence** + paragraph subtree (= the frozen texts) | Optional (D-B) |\n| S2c | same `Tipo`s as S2 | same as S4 | Free filter: S2 vs S2c is the cheaper caput comparison |\n| S5 | same `Tipo`s as S3 | article label + **full caput** + paragraph subtree | Optional, later |\n\n\"Paragraph family\" = every PAR row plus every INC/ALI/ITE row with a `Paragrafo` ancestor: **29,876\nrows** (PAR 21,511, INC 6,645, ALI 1,644, ITE 76). All other rows (ART/DSP and their parts, CPT,\ncaput-side INC/ALI/ITE, groupings, TXT, TAB) are identical in every strategy.\n\nComparisons:\n- S1 vs S2: sub-article units (main question, now without the caput confound);\n- S2 vs S3: groupings;\n- **S3 vs S4** (or S2 vs S2c): does a paragraph chunk need the caput sentence? (the question you\n asked for);\n- S4 vs S5: does it need the caput's components as well? (optional).\n\n### 4.2 Data model: text variants, not new `Tipo`s\n\nToday a strategy is a set of `Tipo`s over one chunk table, and each chunk has one text (`strategies.py`,\n`scripts/rag/strategies.yaml`). S4/S2c/S5 change the **text** of existing units, so they cannot be\n`Tipo` filters.\n\n- `chunks_all.csv` gets a column **`variante`**:\n - `base` — every row of S1–S3; paragraph-family rows **without** the caput sentence (D-A);\n - `caput` — 29,876 paragraph-family rows **with** the caput sentence (S4/S2c);\n - `caput_completo` — S5 rows (only if S5 is built).\n\n A variant row copies every column of its `base` twin (Tipo, Rotulo, urn, intervals, provenance)\n except `Texto`, `texto_sha256`, the token columns and `chunk_id`.\n- **Chunk ids (recommended):** the `caput` rows **keep the `chunk_id`s of the frozen set**, since\n their texts are the frozen texts, and the new caput-free `base` rows get new ids\n (`<stem>#b<seq>`). The existing `chunk_map.csv.gz`, rankings and per-item tables then stay\n consistent as the S2c/S4 results without any remapping (§4.6).\n- New columns: `contexto_ids` (id of the caput whose text was added; empty for `base`) and\n `caput_completo` (S5 only: 1, or 0 when the cap rule fell back to the sentence, §4.4).\n- Strategy config:\n\n ```yaml\n S2: {tipos: [<S2 tipos>], variantes: [base]}\n S3: {tipos: [<S3 tipos>], variantes: [base]}\n S2c: {tipos: [<S2 tipos>], variantes: [caput, base]} # per unit, first variant that exists\n S4: {tipos: [<S3 tipos>], variantes: [caput, base]}\n S5: {tipos: [<S3 tipos>], variantes: [caput_completo, base]} # optional\n ```\n\n `variantes` defaults to `[base]`. Row counts: S2/S2c = 82,642; S3/S4/S5 = 87,702 (variants replace\n rows rather than adding them).\n- **Invariants (validated):** (i) every non-paragraph-family `base` row is byte-identical to the\n frozen set (same `chunk_id`, `texto_sha256`), so S1 and its embeddings, rankings and evaluations\n are untouched; (ii) the `caput` rows are byte-identical to the frozen paragraph-family rows.\n\nRejected: new `Tipo` codes (`PRC`, `INCC`, …). They would leak into `nivel`, `unit_precedence`, the\nrelevance levels and every report, all of which are about structure, not text.\n\n### 4.3 Implementation steps\n\n| # | Where | Change |\n|---|---|---|\n| C1 | `scripts/segmentation/segmenta_estatutario.xsl` | Make **X3b switchable**: new param `caput_em_paragrafo` (`nao` \\| `frase`, default **`nao`**). With `nao`, `lx:caminho` no longer inserts `../Caput/p` after the article label for nodes with a `Paragrafo` ancestor. The XSL's default output becomes the D-A `base` texts |\n| C2 | `scripts/segmentation/common.py` | Python mirror: `caminho(n, caput=\"nenhum\"\\|\"frase\"\\|\"completo\")`, where `completo` inserts `texto(Caput)`. **`split_oversize.py` must call it with `caput=\"frase\"` explicitly**, so the ART-part HEAD is unchanged (§1). The XSL/Python parity test runs with both XSL settings |\n| C3 | new `scripts/segmentation/add_caput_variants.py` | For each statutory CSV + XML: select the paragraph-family rows (through the XML: element with a `Paragrafo` ancestor inside an `Artigo`, or a PAR); write `<file>.caput.csv` (`frase` texts) and, with `--completo`, `<file>.caput_completo.csv` with the cap rule of §4.4; write provenance records (`variante`, `contexto_ids`, `caput_completo`). Covers main documents and category-A annexes. Paragraphs with no `Caput` sibling (orphan structures, e.g. under DSP; 98 rows) get no variant, so S4 falls back to their `base` row. Python is used rather than a second XSL pass because S5 needs token counts, which XSLT cannot do (plan §5b) |\n| C4 | `scripts/segmentation/segment_all.py` | XSL with `caput_em_paragrafo=nao`; new step 3c `add_caput_variants` (`--variants caput[,caput_completo]`, default `caput`). The merge (step 6) appends the variant rows and assigns `chunk_id`s as in §4.2 (it reads the frozen `chunks_all` to reuse the ids; `--chunk-id-source <csv.gz>`). `run_info.json` records the flags |\n| C5 | `scripts/segmentation/validate_segments.py` | New checks: `base_unchanged` (invariant i); `caput_variant_frozen` (invariant ii: `caput` texts and ids equal the frozen paragraph-family rows); `variant_twins` (one `base` twin per variant row, with the same `urn`, `Tipo` and intervals); `base_no_caput` (a `base` paragraph-family text does not contain the caput sentence right after the article label); S5 only: `variant_cap`. The text-coverage check is unaffected (it uses S1) |\n| C6 | `scripts/segmentation/strategies.py` | `STRATEGIES` holds `(tipos, variantes)`; `filter(df, \"S4\")` keeps, per `(arquivo, urn, Tipo)`, the row of the first listed variant. Callers that only pass a `Tipo` set keep working (they get `base`) |\n| C7 | `scripts/rag/strategies.yaml`, `ragpipe/strategies.py`, `ragpipe/data.py` | Parse `variantes`, apply the same per-unit selection, add S2c/S4 (S5 later), and update `expected_rows` and the chunk-file SHA-256. Text ↔ chunk aliasing is unchanged |\n| C8 | `ragpipe/relevance.py`, `context.py` | **Nothing for S4/S2c**: the caput sentence is partial caput text, and the frozen texts were already scored without caput credit. S5 only: report gold hits with and without `contexto_ids` as covered (`gold_cover` modes), and let a `caput_completo` row cover its own interval **and** the caput's interval in containment de-duplication |\n| C9 | `scripts/embedding` | `corpus` refuses a different input file unless `--overwrite`. Add **`--extend`**: load the existing store, embed only the `text_id`s that are missing (the 29,876 caput-free texts, ≲ 7.7 M reference tokens, minus the removed sentences), and write a merged store (`vectors.npy` + `texts.csv` + `chunk_map.csv.gz`) whose manifest lists both input SHA-256s. The parity gate and the template/instruction checks still apply. Run it for `jua-4b-mixed` first, then for every other model |\n| C10 | tests (`scripts/segmentation/tests`, `scripts/rag/tests`) | Update the §3.2 worked target of the plan: `PAR art8_par2` (`base`) = `Art. 8º § 2º O disposto …`, with no caput sentence; its `caput` variant equals today's text. The `ITE art8_cpt_inc2_ali2_ite10` target is unchanged (caput side). XSL regression with both param values. Split-part HEAD unchanged (largest RIR/2018 article). Filters: S4 = S3 with substitutions; S2c = S2 with substitutions; S1 unchanged |\n\n### 4.4 S5 (optional): full caput\n\nSame machinery, variant `caput_completo`. Estimates from `chunks_all`: PAR + full caput ≈ p50 354,\np90 711, p99 1,672, max ≈ 8,383 tokens; 824 PAR rows (3.8 %) over 1,024 and 14 over 8,192. Proposed\nrule: full caput when the chunk is ≤ 1,024 tokens, otherwise fall back to the caput sentence\n(`caput_completo = 0`). Texts whose caput has no components are identical to the S4 text and share\nits `text_id`. A third variant, \"only the caput components the paragraph cites\" (e.g. \"alínea a do\ninciso II\"), needs intra-article reference resolution and is future work. `lexml-linker` targets\nreferences to legislation; whether it resolves bare \"inciso II\" mentions has not been checked.\n\n### 4.5 Work order\n\n1. Decide Q1–Q3 (§7). If E1 changes, implement it now so that only one new chunk set is frozen.\n2. C1 + C2 + C10 (segmentation tests) → check on `lei_9250`, `decreto_9580…anexo1`, `decreto_3000`.\n3. C3 + C4 + C5 → full run; `base_unchanged` and `caput_variant_frozen` must pass; freeze\n (`run_info.json`, `chunks_all.csv.gz`, which now has ≈ 117.6 k rows).\n4. C9 → embed the caput-free texts with `jua-4b-mixed` (`--extend`).\n5. C6 + C7 (+ rag tests) → `rag.py retrieve` + `evaluate` for S1, S2, S3, S2c, S4.\n6. Dated results note in `docs/`, and the doc updates of §6.\n7. S5 (C3 `--completo`, C8, embedding) only if S3 vs S4 shows an effect worth refining.\n\n### 4.6 Existing results\n\n- `runs/retrieval/jua-4b-mixed/irpf/` (S1/S2/S3) and `runs/…/eval/either_containment_skip/` were\n produced from the frozen set. Under the new definitions: **S1 stays S1, S2 → S2c, S3 → S4.**\n- After step 5 the S2/S3 names refer to the caput-free texts. To avoid silently mixing the two\n meanings, the re-run should use a new `eval_id`. The old manifests keep the old chunk-file\n SHA-256, which tells them apart, and the first IR test should get a header note: \"S2/S3 in this\n note = S2c/S4 in the 2026-10-05 definitions\".\n- The headline numbers of the first IR test (e.g. sub-article gold Recall 0.328 / 0.376 / 0.369 for\n S1 / S2 / S3) therefore already answer part of the S1-vs-S2c question. S1 vs the new S2 must be\n measured again.\n\n---\n\n## 5. Non-statutory documents\n\n| Change | Apply to `nao_articulados` / category C / loose content? | Why |\n|---|---|---|\n| Ementa metadata (§2) | **Already applied**: `[ Epígrafe \\| Ementa ]` with fallbacks (`campo EMENTA`/`ASSUNTO`, `preliminar` first line). 5 files have no ementa | Same rule as statutory, so the prefix is not a confounder |\n| Ementa truncation (E1) | If E1 changes, change it **for all documents at once** (72 non-statutory files and 26 category-C annexes are affected) | A strategy-independent setting must stay identical across all strategies |\n| D-A / S4 / S5 (caput in paragraphs) | **No** | There is no caput/paragraph structure: `Agrupamento`/`p` are PDF lines, and headings are already repeated at the start of each unit. The nearest analogue, a soluções-de-consulta ementa acting as the \"head\" of every part, is already in the prefix. Changing NS rows would mix a second factor into S3 vs S4 (strategy doc §6 item 4). They stay `base` only and are identical in every strategy |\n| Annexes with articles (category A) | **Yes, automatically**: C1/C3 handle them like main documents | They are statutory |\n| Orphan dispositivos (category B, DSP) | No variant | A top-level orphan `Paragrafo` has no caput sibling |\n\n---\n\n## 6. Documentation updates to bring the strategy record up to date\n\n| File | Update |\n|---|---|\n| `docs/20260923_193852_…strategies…md` | Decision table: S1 / S2 / S3 now with **caput-free paragraph chunks**; add **S4 (optional) = S3 + caput sentence in paragraph-family chunks**, S2c, and S5 (optional, full caput), with a pointer to this note. §5: S1 = [F] \"Core Chunks + Metadata\", S2 = [F] \"Hierarchical\" without hierarchy titles. **§6 item 2: reversed on 2026-10-05**: the caput sentence moves out of the base chunks into the S4 variant (D-A/D-B); the Art. 8 § 2 example moves to the S4 rationale. §5.2: unchanged (it is a caput-side example). §5 counts: refer to the grouping-limit addendum (S3 = 87,702) |\n| `docs/20260924_123747_…implementation_plan.md` | Short note at X3b and §3.2: \"superseded by the 2026-10-05 note; X3b is now the `caput_em_paragrafo=frase` option\" |\n| `docs/20260927_222210_retrieval_legal_provision_test_jua.md` | Header note: its S2/S3 are S2c/S4 in the new definitions (§4.6) |\n| `CLAUDE.md` | Strategy list: \"S1 article baseline, S2 article + ancestor-path sub-units (paragraphs without the caput), optional S3 + groupings, optional S4 = S3 + caput sentence in paragraph chunks (S5: full caput)\", plus a pointer to this note |\n| `scripts/segmentation/README.md`, `strategies.py` docstring | `caput_em_paragrafo`, `add_caput_variants.py`, `variante`/`contexto_ids` columns |\n| `scripts/rag/README.md`, `strategies.yaml` header | `variantes`, new strategies, expected counts and SHA-256 |\n| `scripts/embedding/README.md` | `--extend` |\n| Paper text | §1 verdict on S3 vs [L]; E1 (ementa truncated to 128 tokens) as a deviation from [F] |\n\n---\n\n## 7. Open questions\n\n- **Q1 — Ementa truncation (E1).** Keep 128 tokens (recommended), or use the full ementa as in [F]?\n If it changes, do it in the same re-run as D-A.\n- **Q2 — Split article parts.** Keep the caput sentence in the HEAD of ART parts that start with a\n paragraph (recommended; S1 unchanged), or apply D-A there too?\n- **Q3 — S5.** Build it now, or only after S3 vs S4 (recommended)?\n","20261007_180833_corpus_fixes_and_full_rebuild_plan.md":"# Corpus Fixes and Full Rebuild Plan (LexML → segmentation → dataset → embeddings → RAG)\n\n**Generated:** 2026-10-07 18:08:33 (local time, from `date +%Y%m%d_%H%M%S`)\n**Status:** plan. **Updated 2026-10-07** after five rounds of user review (§8): B1, B2 and B3 done;\nfix 3 (Q187) added; PDF route tested; the user's `.docx` repairs for item 2 checked by re-parsing\n(§3.1.1); the §1.2 removals (D3) done and Resolução TSE nº 22.250/2006 fetched (commit `7c44d73`).\nEverything else is still to do.\n**Executed 2026-10-08 (R1–R10):** results, deviations and open points in\n`docs/20261008_010441_corpus_rebuild_results.md`.\n**Builds on:** `docs/20260927_180401_dataset_v2_format_and_reference_fixes.md` (**the dataset note**;\n§5.2, §7) and `docs/20261005_184116_segmentation_s3_vs_lima_ementa_and_caput_strategy_plan.md`\n(**the caput plan**; D-A, D-B, C1–C10).\n**Trigger:** the user's corrections to `original/` in commits `1db1c58` (Resolução TSE 22.205\nrenamed) and `ce032e6` (22 wrong documents replaced, Diat added, 11 documents moved to\n`original/nao_articulados`), then `a575acc` and `7c44d73` (the follow-ups listed in §8).\n\n---\n\n## 0. Summary\n\nThe plan rebuilds every derived layer from `original/`:\n\n```\noriginal/ ──(parse)──► lexml/ ──(segment, with D-A/D-B variants)──► segmented/\n │ │ │\n └──────(build_v2_dataset)──► dataset/ ◄───────────────────────────┘\n │\n embeddings/ ──► runs/retrieval + runs/eval (new eval_id)\n```\n\nIt also covers:\n\n- the two requested reference fixes, Q313 and Q249 (§2);\n- explanations and fixes for items 2, 5 and 6 of the dataset note's §7 (§3);\n- **problems found while checking the new `original/`**, some of which block the rebuild (§1.2).\n\n**Blockers to settle before step R1 (§5):**\n\n| # | Problem | Proposed action |\n|---|---|---|\n| B1 | `ad_pgfn_3_20080918.docx` was deleted, but **Q179 cites it** (179-03, 179-06: \"AD PGFN nº 3 de 18 de setembro de 2008\"). Only Q280 cited AD PGFN 3/**2016** | **Done (2026-10-07):** restored with `git checkout 1db1c58 -- original/nao_articulados/ad_pgfn_3_20080918.docx`. The new `ad_pgfn_3_20160330` stays too |\n| B2 | `SCI Cosit nº 24-2008.pdf` is **SCI Cosit nº 24, de 27/06/2008** (social-security exemption, CNAS). Q187 cites **SCI Cosit nº 27, de 07/07/2008** (private pension plans) | **Done (2026-10-07):** the PDF is removed (nothing cites SCI 24/2008). SCI 27/2008 cannot be found, so reference 187-02 is **dropped** (fix 3, §2.3) |\n| B3 | 12 `.pdf` (13 before B2) and 3 `.odt` files. The non-statutory parser reads only `.docx/.html/.htm/.txt`, and `build_v2_dataset.py` globs only `*.docx`. The PDF names didn't follow `<type>_<number>_<YYYYMMDD>` | **Done (user, 2026-10-07):** PDFs renamed to the §1.3 stems; ODTs converted to `.docx`. Still to do: PDF → cleaned text (R1) and the `*.pdf` glob in the build |\n| B4 | Stale LexML: `lexml/` still holds the XMLs of the removed documents and of the 11 moved ones. `segment_all.py` globs `lexml/articulados/*.xml` and `lexml/nao_articulados/*.xml`, so these would be **segmented and indexed** | Delete them in step R2 (§5) |\n\n---\n\n## 1. State of `original/` after the user's changes (checked 2026-10-07)\n\n### 1.1 What changed\n\n| Change | Files |\n|---|---|\n| Replaced in `articulados/` | `ade_rfb_3_20240402` → `adi_rfb_3_20160427`; `lei_8794_19931221` → `decreto_lei_8794_19460123` (added as `decreto-lei_…`, renamed to the `decreto_lei` prefix the build expects, and the old file removed in `7c44d73`; see 1.2) |\n| Replaced in `nao_articulados/` (`.docx`) | `ad_pgfn_2_20180403` → `ad_pgfn_2_20160310`; `ad_pgfn_3_20080918` → `ad_pgfn_3_20160330` (**B1**); `pn_cst_38_19801031` → `pn_cst_38_19750324`; `pn_cst_72_nodate` → `pn_cst_72_19791218`; `resol_tse_22_20060523` → `resol_tse_22205_20060523` (rename only), then → `resol_tse_22250_20060629` (the cited act, fetched by the user; `7c44d73`) |\n| Replaced in `nao_articulados/` (`.odt`, now `.docx`) | `sc_cosit_69_20200624` → `sc_cosit_69_20131230`; `sc_cosit_140_20230714` → `sc_cosit_140_20210921`; `sc_cosit_194_20230829` → `sc_cosit_194_20150805`. Converted by the user; the word counts equal the ODTs' (142/163/179). **Note:** these three hold only the published ementa (DOU), not the full SC text |\n| Replaced in `nao_articulados/` (`.pdf`, renamed to the §1.3 stems) | SC Cosit 7/2017, 50/2020, 64/2014, 75/2020, 123/2021, 166/2019, 173/2015, 179/2023, 183/2014 (replaces `sc_cosit_134_20140602`), 211/2019, 214/2021, 354/2014; SCI Cosit 24/2008 (replaces `sd_cosit_27_20080530`; **B2**) |\n| Added | `documento_de_informacao_e_apuracao_do_ITR_DIAT.docx` |\n| Moved `articulados/` → `nao_articulados/` | `decreto_27784`, `_59308`, `_59309`, `_62125`, `_63151`, `_85801`, `_86006`, `_86084`, `_93153`, `in_srf_23_19830325`, `in_srf_67_19880421` |\n\nI checked the first page of every new PDF/ODT and the opening of every new `.docx`: number and date\nmatch the cited act in all cases except B2.\n\nOf the removed documents, only `ad_pgfn_3_20080918` is cited by a question (B1). The others were\ncited only through the wrong matches that the new files replace.\n\n### 1.2 Remaining corpus issues\n\nAll four were settled by the user in commit `7c44d73` (2026-10-07):\n\n| Item | State | Action |\n|---|---|---|\n| Resolução TSE nº 22.250/2006 (Q438, art. 14) | `resol_tse_22205_20060523` was a different act | **Done:** `resol_tse_22250_20060629.docx` fetched into `nao_articulados/`; `resol_tse_22205_20060523.docx` removed. **Q438 resolution fixed:** `\"resolucao_tse\": \"resol_tse\"` added to `PREFIX` (`build_v2_dataset.py`) and the `not_in_corpus` override deleted (62 `files` entries left). 438-03 now resolves `auto_undated` to `resol_tse_22250_20060629`, and `auto_exact` once R4 sets the canonical record's date (index 344) to 2006-06-29. The file has art. 14. **Moved to `articulados/`** (2026-10-07) after rejoining its hard-wrapped lines, so the statutory parse gives `art1…art50` and `art14` gets its own `Artigo` id (below the table) |\n| `lei_8794_19931221` | cited by no question (the wrong match for DL 8.794/1946) | **Done:** removed. `decreto-lei_8794_19460123.docx` renamed to `decreto_lei_8794_19460123.docx` |\n| `ade_cosit_30_20010723` | cited by no question (the wrong match for \"Parecer Cosit nº 30\") | **Done:** removed (fix 1, §2.1) |\n| `parecer_pgfncat_815_2010_nota_pgfn_crj_981_2015.docx` | a duplicate of `nota_pgfn_981_20151104` (dataset note §7.4) | **Done:** removed (fix 2, §2.2) |\n\n**Statutory parse of Res. TSE 22.250 (tested 2026-10-07, scratchpad only).** Jar rebuilt from the\nparser's HEAD (`ebf6567`, `mvn -Ponejar package`; the old `phase2.jar` path no longer exists). It\nreproduces `lexml/articulados/lei_9250_19951226.xml` byte for byte.\n\n- **As fetched, it fails.** The `.docx` has a hard break after every printed line (610 paragraphs for\n 50 articles). Wrapped citations that start a line (\"9.504/97, art. 24…\", \"22.\") are read as\n dispositivos, and only 12 articles are top-level; the rest fall into a bogus `anexo1`.\n- **With the lines rejoined, it is clean.** One paragraph per dispositivo (281 paragraphs): a line\n starts a paragraph only if it begins with a marker (`Art.`, `§`, `Parágrafo único`, `I –`, `a)`,\n TÍTULO/CAPÍTULO/Seção + title) **and** the previous line ends with `.`, `:` or `;`. Otherwise it is\n a wrapped citation such as \"(Lei nº 9.504/97, art. 28,\" / \"§ 2º).\". Result: 0 parser warnings;\n `art1…art50` in order; 80 parágrafos, 95 incisos, 5 alíneas; 2 títulos, 11 capítulos, 10 seções;\n `art14` complete; URN `urn:lex:br:tribunal.superior.eleitoral:resolucao:2006-06-29;22250`. All but\n 8 of the 5,938 source words are in the XML (the \"Relator …\" line is skipped as post-epigraph).\n- **Profile:** `-a tribunal.superior.eleitoral -t resolucao -n 22250 --data 2006-06-29\n --prof-regex-epigrafe '^resolucao' --prof-regex-pos-epigrafe '^relator' --prof-regex-preambulo\n '^o tribunal superior eleitoral' --prof-epigrafe-head 'RESOLUÇÃO'`. Without the epigraph regex the\n parse stops at \"Epígrafe ausente\"; with `^ementa` in the post-epigraph regex it stops at \"Ementa\n ausente\". `batch_parse.py` needs these for the `resol_tse` stem in R3b.\n- **R3b caveat:** in this shell `LANG=en_US.UTF-8` is set but that locale is not installed, so the\n JVM decodes non-ASCII arguments wrongly (`--prof-epigrafe-head 'RESOLUÇÃO'` → `RESOLU����O`). Run\n the parser with `LC_ALL=C.UTF-8`. The committed `lexml/` has no replacement characters.\n- **Adopted (2026-10-07):** `original/articulados/resol_tse_22250_20060629.docx` is the rejoined file\n (moved from `nao_articulados/` with `git mv`; the as-fetched file is in `git` history). It was made\n with the new `scripts/lexml/rejoin_docx_lines.py`, which moves the runs of each wrapped line into\n the previous paragraph, so formatting is kept:\n `python3 scripts/lexml/rejoin_docx_lines.py <fetched>.docx original/articulados/resol_tse_22250_20060629.docx\n --start '^RESOLUÇÃO' --start '^Relator' --start '^Ementa' --start '^O Tribunal Superior Eleitoral'\n --start '^Sala de Sessões' --start '^Brasília,'`. Its output has the same paragraph text as the\n tested version, and the parse is byte-identical (0 warnings).\n\nRemoving uncited wrong matches keeps the corpus defined as \"documents referred to by the Q&A\".\nLeaving them in only adds distractors that no question needs.\n\n### 1.3 Converting the PDF and ODT files (B3)\n\n**2026-10-07:** the user renamed every PDF to the target stem below and converted the ODTs. The\nSC 354/2014 date was confirmed on the PDF (\"17 de dezembro de 2014\").\n\nTarget names follow `original/` conventions, so `build_v2_dataset.py` resolves them automatically\nonce the canonical list is fixed (§3.3):\n\n| Source | Target stem | Date (from the document) |\n|---|---|---|\n| `SC_Cosit_n_50-2020.pdf` | `sc_cosit_50_20200622` | 22/06/2020 |\n| `SC_Cosit_n_64-2014.pdf` | `sc_cosit_64_20140307` | 07/03/2014 |\n| `SC Cosit nº 7-2017 .pdf` | `sc_cosit_7_20170113` | 13/01/2017 |\n| `SC Cosit nº 75-2020.pdf` | `sc_cosit_75_20200625` | 25/06/2020 |\n| `SC Cosit nº 123-2021.pdf` | `sc_cosit_123_20210913` | 13/09/2021 |\n| `SC Cosit nº 166-2019.pdf` | `sc_cosit_166_20190528` | 28/05/2019 |\n| `SC Cosit nº 173-2015.pdf` | `sc_cosit_173_20150703` | 03/07/2015 |\n| `SC Cosit nº 179-2023.pdf` | `sc_cosit_179_20230816` | 16/08/2023 |\n| `SC Cosit nº 183-2014.pdf` | `sc_cosit_183_20140625` | 25/06/2014 |\n| `SC Cosit nº 211-2019.pdf` | `sc_cosit_211_20190624` | 24/06/2019 |\n| `SC Cosit nº 214-2021.pdf` | `sc_cosit_214_20211220` | 20/12/2021 |\n| `SC Cosit nº 354-2014.pdf` | `sc_cosit_354_20141217` | 17/12/2014 (cited date; confirm on the PDF, whose first page starts with a broken field \"Erro: Origem da referência não encontrada\") |\n| `sc_cosit_69_20131230.odt`, `_140_20210921.odt`, `_194_20150805.odt` | same stems, `.docx` | already in the name |\n\nConversion:\n\n- **ODT → DOCX (done by the user):** `soffice --headless --convert-to docx` (LibreOffice is not installed in this WSL\n image, so either install it or convert on the Windows side). The result is lossless for these\n plain-text documents.\n- **PDF → text, no OCR (tested 2026-10-07 on SC Cosit 166/2019).** The PDFs are born-digital\n (embedded fonts), and `pdftotext -raw` extracts the full text. Extraction is easy; the problem is\n **layout**. The raw output has:\n 1. page furniture on every page: `Cosit`, `Fls. N`, the page number, the header-box labels\n (`Processo`, `Interessado`, `CNPJ/CPF`), and in SC 354/2014 a broken field \"Erro: Origem da\n referência não encontrada\";\n 2. a running header drawn in faux bold (each glyph printed twice, slightly shifted). It comes out as\n `S / So / ol / lu / uç …`;\n 3. a hard line break at the end of every PDF line, so paragraphs are split into lines.\n\n Fed to `lexml_nonstat parse` as is, the whole document becomes **one `<p>`**, with the generic\n profile and a wrong URN (`urn:lex:br:federal:documento:2019-05-28;166`). After a small cleanup\n (drop items 1–2, rejoin lines into paragraphs at sentence ends, numbered paragraphs \"2.\", \"3.\" and\n section headings, and de-hyphenate), the same file is parsed with the **`solucao_consulta`\n profile** and the right URN\n (`urn:lex:br:ministerio.fazenda;secretaria.receita.federal:solucao.consulta:2019-05-28;166`), as\n the existing SC `.docx` files are. The prototype is in this session's scratchpad. It becomes\n `scripts/lexml/pdf_to_text.py`, plus a rule list per page layout: there are two, the 2014–2021\n \"Fls.\" layout and the 2023 \"PROCESSO / SOLUÇÃO DE CONSULTA\" layout of SC 179/2023.\n Known limits of the text route: quoted legal passages lose their indentation, which the parser\n uses as a \"quoted\" cue (the docx sources have the same warnings, so this is minor); a few\n headings (\"Relatório\", \"Fundamentos\") get joined to the next paragraph unless they are listed as\n breaks; and tables, if any, become lines. `pdf2docx` is the alternative if a PDF has tables.\n- **Where things go:** the renamed `.pdf` stays in `original/nao_articulados/` as the source\n document. The cleaned text is a derived file, `lexml/nao_articulados/_text/<stem>.txt` (committed,\n so the parse is reproducible), and it is the parser input. `build_v2_dataset.load_documents` must\n glob `*.docx` **and** `*.pdf` (and `*.odt`, unless they are converted). ODTs are better converted\n to `.docx` in place, keeping the `.odt` in `original/nao_articulados/_sources/`.\n- **Checks:** (i) parse each `.docx`/`.txt` with `lexml_nonstat parse --summary` and confirm a\n `DocumentoGenerico` with an ementa and the expected URN; (ii) text coverage: ≥ 98 % of the\n `pdftotext` word tokens (page furniture excluded) appear in the XML text.\n\n---\n\n## 2. The two requested reference fixes\n\nCommon facts:\n\n- Neither citation appears in `answer_cleaned` (the gold answer), so **nuggets are not affected**.\n- `answer` and `references_text` are verbatim copies of the Receita Federal PDF. **They are not\n edited:** they record what the source says. The correction lives in the `references` row, with\n a `resolution_note` that explains it. The fixes are applied everywhere else (tables below).\n- The legal-provision score de-duplicates gold items per `(question, document)` key\n (`ragpipe/relevance.py: gold_items`), so a second reference to the same document does not count\n twice.\n\n### 2.1 Fix 1 — Q313: remove \"Parecer Cosit nº 30, de 28/09/2001\"\n\nThe act does not exist. Only Q313 uses this v1.1 file name, and it is the last reference of Q313\n(313-06), so no other `reference_id` changes.\n\n| Place | Change |\n|---|---|\n| `scripts/dataset/reference_overrides.json → drop` | add `{\"question_number\": \"313\", \"file\": \"Parecer Cosit nº 30, de 28 de setembro de 2001.txt\", \"reason\": \"user fix (2026-10-07): no such act exists; v1/v2 matched the unrelated ADE Cosit nº 30, de 23/07/2001 (US dollar rate)\"}` |\n| `reference_overrides.json → files` | delete the `\"Parecer Cosit nº 30, de 28 de setembro de 2001.txt\"` `not_in_corpus` entry (the drop makes it dead; the build should refuse dead overrides, §3.3) |\n| `original/articulados/ade_cosit_30_20010723.docx` + `lexml/articulados/ade_cosit_30_20010723.{xml,err.log}` | `.docx` **done** (removed in `7c44d73`); the LexML files go in R2 |\n| `../br-taxqa-document-fetcher/output_canonical/canonical_referred_documents.json` (index 293) | mark the record `\"status\": \"nonexistent_act\"`, with `canonical_name: null` and a `correction` field (§3.3) |\n| `dataset/references.jsonl`, `questions.jsonl` (`document_ids`, `n_unresolved_references`: 1 → 0), `build_report.json` (`dropped_references` gains it), `dataset/README.md` counts | regenerated by the build |\n| `docs/20260927_180401_…md` §5.2a table row and §6 counts | append a dated correction note; don't rewrite the row |\n\n### 2.2 Fix 2 — Q249: \"Parecer PGFN/CAT nº 815/2010\" → Nota PGFN/CRJ nº 981/2015\n\nOnly Q249 uses the v1.1 file `Parecer PGFNCAT nº 815 2010.txt`. Q249 **already cites** Nota 981/2015\nas `249-04` (→ `nota_pgfn_981_20151104`). There are two ways to apply the fix:\n\n- **(a) Recommended: re-point 249-03** to `nota_pgfn_981_20151104` through the `files` override.\n `reference_id`s stay stable, `cited_title` keeps the PDF's wording, and the `resolution_note`\n states the correction. Scoring is unchanged by the duplicate (de-duplicated gold items).\n- (b) Drop 249-03. This gives the same scoring result, but it shifts `249-04…249-16` to `249-03…249-15`.\n\n| Place | Change |\n|---|---|\n| `reference_overrides.json → files[\"Parecer PGFNCAT nº 815 2010.txt\"]` | `{\"document_id\": \"nota_pgfn_981_20151104\", \"reason\": \"user fix (2026-10-07): the citation is replaced by Nota PGFN/CRJ nº 981/2015 (the document v1 held under this name; also cited as 249-04)\"}` |\n| `original/nao_articulados/parecer_pgfncat_815_2010_nota_pgfn_crj_981_2015.docx` | **done** (removed in `7c44d73`; duplicate, dataset note §7.4) |\n| `lexml/nao_articulados/urn_lex_br_ministerio.fazenda_secretaria.receita.federal_sumula_2015_981.xml` and its row in `scripts/dataset/nonstat_lexml_map.tsv` | remove (this is also the wrong URN of item 5) |\n| fetcher canonical record (index 332) | `canonical_name: \"Nota PGFN/CRJ nº 981/2015\"`, `type_slug: nota_pgfn`, `number: 981`, `correction` field (§3.3) |\n| `dataset/*`, `build_report.json` (`unresolved_references` loses 249-03; Q249 `n_unresolved_references` 1 → 0) | regenerated |\n| dataset note §5.2a row | dated correction note |\n\n### 2.3 Fix 3 — Q187: remove \"Solução de Consulta Interna Cosit nº 27, de 7 de julho de 2008\"\n\nThe act cannot be found (user, 2026-10-07). The PDF fetched for it, `SCI Cosit nº 24-2008.pdf`, is\nSCI 24 of 27/06/2008, a different act that no question cites, so it was removed (B2). Only Q187 uses\nthis v1.1 file name, and 187-02 is the last reference of Q187, so no other `reference_id` changes.\nQ187 keeps 187-01 (Lei 7.713, art. 6).\n\n| Place | Change |\n|---|---|\n| `scripts/dataset/reference_overrides.json → drop` | **done:** `{\"question_number\": \"187\", \"file\": \"Solução de Consulta Interna Cosit nº 27, de 7 de julho de 2008.txt\", \"reason\": \"user fix (2026-10-07): … cannot be found …\"}` |\n| `reference_overrides.json → files` | **done:** its `not_in_corpus` entry deleted |\n| `original/nao_articulados/SCI Cosit nº 24-2008.pdf` | **done:** removed |\n| fetcher canonical record | `status: \"not_found\"` (§3.3) |\n| `dataset/*`, `build_report.json` | regenerated in R5 (Q187 `n_unresolved_references` 1 → 0) |\n| dataset note §5.2a row | dated correction note |\n\n---\n\n## 3. Items 2, 5 and 6 of the dataset note's §7\n\n### 3.1 Item 2 — articles that are in the `.docx` but not in the XML\n\n**What it means.** The dataset checks each cited article (e.g. `art24`) against the `id`s in the\ndocument's LexML. For 28 cited article ids (`build_report.json → validation.article_ids_missing`),\nno `<Artigo id=\"artN\">` exists. A gold provision that the XML lacks has **no chunk**. So no retriever\ncan find it, and the legal-provision score counts it as a miss for every system. That depresses all\nstrategies equally and adds noise to S1-vs-S2 comparisons.\n\nI traced every case to its cause. There are six:\n\n| # | Cause | Cases (references) | Evidence | Fix |\n|---|---|---|---|---|\n| 2a | **Revoked text is dropped.** Planalto marks revoked text with strike-through, and the parser drops struck runs, which takes the whole article with them | MP 2.158-35 **art. 24** (560-15, 617-01, 618-02, 618-09, 620-01, 620-08, 621-02, 624-04) | Art. 24 is struck, \"(Revogado pela Lei nº 14.754, de 2023)\". XML has `art23`, `art25` and no `art24` | **Important:** the P&R IRPF 2024 covers calendar year 2023, before the revocation took effect. The article is still the right legal basis, so it must be in the corpus. Keep struck articles as text and mark them revoked, rather than dropping them (preprocessing: remove `<w:strike/>` from runs of an article whose last run says \"(Revogado …)\", and keep the note in the text). Apply corpus-wide (audit, below) |\n| 2b | **A heading read as the start of a bill's \"Justificação\".** The parser is the *projeto de lei* parser, and its `regexJustificativa` marker ends the articulação | Lei 6.404 **art. 252** (584-01); in fact **arts. 225–300 are all missing** | The paragraph \"Justificação\" is the section heading of art. 225. XML stops at `art224`; `ProjetoLei.scala:172,187` | Re-parse statutory documents with `--prof-regex-justificativa` set to a never-matching pattern: enacted acts have no justification section |\n| 2c | **Unclosed amendment quote.** The text after an `Alteracao` is taken as more quoted text, so the act's own articles become `Artigo` elements *inside* the amendment and get no rows of their own (caput plan §3) | Lei 11.941 **art. 56** (312-02); in fact arts. **15–24 and 48–72** are nested (`art47_cpt_alt1_art56` …) | Top-level ids jump `art14 → art25` and `art47 → art73` | Fix the quotes in the `.docx` (add the missing closing `”`/`(NR)`, or split the block) and re-parse. The audit below finds the other cases. **Correction (2026-10-07):** arts. 15–24 are *not* a parser fault: the `.docx` has one line, \"Arts. 15 a 24. (Revogados pela MP nº 627/2013, convertida na Lei nº 12.973/2014)\" |\n| 2d | **Label split across two paragraphs** (\"Art\" / \"3º Arrendamento rural …\") | Decreto 59.566 **art. 3** (480-02) | Its §§ 1–3 were attached to art. 2 (`art2_par1..3`): the gold is missing *and* art. 2 holds wrong text | Merge the two paragraphs in the `.docx` and re-parse |\n| 2e | **Text not in the source.** Planalto prints the article as a dotted placeholder | Lei 13.043 **art. 16** (677-02, 677-04, 699-02, 699-04) | No paragraph starts with \"Art. 16\" | Take the text from the DOU (original publication) and add it to the `.docx`, citing the source in `original/…/README` or in a dated note. Otherwise mark these provisions `unmatchable` (below) |\n| 2f | **Treaty articles.** The question cites an article of a *promulgated treaty*, not of the decree. The treaty text is either missing from the `.docx` (only the 2-article promulgating decree was fetched) or present but numbered `ARTIGO I…`, which the statutory parser does not read as articles | 149-01, 149-03, 150-05, 150-12 (decretos 27.784, 59.308); 152-01, 153-01 (57.942: no article markers at all); 153-04 (361: treaty text absent); 154-01 (86.084); 155-01 (87.563: `ARTIGO I…XXV`); 157-02 (8.289: `Artigo I…XIV` in annex 1); 158-02 (85.801: treaty absent); 159-01 (93.153: treaty absent) | `.docx` paragraph counts of 10–13 for 27.784, 85.801, 93.153 and 361 | (i) Fetch the treaty texts where they are missing (the DOU/Senado publication). (ii) After the move to `nao_articulados`, these documents have no `Artigo` ids at all. So map treaty articles to the non-statutory blocks: the non-statutory segmenter emits each `ARTIGO N` heading as a block boundary, and the build records `fragment_id = null`, `block_label = \"ARTIGO V\"`, matched by label. (iii) Until then, score them at **document level only** |\n\n#### 3.1.1 Status after the user's `.docx` repairs (checked 2026-10-07)\n\nThe user repaired MP 2.158-35, Lei 11.941, Decreto 59.566 and Lei 13.043 (the working tree is not\ncommitted). Lei 6.404 was not changed. I re-parsed all five with the **same jar** that produced\ntoday's `lexml/` (`phase2.jar`, the command line in each `.err.log`) into the session scratchpad,\nand compared the top-level `Artigo` ids with the committed XML and with the `.docx` article labels.\n\n| Document | What the user changed | Top-level articles (old → new) | Cited article | Result |\n|---|---|---|---|---|\n| MP 2.158-35 (2a) | New source text: no strike-through runs (76 struck paragraphs → 0); art. 24 is plain text, without the \"(Revogado …)\" note | 89 → **93**, equal to the 93 `Art.` paragraphs of the `.docx`, no gaps | `art24` ✔ (full text, §§ 1–7) | **Fixed.** No duplicate-label warnings, so no superseded wordings were left in. The text is the version in force in 2023, which suits the P&R 2024 |\n| Lei 11.941 (2c) | Added the closing `…” (NR)` after art. 47's amendment block | 45 → **70**, equal to the `.docx` | `art56` ✔ | **Fixed.** The only gap, arts. 15–24, is the collective revocation (see 2c). Arts. 48–72 are now top-level |\n| Decreto 59.566 (2d) | Merged \"Art\" + \"3º …\"; also joined four broken quoted fragments (`\" b` / `\"`) and fixed `Art 41.O` | 88 → **89**, equal to the `.docx` | `art3` ✔ (and §§ 1–3 are back under art. 3) | **Fixed** |\n| Lei 13.043 (2e) | **Round 1:** new source, the Planalto compilation instead of the Câmara text (art. 16 present; arts. 2 etc. in the wording before MP 1.303/2025). **Round 2:** fixed the two amendment closings (end of art. 50 and art. 84). **Round 3:** removed the superseded wordings of arts. 19, 42 and art. 22 § 1º | 103 → **115**, equal to the 115 `.docx` labels; no gaps, no duplicate ids, arts. 51–53 and 85 top-level, `art28-1` present | `art16` ✔ | **Fixed.** 0 duplicate-label warnings (29 before). Kept: art. 19 = original wording (caput + §§ 1–3); art. 42 = the Lei 13.097/2015 wording; art. 22 § 1º = \"O percentual referido no caput poderá variar…\" (the first of the two wordings; confirm on Planalto that it is the one in force in 2023). Heading typos remain (minor, below) |\n| Lei 6.404 (2b) | **Round 2:** deleted the \"Justificação\" heading paragraph before art. 225 (the only change in the `.docx`) | 232 → **314**, up to `art300`, equal to the `.docx` (A-articles included, e.g. `art4-1`, `art299-2`) | `art225`, `art252` ✔ | **Fixed**, with or without `--prof-regex-justificativa`. Its 6 duplicate-label warnings (arts. 59, 140, 183) were already in the committed parse. R3b still passes the flag for all statutory documents, as a guard |\n\n**Lei 13.043: what is left (after round 3).** Only cosmetic: split words in headings, \"Do s Fundos…\",\n\"D a Isenção…\", \"D a Contribuição…\", \"D a Legislação Aduaneira\", \"D a Legislação Tributária…\",\n\"D a Alienação Fiduciária\", and \"PRESIDENTE DA REPÚBLIC A Faço saber\" in the preamble. They reach\nonly the grouping chunks (S3) and the preamble, not article chunks. Fixing them is optional and does\nnot change any article id.\n\n**All five item-2 `.docx` repairs are done** (MP 2.158-35, Lei 11.941, Decreto 59.566, Lei 6.404, Lei 13.043). The remaining item-2 cases are the treaty articles (2f) and whatever the corpus-wide audit finds.\n\n**Corpus-wide audit (new, `scripts/lexml/audit_article_coverage.py`).** Every case above was found\nonly because a question cites the article. Others surely exist. For each statutory `.docx`, list the\nparagraphs that start an article (`^Art\\.?\\s*\\d+`, outside quotes) and compare them with the\ntop-level `Artigo` ids of the XML (main plus annexes). Report missing, nested-in-`Alteracao` and\nout-of-order ids per document, flagging cited documents first. Run it after R3, and fix by cause\n(2a–2e). Gate: no cited article missing, unless it is listed in an `unmatchable` table with a\nreason.\n\n**Scoring rule for what remains:** the build marks each remaining provision `\"matchable\": false`.\n`ragpipe/relevance.py` then reports metrics over matchable gold, with the unmatchable count shown\nnext to them. That is better than silently counting them as misses.\n\n### 3.2 Item 5 — wrong authority or type in non-statutory URNs\n\n**What it means.** Each document's URN (`urn:lex:br:<authority>:<type>:<date>;<number>`) is its\nidentity across the pipeline: `document_urn` in the dataset, `doc_urn` in the chunks, and the\n`Remissao` links that `lexml-linker` writes when it finds \"Nota PGFN/CRJ nº 1.104/2017\" in a text.\nThe non-statutory parser **infers** authority and type from the document's text and profile, and\nfor some documents it guessed wrong. Today gold and chunks agree, because both copy the same wrong\nURN. But the planned legal-provision check on *generated answers* would extract the citation with\n`lexml-linker`, get the *correct* URN, and fail to match.\n\nAudit of the 234 current non-statutory URNs, grouped by stem prefix (consistent groups omitted):\n\n| Stem prefix | URN authority : type | Should be |\n|---|---|---|\n| `nota_pgfn_981…` | `…receita.federal : sumula` | `procuradoria.geral.fazenda.nacional : nota` |\n| `nota_pgfn_crj_*` (3) | `pgfn : nota.pgfn`, `superior.tribunal.justica : solucao.consulta`, `…receita.federal : portaria` | `procuradoria.geral.fazenda.nacional : nota` |\n| `nota_sei_48_2018` | `pgfn : nota.pgfn` | the issuing body of the SEI note (to check) |\n| `par_pgfn`, `parecer_pgfn_crj` (2), `parecer_pgfn_pga` (2), `parecer_sei` (3), `parecer_pgfncat_1503` | `superior.tribunal.justica`, `…receita.federal`, `ministerio.fazenda`, `federal` | `procuradoria.geral.fazenda.nacional : parecer` (SEI pareceres: issuing body as printed) |\n| `sc_*` (1 of 2) | `federal : solucao.consulta` | `…receita.federal : solucao.consulta` |\n| `in_srf_84_19791220` | `…receita.federal : ato.declaratorio` | check: the stem says IN SRF, the URN says AD |\n| the 11 moved documents | not parsed yet | the **statutory** URNs they had (`urn:lex:br:federal:decreto:1950-02-16;27784`, …), which `lexml-linker` produces for \"Decreto nº 27.784\" |\n\n**Fix.** Make URNs **declared, not inferred**, for this corpus:\n\n1. Add `scripts/lexml/nonstat_metadata.tsv` (stem → authority, type, date, number), generated from\n the stems and the (fixed) canonical records, then reviewed by hand. The 20 documents whose parser\n date was `0000` (dataset note §4.1) also go here.\n2. Upstream, in `../lexml_parser_non_statutory`, add `parse --urn <urn>` (or `--metadata <tsv>`).\n This overrides the inferred URN in `Identificacao`, in the output file name and in `@xlink:href`\n bases. Until it lands, a post-parse rewrite step in this repo does the same\n (`scripts/lexml/fix_nonstat_urns.py`).\n3. **Normalize URN vocabulary with `lexml-linker`.** For each corrected type, run the linker on the\n document's own title (\"Nota PGFN/CRJ nº 981/2015\") and require that it yields the same URN. That\n check is the actual goal, and it also catches type spellings (`nota` vs `nota.pgfn`).\n4. Since all non-statutory XMLs are re-parsed anyway (R3), regenerate `nonstat_lexml_map.tsv`\n **from the parse output** instead of by matching. The re-parse + manual pairing of dataset note\n §4.1 is no longer needed.\n5. Build check (new): `document_urn` equals the linker URN of `cited_title` for every resolved\n reference whose title has a number. List the exceptions (colloquial titles, treaties).\n\n### 3.3 Item 6 — the fetcher's canonical list still carries the errors\n\n**What it means.** `canonical_referred_documents.json` (in `../br-taxqa-document-fetcher`) maps each\nv1.1 file name to the act it *should* be (type, number, date). `build_v2_dataset.py` uses it to find\nthe `original/` stem automatically (`prefix + number + date`). For the 26 acts of dataset note §5.2a\nand the 2 of §5.2b, the record names the **wrong** act, because the fetcher picked a\nsame-numbered act from another year. For example, `Solução de Consulta Cosit nº 50.txt` → \"SC\nCosit nº 50, de 22 de março de **2024**\", and `Parecer Cosit nº 30…txt` → \"ADE Cosit nº 30\". The\ncorrections were put only in this repo's `reference_overrides.json`, as `not_in_corpus` entries.\nConsequences:\n\n- the canonical list, which is the fetcher's source of truth and the input of any re-fetch, still\n says to fetch the wrong acts;\n- now that the right documents are in `original/` with proper stems, the build **still** resolves\n them through the overrides, which say `not_in_corpus`. Without a fix, the 22 new documents would\n remain uncited and the 42 references unresolved;\n- two sources of truth disagree, and nothing checks them against each other.\n\n**Fix.**\n\n1. **Correct the records in the fetcher** (`scripts/fix_canonical_records.py` there, driven by a\n reviewed JSON of corrections). For each §5.2a/b record, set `canonical_name`, `type_slug`,\n `number`, `date` to the cited act, `source: \"manual\"`, and add\n `\"correction\": {\"date\": \"2026-10-07\", \"was\": \"<old canonical_name>\", \"reason\": \"…\"}`. Special\n cases:\n - `Parecer Cosit nº 30…` → `status: \"nonexistent_act\"` (fix 1);\n - `Parecer PGFNCAT nº 815 2010.txt` → Nota PGFN/CRJ 981/2015 (fix 2);\n - `Solução de Consulta Interna Cosit nº 27…` → `status: \"not_found\"` (fix 3: the act cannot be\n found; the record's current target, SD Cosit 27/2008, is a different act);\n - `Solução de Consulta Cosit nº 183.txt` → nº **183**, 25/06/2014 (the record had 134);\n - IN RFB 1.997/2019 (§5.2b) and the Convenção … Nações Unidas (→ `decreto_27784`);\n - `Resolução TSE nº 22.250, de 2006.txt` (index 344) → `date: 2006-06-29` (now in `original/`).\n The build's `PREFIX` already has `resolucao_tse → resol_tse` (§1.2).\n Also regenerate `output_canonical/by_type/*.md`, and record the change in a dated note in the\n fetcher repo.\n2. **Make this repo trust the corrected list.** Delete from `reference_overrides.json → files` every\n `not_in_corpus` entry whose act is now in `original/`; they then resolve as `auto_exact`. What\n remains in `files` are true hand mappings (stems with no date, treaties). `drop`, `reassign`\n and `citations` stay, since they are per-question decisions that do not belong in the fetcher.\n3. **New build guards in `build_v2_dataset.py`:**\n - *dead override*: fail if a `files` override is never used, or if its file name is fully covered\n by `drop`;\n - *redundant override*: warn when the automatic resolution gives the same answer as the override;\n - *contradiction*: fail if an override says `not_in_corpus` but the canonical record resolves\n `auto_exact`;\n - *uncited document*: list stems in `original/` that no question cites (the corpus should be\n exactly the cited set, plus a whitelist).\n4. Pin the canonical file's SHA-256 in `build_report.json` (already done) **and** print the fetcher's\n git commit next to it.\n\n---\n\n## 4. Segmentation: the caput plan, adapted to a changed corpus\n\nThe caput plan assumed an **unchanged corpus**: invariant (i) \"every non-paragraph-family `base` row\nis byte-identical to the frozen set\", reuse of frozen `chunk_id`s for `caput` rows, and embedding\nwith `--extend` for only the 29,876 new texts. After this rebuild many documents change (new,\nremoved, re-routed, re-parsed with fixes 2a–2d, new URNs), so these assumptions are relaxed:\n\n| Caput plan item | Change in this plan |\n|---|---|\n| D-A, D-B, S1–S5 definitions, `variante` column, `contexto_ids` (§4.1–4.2) | **unchanged** |\n| C1–C3, C6–C8, C10 | **unchanged** (implement as written) |\n| C4 `--chunk-id-source` (reuse frozen ids) | **Dropped.** Old and new results are not comparable anyway, because the corpus differs. Chunk ids are assigned fresh: `<stem>#<seq>` for `base`, `<stem>#c<seq>` for `caput` |\n| C5 `base_unchanged`, `caput_variant_frozen` | Replace with **`diff_vs_frozen`**: restricted to documents whose LexML SHA-256 did not change, base rows must equal the frozen ones and `caput` rows the frozen paragraph-family rows. The check reports, not gates, the documents that changed. The other C5 checks stay |\n| C9 `--extend` | Generalize to **embed by text hash**: reuse any vector whose `texto_sha256` is in the existing store, and embed only new texts. This covers both the caput-free texts and the changed documents, and it is still much cheaper than a full re-embed |\n| §4.6 renaming of old results | Still true (old S2/S3 = S2c/S4 on the **old corpus**). New runs use a new `eval_id` and new manifests |\n\nOpen questions Q1–Q3 of the caput plan, defaults taken unless the user says otherwise: **Q1** keep\nthe 128-token ementa; **Q2** keep the caput sentence in the HEAD of split ART parts; **Q3** S5 later.\n\nAlso in segmentation:\n\n- `classify_annexes.check_counts` will fail, because category counts change (new annexes, the\n re-parse of Lei 6.404, treaty annexes). Run with `--allow-count-change` once and record the new\n counts.\n- The 11 moved documents become TXT/TAB chunks (non-statutory path), with the statutory URNs of\n §3.2.\n\n---\n\n## 5. Rebuild order\n\nEach step ends with its check. Commit after each **R**-step, so that a failure can be bisected.\n\n| Step | What | Commands / files | Check |\n|---|---|---|---|\n| **R0** | Decisions (§7) + blocker B4 (B1–B3 done) | §1.2 removals **done** (`7c44d73`) | `git status` shows exactly the intended `original/` changes |\n| **R1** | PDF → cleaned text (§1.3; ODTs already converted) | `scripts/lexml/pdf_to_text.py` → `lexml/nao_articulados/_text/`; `build_v2_dataset.load_documents` globs `*.pdf` too | §1.3 checks (i), (ii) |\n| **R2** | Clean stale LexML | delete `lexml/articulados/{11 moved stems, ade_rfb_3_20240402, ade_cosit_30_20010723, lei_8794_19931221}.*` (`decreto_lei_8794_19460123` and `resol_tse_22250_20060629` are new and parsed in R3b; the latter with the TSE profile of §1.2 and `LC_ALL=C.UTF-8`), and every `lexml/nao_articulados/*.xml` (fully regenerated in R3) | for each folder, the set of `lexml` stems equals the set of `original` stems |\n| **R3a** | `.docx` repairs for item 2: MP 2.158-35, Lei 11.941 and Decreto 59.566 **done**; Lei 6.404 and Lei 13.043 **done** (Lei 13.043 heading typos optional); then the repairs that the audit finds | edit the `.docx` (pre-edit copies stay in `git` history; list the edits in the results note) | §3.1.1 re-parse check per document: top-level ids = `.docx` article labels, no duplicate-label warnings |\n| **R3b** | Re-parse **statutory**: all of `original/articulados` (≈ 205 stems), with a pinned, reproducible jar | `../lexml-parser-projeto-lei/scripts/batch_parse.py` with a pinned jar: the old logs point at `phase2.jar` in another session's scratchpad (`/tmp/claude-0/-work-unicamp-articles-RAG-evaluation-lexml-parser-projeto-lei/…/phase2.jar`, still present and used for the §3.1.1 check). Copy it to a stable path, or rebuild it from the parser repo's commit and check that both produce identical XML, and record its SHA-256 in `lexml/articulados/PARSER_VERSION`, `--prof-regex-justificativa` never-match (2b), `--linker /usr/local/bin/linkertool` | `skipped_report.txt` reviewed; `audit_article_coverage.py` (§3.1) passes or lists `unmatchable` |\n| **R3c** | Re-parse **non-statutory**: all of `original/nao_articulados` (≈ 247 stems), declared URNs (§3.2) | `python -m lexml_nonstat parse -o lexml/nao_articulados/ …` + `fix_nonstat_urns.py` until `--urn` exists upstream; regenerate `scripts/dataset/nonstat_lexml_map.tsv` from the output | XSD-valid; URN = `nonstat_metadata.tsv`; linker round trip (§3.2 step 3) |\n| **R4** | Fix the canonical list in the fetcher (§3.3 step 1) | `../br-taxqa-document-fetcher` commit | 28 corrected records + 1 `nonexistent_act` |\n| **R5** | Dataset | `reference_overrides.json` (§2, §3.3 step 2) + build guards (§3.3 step 3), the `matchable` flag (§3.1) → `python3 scripts/dataset/build_v2_dataset.py` | see the expected deltas below; tests in `scripts/dataset/tests` updated |\n| **R6** | Segmentation code: caput plan C1–C5, C10, adapted as in §4 | `scripts/segmentation/*` | unit tests + XSL/Python parity with both `caput_em_paragrafo` values |\n| **R7** | Full segmentation run → new frozen set | `python scripts/segmentation/segment_all.py --jobs 16 --overwrite --allow-count-change --variants caput` | `validate_segments.py` passes; `diff_vs_frozen` report; **no cited document without chunks** (`build_report → cited_documents_without_chunks` empty after re-running R5 against the new chunks) |\n| **R8** | Embeddings | C9 generalized (embed by text hash) → `embed.py corpus --model jua-4b-mixed --extend`; parity gate; queries unchanged | store covers every `texto_sha256` of the new `chunks_all` |\n| **R9** | RAG: C6, C7 (`variantes`, S2c/S4, new `expected_rows` and chunk-file SHA-256) | `rag.py retrieve` + `evaluate` for S1, S2, S3, S2c, S4 with a **new `eval_id`** (e.g. `v2c_either_containment_skip`) | report and metrics written; old `runs/…/either_containment_skip` untouched |\n| **R10** | Notes and docs (§6) | — | — |\n\n**Expected dataset deltas after R5** (to check, not to force):\n\n- `not_in_corpus`: 42 → **0**. 249-03 is re-pointed (fix 2), 313-06 and 187-02 are dropped\n (fixes 1 and 3), 438-03 resolves to `resol_tse_22250_20060629` (§1.2), and the other 38 resolve\n `auto_exact` to the new documents (SCs, ADs, ADI 3/2016, DL 8.794/1946, PN CST 38/1975 and\n 72/1979, Diat).\n- Questions with ≥ 1 unresolved reference: 37 → **0** (Q438 included).\n- Dropped references: 7 → **9** (+ 313-06, 187-02).\n- Q179 unchanged (B1 restored); Q249 and Q313 `n_unresolved_references` → 0.\n- Corpus documents: 459 → **458**. After B1 and B2, `original/` held 461 files (`.docx` + `.pdf`);\n `7c44d73` removed 4 (D3) and added Res. TSE 22.250, so it now holds **458**.\n- `article_ids_missing`: 28 → only the `unmatchable` list.\n\n---\n\n## 6. Notes and documentation to update (R10)\n\n| File | Update |\n|---|---|\n| new `docs/<ts>_corpus_rebuild_results.md` | what was run, counts before/after, `diff_vs_frozen` summary, new IR results (S1/S2/S3/S2c/S4) |\n| `docs/20260927_180401_…dataset_v2…md` | dated header note: §5.2a rows resolved by the 2026-10-07 corpus fix; fixes 1–2; §7 items 1–6 status with a pointer here |\n| `docs/20261005_184116_…caput…md` | header note: C4/C5/C9 adapted (§4 here) |\n| `docs/20260927_222210_retrieval_legal_provision_test_jua.md` | header note: old corpus; S2/S3 = S2c/S4 |\n| `docs/20260923_193852_…strategies…md`, `docs/20260924_123747_…plan.md` | the caput plan's §6 updates |\n| `CLAUDE.md` | strategy list (S4/S5), `_sources/` folder, `scripts/lexml/` |\n| `dataset/README.md`, `scripts/dataset/README.md` | counts, the `matchable` field, the guards, the canonical-list dependency |\n| `scripts/segmentation/README.md`, `scripts/rag/README.md`, `scripts/embedding/README.md` | as in the caput plan §6, plus \"embed by text hash\" |\n\n---\n\n## 7. Decisions needed from the user\n\n| # | Question | Recommendation |\n|---|---|---|\n| D1 | B1: restore `ad_pgfn_3_20080918` (Q179)? | **Decided: yes, done** |\n| D2 | B2: SCI 24/2008 PDF and Q187 | **Decided:** PDF removed; 187-02 dropped (fix 3) |\n| D3 | Remove the uncited wrong matches (`lei_8794_19931221`, `ade_cosit_30_20010723`, `resol_tse_22205_20060523`) and the Nota-981 duplicate? | **Decided: yes, done** (`7c44d73`); Res. TSE 22.250 fetched as well |\n| D4 | Q249: re-point 249-03 (a) or drop it (b)? | **(a)**, stable ids |\n| D5 | MP 2.158-35 art. 24 and other revoked articles: keep them as text marked \"revogado\" (2a)? | **Done for MP 2.158-35** (the user used a source without strike runs). For other documents, the audit decides; whatever the source, each article must appear once, in its 2023 wording |\n| D6 | Lei 13.043 art. 16 (2e): add the DOU text, or mark it unmatchable? | **Done** (Planalto source). The remaining Lei 13.043 items are in §3.1.1 |\n| D7 | Treaty articles (2f): fetch the missing treaty texts and match by block label, or score at document level only? | Fetch them; document level only until done |\n| D8 | URN fix (item 5): upstream `--urn` option in `lexml_parser_non_statutory`, or post-parse rewrite here? | Upstream, with the rewrite as a stop-gap |\n| D9 | Caput plan Q1–Q3 | the defaults in §4 |\n\n---\n\n## 8. Review log\n\n**2026-10-07, after the user's review:**\n\n- D1: `ad_pgfn_3_20080918.docx` restored from `1db1c58`.\n- D2: SCI 24/2008 PDF removed (no question, reference or canonical record mentions it). Q187's\n SCI 27/2008 reference dropped (fix 3, §2.3); `reference_overrides.json` validated as JSON (63\n `files`, 8 `drop` entries).\n- The user will rename the PDFs to the target stems of §1.3.\n- PDF text extraction without OCR: confirmed and tested (§1.3).\n- **Found while checking:** `build_v2_dataset.py` reads `--questions` by default from\n `../questions_QA_2024_v1.1_manual_fix.json`, which no longer exists. The copy\n `../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json` has the same SHA-256 as the one recorded\n in `build_report.json` (`097abfc4…1585`). R5 passes it with `--questions`, or the default is\n changed to that path.\n- The dataset has **not** been rebuilt yet: as it stands, the build would fail on the new stems\n missing from `nonstat_lexml_map.tsv` (R3c).\n\n**2026-10-07, second review (`.docx` repairs and PDF renames):**\n\n- PDFs renamed to the §1.3 stems; ODTs converted to `.docx` (text identical to the ODTs). B3 done\n except the text extraction (R1).\n- Item 2 repairs re-parsed and checked (§3.1.1): MP 2.158-35, Lei 11.941 and Decreto 59.566 are\n fixed. Lei 13.043 has art. 16 now, but two amendment closings are malformed (arts. 51–53 and 85\n nested) and superseded wordings of arts. 19, 22 and 42 are merged. Lei 6.404 needs only the\n parser flag, tested.\n- Correction to 2c: Lei 11.941 arts. 15–24 are revoked collectively; there is no parser defect.\n- The re-parsed XMLs are only in the session scratchpad; `lexml/` is unchanged until R3b.\n\n**2026-10-07, third review (Lei 6.404 and Lei 13.043, round 2):**\n\n- Lei 6.404: the \"Justificação\" heading was removed; the re-parse gives all 314 articles (225 and 252\n included), with or without the parser flag. Done.\n- Lei 13.043: both amendment closings fixed (arts. 51–53 and 85 are top-level), and the Word lock\n file is gone. Still open: the duplicate versions of arts. 19 and 42 (now duplicate XML ids) and\n of art. 22 § 1º, plus the heading typos (§3.1.1 items 2–3).\n\n**2026-10-07, fourth review (Lei 13.043, round 3):**\n\n- Superseded wordings removed. Re-parse: 115 top-level articles = 115 `.docx` labels, no gaps, no\n duplicate ids, 0 duplicate-label warnings. All five item-2 `.docx` repairs are done.\n- To confirm: the art. 22 § 1º wording kept is the first one (\"…referido no caput poderá variar…\").\n- Optional: heading typos in Lei 13.043 (\"D a …\", \"Do s …\", \"REPÚBLIC A\").\n\n**2026-10-07, fifth review (§1.2 removals, commit `7c44d73`):**\n\n- `decreto-lei_8794_19460123.docx` renamed to `decreto_lei_8794_19460123.docx` (the build's\n `decreto_lei` prefix; the hyphenated name would not have resolved).\n- Removed: `lei_8794_19931221.docx`, `ade_cosit_30_20010723.docx`,\n `parecer_pgfncat_815_2010_nota_pgfn_crj_981_2015.docx`, `resol_tse_22205_20060523.docx`.\n- Added: `resol_tse_22250_20060629.docx` (`nao_articulados/`), the act Q438 cites. `original/` now\n holds 458 files.\n- Q438: `resolucao_tse → resol_tse` added to the build's `PREFIX`, and the `not_in_corpus` override\n deleted. `resolve()` returns `resol_tse_22250_20060629` (`auto_undated`); the\n `port_conj_tse_srf_74` record is unaffected; `scripts/dataset/tests` pass (36). Open: the act sits\n in `nao_articulados/`, so `art14` will lack an `Artigo` id (§1.2).\n- D3 done. The stale LexML of the removed documents (including\n `…resolucao.tse_2006-05-23_22205.xml` and `…sumula_2015_981.xml`) is deleted in R2 (B4).\n- The commit also added the Word lock file `original/articulados/.~lock.lei_13043_20141113_fix.docx#`,\n which is already deleted in the working tree; commit that deletion (and consider a `.~lock.*`\n entry in `.gitignore`).\n\n**2026-10-07, sixth review (Res. TSE 22.250 to the statutory path):**\n\n- The as-fetched `.docx` breaks the statutory parse (hard line breaks; 12 of 50 articles top-level).\n Rejoined with the new `scripts/lexml/rejoin_docx_lines.py` and moved to\n `original/articulados/resol_tse_22250_20060629.docx`. Parse check: 0 warnings, `art1…art50`, `art14`\n complete (§1.2). `resolve()` still returns it for 438-03.\n- The parser jar for R3b can be rebuilt from `../lexml-parser-projeto-lei` HEAD (`ebf6567`) with\n `mvn -Ponejar package`; it reproduces `lei_9250_19951226.xml` byte for byte. The `phase2.jar` path\n in the `.err.log` files no longer exists.\n","20261008_010441_corpus_rebuild_results.md":"# Corpus Rebuild Results (R1–R10): LexML → segmentation with caput variants → dataset → embeddings → retrieval\n\n**Generated:** 2026-10-08 01:04:41 (local time, from `date +%Y%m%d_%H%M%S`)\n**Executes:** `docs/20261007_180833_corpus_fixes_and_full_rebuild_plan.md` (**the rebuild plan**; steps\nR1–R10) and the segmentation part of\n`docs/20261005_184116_segmentation_s3_vs_lima_ementa_and_caput_strategy_plan.md` (**the caput plan**;\nD-A, D-B, C1–C10). Decisions taken: the plan's recommendations D4 (re-point 249-03), D7 (treaty\narticles at document level), D8 (declared URNs upstream) and the caput plan's defaults Q1–Q3\n(128-token ementa, caput sentence kept in split-part HEADs, S5 later).\n**Embedding:** only `jua-4b-mixed` (the only model embedded so far), instruction `irpf`.\n**Status:** done. Every step ends with its check passing. Open points are in §6.\n\n---\n\n## 1. Summary\n\n| | Before (2026-09-27) | After (2026-10-08) |\n|---|---:|---:|\n| `original/` files (articulados + nao_articulados) | 225 + 234 = 459 | 214 + 244 = 458 (12 of them PDFs) |\n| `lexml/articulados` XML (main + annexes) | 467 | 455 |\n| `lexml/nao_articulados` XML | 235 | 245 (244 documents + 1 annex) |\n| Chunk rows (`chunks_all.csv.gz`) | 87,702 | 118,766 = 88,600 `base` + 30,166 `caput` |\n| S1 / S2 / S3 rows | 26,250 / 82,642 / 87,702 | 26,364 / 83,496 / 88,600 |\n| S2c / S4 rows | — | 83,496 / 88,600 |\n| References / `not_in_corpus` / dropped | 1,919 / 42 / 7 | 1,917 / **0** / 9 |\n| Questions with an unresolved reference | 37 | **0** |\n| Documents / cited / cited without chunks | 459 / 424 / **11** | 458 / 447 / **0** |\n| Cited article ids missing from the LexML | 28 | 13, all treaty articles, listed as unmatchable |\n| Cited provision fragments missing | 41 | 25 |\n| Unique texts embedded (`jua-4b-mixed`) | 84,568 | 115,582 (83,388 reused, 32,194 new, $0.27) |\n\n**Headline retrieval result** (recall at a 4k-token context, all gold; §4):\n\n| Level | S1 | S2 | S3 | S2c | S4 |\n|---|---:|---:|---:|---:|---:|\n| document | 0.604 | **0.665** | 0.652 | 0.631 | 0.627 |\n| article | 0.379 | **0.473** | 0.464 | 0.428 | 0.426 |\n| provision | 0.347 | **0.361** | **0.361** | 0.321 | 0.334 |\n| provision, sub-article gold | 0.313 | **0.424** | 0.409 | 0.370 | 0.367 |\n\n**Adding the caput sentence to paragraph chunks hurts retrieval** (S2c < S2 and S4 < S3, significant\nat every budget and level, §4.2). Decision D-A, caput-free paragraph chunks, is the better S2.\n\n---\n\n## 2. Commits\n\n| Repository | Commit | Step |\n|---|---|---|\n| br-taxqa-r_v2.0 | `408cf46` | R1: PDF → cleaned text |\n| | `5d97665` | R2/R3a/R3b: statutory re-parse, MP 2.189-49 un-struck, audit |\n| | `bf94141`, `bf79a58` | R3c: non-statutory re-parse with declared URNs; front-matter fix re-parse |\n| | `496acbb` | R5 code: dataset build |\n| | `51536b9` | R6: segmentation code (caput plan C1–C5, C10) |\n| | `f2e49d7` | R8 code: `embed.py corpus --extend` |\n| | `9513dbb` | R9 code: strategy variants in the RAG pipeline |\n| | `280121b` | R7: segmentation run (new frozen chunk set) |\n| | `7d88bd6` | R5: dataset rebuilt (clean tree, after R7) |\n| | (next commit) | R8/R9 outputs, R10 docs (this note) |\n| ../lexml-parser-projeto-lei | `6142756` | `batch_parse.py`: `--no-justificativa`, `--only`, TSE resolutions (`work_history/20261008_001450_*`) |\n| ../lexml_parser_non_statutory | `d9624a7` | `parse --urn / --metadata` (`docs/20261008_003108_declared_urn_option.md`) |\n| | `e8c3d1e` | front matter: layout tables, presidential preamble, portal lines (`docs/20261008_003915_*`) |\n| ../br-taxqa-document-fetcher | `c7f4b8f` | 27 canonical records corrected (`20261008_002333_canonical_list_corrections.md`) |\n\nNone of these commits is pushed.\n\n---\n\n## 3. Steps as run\n\n### R0 — decisions and blockers\n\nB1–B3 were done before this run (rebuild plan §8). B4 (stale LexML) is handled by regenerating both\n`lexml/` folders completely (R2). The Word lock-file pattern `.~lock.*` was added to `.gitignore`.\n\n### R1 — PDF → text (`scripts/lexml/pdf_to_text.py`)\n\nThe rebuild plan's prototype was lost with an earlier session's scratchpad, so the converter was\nrewritten. It reads `pdftotext -bbox-layout` (line positions) rather than `-raw`:\n\n- **Furniture by position.** Lines above y = 72 pt are dropped, and so are lines between 72 and\n 90 pt that look like furniture (\"Cosit\", \"Fls. N\", the faux-bold running header \"S o l u ç ã o…\",\n \"Erro: Origem da referência não encontrada\"). Lines below 785 pt (page number, \"Cópia autenticada\n administrativamente\") are dropped too. A fixed 85 pt cut would have lost the first line of some\n pages (body text starts at y ≈ 81 in SC 211/2019 and 214/2021).\n- **Header box → title.** Everything before `Assunto:` on page 1 (Processo, Interessado, Data…)\n becomes `Solução de Consulta Cosit nº N, de <data>`, the first line of the existing SC `.docx`.\n- **Paragraphs from geometry.** Words on one baseline are merged, so \"2.\" joins its text. A gap\n above 1.3 × the line spacing starts a paragraph. A paragraph cut by a page break is rejoined when\n its last line has no closing punctuation or the next page starts in lower case. Words closer than\n 0.5 pt are joined: small caps came out as \"A SSUNTO : I MPOSTO…\".\n- **Ementa zone:** the `Assunto:` line, upper-case heading runs and ementa texts become separate\n paragraphs, as in the `.docx`.\n- **Quotation indent:** paragraphs whose lines all start right of the body margin (taken from the\n numbered paragraphs) get leading spaces (180 twips per space in `txt_reader`).\n\nChecks (plan §1.3): all 12 files route to the `solucao_consulta` profile with the right URN, and\n**100 %** of the `pdftotext -raw` word tokens (furniture excluded) are in the text. Output:\n`lexml/nao_articulados/_text/<stem>.txt` (committed).\n\n### R2/R3a/R3b — statutory LexML\n\n- **Jar.** The jar in `../lexml-parser-projeto-lei/target/` was from 2026-05-25, older than HEAD\n `ebf6567`. It was rebuilt with `mvn -Ponejar package -DskipTests` (SHA-256 `51963519…a766`).\n Provenance is in `lexml/articulados/PARSER_VERSION`.\n- **Driver.** `batch_parse.py --no-justificativa --linker /usr/local/bin/linkertool original/articulados …`.\n The new flag passes `--prof-regex-justificativa '(?!)'` (cause 2b guard). The `resolucao` overrides\n gained `%^relator` (post-epígrafe) and `%^o tribunal superior eleitoral` (preamble), so\n `resol_tse_22250_20060629` parses with the batch (rebuild plan §1.2): 50 articles, `art14` present.\n- **Result:** 214 converted, 0 skipped, 0 failed. 440 of the 451 files shared with the previous\n parse are **byte-identical**, so the jar reproduces the committed corpus. Of the other 11, 7 come\n from the `.docx` repairs (Decreto 59.566, Lei 11.941, Lei 13.043, Lei 6.404, MP 2.158-35 main +\n annex, MP 2.189-49). The other 4 differ only in `Remissao` links (§5.3).\n- **Corpus-wide audit** (new `scripts/lexml/audit_article_coverage.py`). It compares each `.docx`'s\n article labels outside quotes with the top-level `Artigo` ids of the main and annex XMLs. Before:\n 36 documents differed, with 10 cited ids missing. After the repairs: 21 documents differ, and no\n cited id is missing apart from the treaty articles in `scripts/lexml/unmatchable_articles.tsv`\n (the gate). One new case was found and fixed:\n - **MP 2.189-49, arts. 1–6 (cause 2a).** Planalto strikes them through with \"(Revogado pela Lei\n nº 14.754, de 2023)\". The parser drops struck runs, so the XML started at art. 7. Lei 14.754 took\n effect in 2024, so these articles were in force in 2023 (D5). New\n `scripts/lexml/unstrike_revoked.py --revoked-by 'Lei nº 14\\.754, de 2023'` removed the strike from\n the 28 paragraphs of those articles and of the art. 10 amendment item they belong to; the note\n stays in the text. Re-parse: `art1…art20` top-level. Only one other statutory document has\n struck articles: `mp_2228-1_20010906` (uncited), whose struck text is superseded wordings, so it\n was left alone. A corpus scan found no other \"Revogado pela Lei nº 14.754\" strike.\n - The remaining audit differences are in uncited documents (§6).\n\n### R3c — non-statutory LexML\n\n- **Declared URNs** (rebuild plan §3.2, D8). `scripts/lexml/nonstat_metadata.tsv` gives\n stem → authority, type, date, number, URN, with a `note` per row:\n\n | Source of the URN | Stems |\n |---|---:|\n | committed parse (2026-09-16), unchanged | 197 |\n | committed statutory parse (the 11 decrees/INs moved in `ce032e6`) | 11 |\n | corrected (§3.2 table: PGFN notes and pareceres → `procuradoria.geral.fazenda.nacional`; IN SRF 84 → `instrucao.normativa`; `sc_6007` and 3 new SCs `federal` → `…receita.federal`; AD Mesa CN 38 full date) | 20 |\n | inferred by the parser (new documents) | 15 |\n | declared like the other service pages (Diat → `…servico:2026;diat`) | 1 |\n\n All 244 URNs are distinct, no date is `0000`, and every `_<number>_<YYYYMMDD>` stem agrees with its\n URN.\n- **Upstream option.** `lexml_nonstat parse --urn` / `--metadata` (`d9624a7`) puts the declared\n identity into `Identificacao`, the annex URNs and the `-o` file names; the `*_source` fields say\n `declared`. Five tests were added.\n- **Linker round trip (§3.2 step 3) is not possible.** `linkertool` returns nothing for Notas,\n Pareceres, SCs, ADs, Súmulas or IN SRF titles; it only resolves federal laws and decrees (for\n \"Decreto nº 27.784, de 16 de fevereiro de 1950\" it gives the declared URN). So the vocabulary\n follows the conventions this corpus already uses.\n- **Parse** (`lexml/nao_articulados/PARSER_VERSION`): the same options as the committed parse\n (`--emitter=generico-aninhado --generation=proposed --referee=api --linker=…`) plus `--metadata`.\n Result: 244 documents + 1 annex, schema-valid (rigid and flexible), exit 0, 94 rendered flat.\n `/tmp/lexml_referee_cache` held only 41 of the earlier answers, so 513 referee calls were made\n (deepseek). 180 of the 213 documents also in the old parse are identical apart from the URN. The\n other 33 differ by one borderline section heading or a few `Remissao` links, with the text equal\n to within one word.\n- **Front-matter fix (found in R7, `e8c3d1e`).** The segmentation's coverage check failed on a\n dropped table in five treaty decrees, and the metadata prefix of 27 documents carried a wrong\n ementa:\n - the 9 treaty decrees: the ementa sits in a one-row layout table (empty first cell), and the\n preamble \"O PRESIDENTE DA REPÚBLICA…\" was taken as the ementa;\n - 18 Receita portal pages (IN SRF 23/67/84, 10 PN CST, ADs, Portaria MF 80/1979, SD 16/2012,\n AD PGFN 1/2014): \"Norma Federal - Publicado no DO em …\" was taken as the ementa.\n\n The parser now unwraps one-row tables among the first 12 blocks (the rule fires in exactly these 5\n documents), reads \"O PRESIDENTE DA REPÚBLICA\" as a preamble opener, and skips portal lines\n (\"Vide…\", \"Texto compilado\", \"Download…\", \"(Norma Federal -) Publicado no DO…\") before an\n unlabelled ementa. The re-parse with cached referee answers changed exactly those 27 files; the\n other 218 are byte-identical. The parser's suite fails the same 11 corpus-dependent tests as\n before the change (§6).\n- `scripts/dataset/nonstat_lexml_map.tsv` is now generated from the output\n (`scripts/lexml/nonstat_lexml_map.py`, match `declared-urn`).\n\n### R4 — fetcher canonical list\n\n`../br-taxqa-document-fetcher/scripts/fix_canonical_records.py` applies the reviewed\n`output_canonical/canonical_corrections_20261008.json`. 27 records changed: 25 now name the cited\nact, Parecer Cosit 30/2001 is `nonexistent_act`, and SCI Cosit 27/2008 is `not_found`. Each record\ngets `source: manual` and `correction: {date, was, reason}`, and `by_type/*.md` and `index.md` are\nregenerated. A second run is a no-op. Re-running `extract_canonical_names.py` would undo the\ncorrections; the note there says so.\n\n### R5 — dataset\n\n- `reference_overrides.json`: the 25 `not_in_corpus` entries are gone, because the acts now resolve\n `auto_exact` from the corrected list. Also removed: the now-redundant \"Convenção … Nações Unidas\"\n entry. Diat now maps to its document. Q313's Parecer Cosit 30 is dropped (fix 1). 37 `files` and\n 9 `drop` entries remain.\n- `build_v2_dataset.py`:\n - a canonical `correction.reason` becomes the `resolution_note`, and a `status` record resolves to\n no document. With this, fix 2 (Q249 → Nota 981/2015) comes from the canonical list, not from an\n override;\n - `*.pdf` sources are read;\n - guards: dead override (error), contradiction (error), redundant override and uncited file name\n (warnings), uncited documents (warning). The uncited-file-name rule differs from the plan: the 5\n service-page overrides are used by no question but are still needed, because every canonical\n file name must resolve;\n - new fields: `provisions[].matchable`, `article_ids_unmatchable` and `unmatchable_reasons`;\n - the fetcher's git commit is recorded in `build_report.json`.\n- **Expected deltas (plan §5): all met.** `not_in_corpus` 42 → 0; questions with an unresolved\n reference 37 → 0; dropped 7 → 9; Q179 unchanged; Q249/Q313/Q187 resolved or dropped; 458\n documents; `article_ids_missing` 28 → 13, all explained (`article_ids_missing_unexplained = []`).\n The 36 dataset tests pass. The final build ran on a clean tree (`7d88bd6`), against the R7 chunks:\n `cited_documents_without_chunks = []`.\n\n### R6 — segmentation code (caput plan C1–C5, C10, adapted as in the rebuild plan §4)\n\n| Item | Implementation |\n|---|---|\n| C1 | XSL param `caput_em_paragrafo` (`nao` default, `frase` = old X3b) |\n| C2 | `common.caminho_parts(n, caput=\"nenhum\"\\|\"frase\"\\|\"completo\")`; `split_oversize.py` uses `frase` explicitly (Q2: ART-part HEADs unchanged) |\n| C3 | `add_caput_variants.caput_variant(e, tipo, base_text)`. Called from step 6 (merge) rather than writing separate `<file>.caput.csv` files: it uses the element lookup step 6 already does, and **asserts that the base text equals prefix + caput-free Python text**. That is an XSL/Python parity check over every paragraph-family row of the corpus |\n| C4 | `segment_all.py --variants caput` (default), `--frozen`, `--frozen-lexml-rev`; new columns `variante`, `contexto_ids`; chunk ids `<stem>#<seq>` (base) and `<stem>#c<seq>` (caput, the same seq as its twin). `--chunk-id-source` was dropped, as the rebuild plan says |\n| C5 | `validate_segments.py`: structural checks on base rows; `variant_twins`, `base_no_caput` (the variant is the base plus one inserted segment), `diff_vs_frozen` (report only, rebuild plan §4) |\n| C6 | `strategies.py`: `(tipos, variantes)`; S2C, S4 |\n| C10 | worked target (base `art8_par2` = `Art. 8º § 2º O disposto…`), caput target with `frase`, parity with both settings on 4 fixtures, variant and filter tests: **45 pass** |\n\n**Environment:** the segmentation runs in `.venv` (Python 3.12). It lacked `lxml`/`saxonche`, so\n`scripts/segmentation/requirements.txt` was installed into it. The conda Python's `tokenizers`\n0.19 cannot read the Qwen3 `tokenizer.json`.\n\n### R7 — segmentation run\n\n```bash\n.venv/bin/python scripts/segmentation/segment_all.py --jobs 16 --overwrite --allow-count-change \\\n --variants caput --frozen <old chunks_all.csv.gz> --frozen-lexml-rev 0ce50c5 # 62 s\n```\n\n- Router A/B/C = 12 / 50 / 179 (was 12 / 50 / 181: two annexes of removed documents are gone).\n XSL: 276 files, 83,569 rows. 655 ART/DSP rows split into 1,746 parts. Loose: 697 rows. Non-statutory:\n 424 files, 3,486 rows.\n- `chunks_all.csv`: **118,766 rows** = 88,600 base + 30,166 caput. 243 grouping rows over 8,192\n tokens are listed in `groupings_over_limit.csv`.\n- **Validation OK** on all 14 checks.\n- **`diff_vs_frozen`:** for the 569 files whose LexML did not change since `0ce50c5`, **75,979 rows\n compared, 0 differ, 0 missing, 0 extra**. Base rows equal the frozen rows, and the caput rows equal\n the frozen paragraph-family texts. The caput plan's invariants (i) and (ii) therefore hold\n wherever the corpus did not change. 147 files changed, were added or were removed.\n- Per Tipo (base): PAR 21,813, INC 20,867, ART 20,662, CPT 8,209, ALI 4,938, TXT 3,497, SEC 2,128,\n CAP 1,863, DSP 1,519, ITE 1,305, SSC 714, TAB 686, TIT 328, LIV 45, SBT 21, PRT 5. The caput\n plan's 29,876 paragraph-family rows are now 30,166 (more documents and articles).\n\n### R8 — embeddings (`jua-4b-mixed`)\n\n`embed.py corpus` gained **`--extend`** (embed by text hash; rebuild plan §4, generalizing C9). The\nvectors of texts still in the input are copied from the finalized store into the shard store, so\nresume and assembly are unchanged. The store must match in model, revision, template, dimension and\nserver fingerprint. A fake-provider test covers it, and the 27 embedding tests pass.\n\n```bash\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --extend --dry-run\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --extend --resume\n```\n\n- 115,582 unique texts: **83,388 reused, 32,194 embedded** (5.95 M tokens, 504 requests, 0 retries,\n 5,182 tok/s, 19.9 replica-minutes, **≈ $0.27**), 1,180 old texts dropped. Vectors are\n [115,582 × 2,560] with norms OK. The endpoint was paused afterwards.\n- The old store is kept in `embeddings/jua-4b-mixed/corpus_prev_20260926/` (vectors gitignored,\n manifest versioned), so the old rankings can be regenerated.\n- **Queries were not re-embedded:** the question texts did not change, and `rag.py check` verifies\n them against `questions.jsonl`.\n\n### R9 — retrieval and evaluation\n\n- C7: `strategies.yaml` has `variantes` (default `[base]`), S2c and S4, and the new expected rows.\n `ragpipe.strategies.member_mask` (first listed variant per unit) is used both by the index and by\n the evaluation. The evaluation previously filtered by `Tipo` only, which would have counted caput\n rows as members of S2/S3. Chunk files without `variante` load as `base`. 24 RAG tests pass.\n\n```bash\nR=scripts/rag/rag.py\n.venv/bin/python $R check --embedding jua-4b-mixed # OK\n.venv/bin/python $R retrieve --embedding jua-4b-mixed --force # 20 s\n.venv/bin/python $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf \\\n --eval-id v2c_either_containment_skip --comparisons S1:S2,S2:S3,S2:S2c,S3:S4,S1:S2c # 32 s\n```\n\n- `check`: 0 references not in the corpus, 0 documents without chunks.\n- Texts per strategy: S1 26,323; S2 83,330; S3 88,434; S2c 80,325; S4 85,429. Without the caput\n sentence fewer paragraph chunks share a text, so S2 has 3,000 more distinct texts than S2c.\n- The old evaluation `eval/either_containment_skip/` (report, metrics) is untouched. The rankings in\n `S1/S2/S3/` are now the new ones (`--force` replaces only the files it writes).\n\n---\n\n## 4. Retrieval results (`runs/retrieval/jua-4b-mixed/irpf/eval/v2c_either_containment_skip/report.md`)\n\nSettings as in the first IR test: annex rule `either`, containment de-duplication, overflow `skip`,\nQwen3-token budgets, paired bootstrap (10,000 resamples, seed 13) and permutation tests. Gold: 1,725\ndocument, 1,958 article and 2,230 provision items. Unreachable: 13 articles (the treaty articles)\nand 57 provisions, the same for every strategy.\n\n### 4.1 Recall by budget (all resolved gold)\n\n| Level | Strategy | 1k | 2k | 4k | 8k | 16k |\n|---|---|---:|---:|---:|---:|---:|\n| document | S1 | 0.376 | 0.482 | 0.604 | 0.717 | 0.803 |\n| | S2 | **0.488** | **0.575** | **0.665** | **0.763** | **0.833** |\n| | S3 | 0.479 | 0.565 | 0.652 | 0.745 | 0.815 |\n| | S2c | 0.444 | 0.537 | 0.631 | 0.727 | 0.805 |\n| | S4 | 0.440 | 0.534 | 0.627 | 0.715 | 0.791 |\n| article | S1 | 0.169 | 0.265 | 0.379 | 0.479 | 0.566 |\n| | S2 | **0.307** | **0.387** | **0.473** | **0.567** | 0.650 |\n| | S3 | 0.302 | 0.379 | 0.464 | 0.566 | **0.659** |\n| | S2c | 0.273 | 0.346 | 0.428 | 0.523 | 0.616 |\n| | S4 | 0.269 | 0.348 | 0.426 | 0.525 | 0.624 |\n| provision | S1 | 0.157 | 0.240 | 0.347 | 0.454 | 0.532 |\n| | S2 | 0.187 | **0.261** | **0.361** | 0.467 | 0.565 |\n| | S3 | **0.192** | 0.260 | **0.361** | **0.482** | **0.581** |\n| | S2c | 0.164 | 0.226 | 0.321 | 0.433 | 0.538 |\n| | S4 | 0.169 | 0.231 | 0.334 | 0.443 | 0.555 |\n\nSlices at 4k (provision level): sub-article gold (366 questions) S1 0.313 / S2 **0.424** / S3 0.409 /\nS2c 0.370 / S4 0.367; whole-article gold (429) S1 **0.337** / S2 0.266 / S3 0.270 / S2c 0.237 /\nS4 0.259. Non-statutory provisions (15 questions) cannot be hit by any strategy: their oracle is 0,\nbecause those documents have no article ids.\n\n### 4.2 Paired comparisons (recall, budget view; difference [95 % CI], permutation p)\n\n| Pair | Level | 1k | 4k | 16k |\n|---|---|---|---|---|\n| S2 − S1 | article | +0.138 [+0.112, +0.165] p<0.001 | +0.094 [+0.072, +0.117] p<0.001 | +0.084 [+0.064, +0.105] p<0.001 |\n| S2 − S1 | provision | +0.031 [+0.008, +0.053] p=0.007 | +0.014 [−0.012, +0.039] p=0.29 | +0.033 [+0.015, +0.051] p<0.001 |\n| S3 − S2 | provision | +0.004 p=0.25 | −0.000 p=0.95 | +0.016 [+0.002, +0.030] p=0.02 |\n| **S2c − S2** | article | −0.034 [−0.054, −0.015] p<0.001 | −0.045 [−0.062, −0.028] p<0.001 | −0.034 [−0.047, −0.022] p<0.001 |\n| **S2c − S2** | provision | −0.023 [−0.038, −0.009] p<0.001 | −0.040 [−0.056, −0.024] p<0.001 | −0.026 [−0.039, −0.015] p<0.001 |\n| **S4 − S3** | article | −0.033 [−0.053, −0.014] p=0.001 | −0.038 [−0.055, −0.022] p<0.001 | −0.035 [−0.049, −0.022] p<0.001 |\n| **S4 − S3** | provision | −0.023 [−0.037, −0.008] p=0.002 | −0.027 [−0.040, −0.012] p<0.001 | −0.026 [−0.038, −0.015] p<0.001 |\n| S2c − S1 | provision | +0.007 p=0.52 | −0.026 [−0.050, −0.003] p=0.03 | +0.007 p=0.47 |\n\nS2c is also worse than S2 at the document level (−0.044 at 1k, p<0.001). S3 − S2 trades a little\ndocument recall (−0.013 at 4k) for higher context precision at 8k/16k. All rows are in\n`comparisons.csv`.\n\n### 4.3 Reading\n\n- **Sub-article units help** (S2 vs S1): +9–14 points of article recall, and +11 points of\n provision recall on sub-article gold at 4k. On the old corpus the S2 tested was really S2c: its\n provision recall at 4k was *below* S1 (0.327 vs 0.358). The caput-free S2 is the first variant\n above S1 at the provision level.\n- **The caput sentence hurts** (S2c vs S2, S4 vs S3): every level and budget, about 2–5 points,\n all significant. One likely cause: paragraph chunks of one article all start with the same caput\n sentence, so their vectors resemble each other and the article's caput chunk. That crowds the\n token budget with near-duplicates of one article (S2c has 3,005 fewer distinct texts than S2, and\n its contexts hold fewer texts per budget). It also dilutes what is specific to each paragraph. The\n full-caput S5 (caput plan Q3) is therefore **not worth building** unless a generation-level test\n shows the opposite.\n- **Groupings** (S3 vs S2) remain about neutral for recall. They are better for context precision\n at large budgets.\n- These are retrieval scores on one embedding model. The answer-level (nugget) evaluation is still\n to come.\n- **Old vs new runs are not directly comparable:** the corpus changed (22 documents replaced,\n 11 re-routed, missing articles restored, URNs and ementas fixed) and the gold changed (42\n references resolved, 2 dropped).\n\n---\n\n## 5. Findings and deviations from the plans\n\n1. **PDF prototype missing** (R1): rewritten as above; the plan's checks pass.\n2. **New cause-2a case: MP 2.189-49** (R3a), fixed with a reusable tool. D5's rule (\"each article\n once, in its 2023 wording\") applied.\n3. **Linker defect, unchanged:** for \"art. 19, caput, da Lei nº 9.096…\" `linkertool` returns\n `…;9096!cpt` and loses the article. The committed corpus already had 227 such links; the new one\n has 234. Four unchanged `.docx` (Decreto 9.580 annex 1, Lei 10.833, Lei 8.242 annex 1, Lei 9.504)\n now get these weaker links where the committed XML had better ones, probably from a linker built\n elsewhere (old logs point at `/work/unicamp/…`). The current binary dates from 2025-10-31. Chunk\n text is unaffected. Details in the statutory parser's `work_history` note.\n4. **Non-statutory front matter** (R3c fix): 27 wrong ementas corrected upstream. Without this fix\n the coverage check failed, and every chunk of those documents carried the preamble or a DOU\n publication line as its \"ementa\".\n5. **Referee cache was volatile:** `/tmp/lexml_referee_cache` had lost most of the 2026-09-16 run's\n answers, so 513 new API answers were bought and section headings differ slightly in 33\n documents. The cache now holds 554 answers; it is still under `/tmp`.\n6. **Dead-override rule relaxed** (R5, see above).\n7. **C3 lives inside step 6** rather than writing per-file `.caput.csv` (R6); same output, with a\n built-in parity assertion.\n8. **`diff_vs_frozen` passes with zero differences** (R7), so the new code changes nothing that the\n caput plan did not intend.\n9. **Retrieval directory reused** with `--force` (R9). The old evaluation stays readable, but its\n rankings were replaced; they can be regenerated from `corpus_prev_20260926`.\n10. **Authority vocabulary SRF vs RFB:** the statutory side writes\n `…secretaria.receita.federal.brasil` for acts after 2007-05-02, while the non-statutory side\n writes `…secretaria.receita.federal` for every Receita act (SCs of 2014–2023 included). This was\n kept as is (the plan only fixed inconsistent groups), but two documents of one authority can\n carry different spellings.\n\n---\n\n## 6. Open points (for the user)\n\n| # | Point | Suggestion |\n|---|---|---|\n| O1 | **Treaty articles (2f, D7):** 11 cited articles (13 gold article items) of 9 treaty decrees are unmatchable; the treaty texts are missing or numbered `ARTIGO I…`. Listed in `scripts/lexml/unmatchable_articles.tsv` | Fetch the treaty texts (DOU/Senado), then map `ARTIGO N` blocks by label |\n| O2 | **Uncited documents:** `in_rfb_1911_20191011` (the old wrong match for IN RFB 1.997) and `in_rfb_1505_20141031` (cited only by Q081's dropped hallucinated reference). Also uncited, as before: the 5 service pages, `lei_3071_19160101`, `lei_5869_19730111`, `par_cosit_26_20000629`, `sc_cosit_153_20140611` | Remove the first two, like the D3 removals? |\n| O3 | **Uncited documents with parse gaps** (audit): `decreto_7030_20091214` (85 articles in the `.docx`, 3 in the XML; the Vienna Convention, numbered \"Artigo N\"), `mp_2228-1_20010906` (arts. 13, 31, 51, 73 missing; all wordings struck), duplicate ids in `decreto_70951`, `decreto_71733`, `lei_12715`, `decreto_lei_58`, `lei_3071` | They affect only distractor chunks; fix if they are kept in the corpus |\n| O4 | **25 cited provision fragments not in the XML** (e.g. `lei_9250` art. 10 inc. X, `lei_6015` art. 167 I items 7/24/25, `lei_12350` art. 45 § 3º, `lei_11033` art. 3º p.u.); marked `matchable: false` | Check each against the source (revoked text? citation error?) |\n| O5 | **11 tests of `lexml_parser_non_statutory` fail** (with and without these changes): they pin the 2026-09 corpus (233 documents, flatness counts, referee fixtures) | Update their expected values or freeze a corpus copy for them |\n| O6 | **Linker defect** (§5.3) | Fix in `../lexml-linker`, then re-parse |\n| O7 | **Referee cache** in `/tmp` | Copy `/tmp/lexml_referee_cache` into the parser repo's fixtures so the parse can be reproduced without the API |\n| O8 | **Other embedding models** (`qwen3-emb-4b`, `inf-retriever-v1`): no vectors yet | Embed the new chunk set directly (no `--extend` needed) |\n| O9 | **S5** (full caput) | Not recommended after §4.3 |\n| O10 | Lei 13.043 heading typos (\"D a …\", \"REPÚBLIC A\") and the art. 22 § 1º wording (rebuild plan §3.1.1) | Still to confirm or fix |\n\n---\n\n## 7. Reproduction (from `original/`)\n\n```bash\n# R1\npython3 scripts/lexml/pdf_to_text.py original/nao_articulados/*.pdf -o lexml/nao_articulados/_text/\n# R3b (jar: ../lexml-parser-projeto-lei, mvn -Ponejar package -DskipTests at ebf6567)\npython3 ../lexml-parser-projeto-lei/scripts/batch_parse.py --no-justificativa \\\n --linker /usr/local/bin/linkertool original/articulados lexml/articulados\npython3 scripts/lexml/audit_article_coverage.py # gate\n# R3c (from ../lexml_parser_non_statutory, e8c3d1e; see lexml/nao_articulados/PARSER_VERSION)\nPYTHONPATH=src LC_ALL=C.UTF-8 python3 -m lexml_nonstat parse --emitter=generico-aninhado \\\n --generation=proposed --referee=api --referee-cache=/tmp/lexml_referee_cache \\\n --linker=/usr/local/bin/linkertool --linker-cache=.cache/linker \\\n --metadata ../br-taxqa-r_v2.0/scripts/lexml/nonstat_metadata.tsv \\\n -o ../br-taxqa-r_v2.0/lexml/nao_articulados \\\n ../br-taxqa-r_v2.0/original/nao_articulados/*.docx ../br-taxqa-r_v2.0/lexml/nao_articulados/_text/*.txt\npython3 scripts/lexml/nonstat_lexml_map.py\n# R4 (from ../br-taxqa-document-fetcher)\npython3 scripts/fix_canonical_records.py output_canonical/canonical_corrections_20261008.json\n# R7, R5\n.venv/bin/python scripts/segmentation/segment_all.py --jobs 16 --overwrite --variants caput\npython3 scripts/dataset/build_v2_dataset.py\n# R8, R9: §3 above\n```\n","20261008_133726_corpus_rebuild_review_answers.md":"# Corpus Rebuild Results: Answers to the Review Questions (levels, budgets, open points, metric handling, chunk samples)\n\n**Generated:** 2026-10-08 13:37:26 (local time, from `date +%Y%m%d_%H%M%S`)\n**About:** `docs/20261008_010441_corpus_rebuild_results.md` (**the results note**). This note answers the\nuser's questions on its §4.1 and §6 and on the evaluation, and holds 20 chunk samples for review.\nNothing in the corpus, the dataset or the runs was changed while writing it.\n**Sources:** `dataset/*.jsonl` and `build_report.json`; `segmented/chunks_all.csv.gz` (SHA-256 `d1b9cf7e…`);\n`runs/retrieval/jua-4b-mixed/irpf/eval/v2c_either_containment_skip/{metrics,reachability}.csv`;\n`scripts/rag/ragpipe/{relevance,context,evaluation}.py`; `scripts/lexml/audit_article_coverage.py` (re-run);\nthe `lexml/` XML and the `original/` `.docx` files; the test suite of `../lexml_parser_non_statutory` (re-run).\n\n---\n\n## 0. Summary\n\n**Answers in brief**\n\n- **Levels (§1.1).** *Document* = any chunk of the cited act. *Article* = any chunk of the cited\n article. *Provision* = the exact unit cited in the gold, e.g. `art1_cpt_inc10` for \"art. 1º, inciso X\".\n It is not \"up to the article\". A chunk scores a full hit when it holds the whole unit: the unit\n itself, an ancestor (the article chunk included), a grouping chunk that contains it, or every part\n of a split article.\n- **1k–16k (§1.2)** are **context sizes in Qwen3 tokens**. They are not a number of chunks and do\n not come from sampling. For every question, the ranked texts are added to the context in rank order\n until the budget is full. Recall@B is the share of the question's gold items hit by that context.\n All questions with gold count (596 / 553 / 558 per level).\n- **Missing fragments (§3.1)** stay in the denominator of the headline numbers (`gold=all`) and are\n left out of `gold=reachable`. They are the same items for every strategy. The provision-level ceiling is 0.965,\n and the gap between the two numbers is 0.3–2 points. The S1/S2/S3/S2c/S4 comparisons do not change\n direction.\n\n**New findings (not in the results note)**\n\n| # | Finding | Effect | Section |\n|---|---|---|---|\n| N1 | Reference **144-05** is wrong. \"Convenção de Viena\" in Q144 is the **diplomatic-relations** convention (Decreto 56.435, already 144-01), not the law-of-treaties convention (Decreto 7.030) | One false document-level gold item; once dropped, `decreto_7030` is uncited | §2.1 |\n| N2 | Most of the O2 \"uncited\" documents **are cited in the answer texts**. The 5 service pages are named in Q029, and Parecer Cosit 26/2000 and SC Cosit 153/2014 are in Q576's citation block. The v1 references missed them | Missing gold, so these documents should get references rather than be removed | §2.1 |\n| N3 | **435 article chunks hold only their label** (\"Art. 34.\"), in 14 treaty-type files. The article body was parsed outside the `Artigo` element and became loose `TXT`/`DSP` chunks. **5 cited articles** fall on such empty chunks | Those 5 article items count as \"reachable\", but their article chunk has no content | §2.3, §3.1 |\n| N4 | The **RIR/2018 annex has broken groupings**. The parser read the headings \"Livro diário\" and \"Livro de Apuração do Lucro Real\" as LIVROs, so 404 Livro II articles sit under two fake LIVROs. LIVRO III holds 1 article, and its other ≈ 210 articles hang outside any LIVRO. The ids `liv3` and `liv4` are duplicated | Only S3/S4 grouping chunks and the `agrupadores_*` metadata. Article and sub-article chunk texts are correct | §3.2 (A9) |\n| N5 | 10 of the 25 missing fragments are **fixable**: wrong numbering in the source, renumbering by a later law, a citation into amendment text, and citation errors | They would become reachable | §2.3 |\n| N6 | `decreto_7030_20091214` (the treaty convention) has **3 chunks / 411 tokens**: the convention's 85 articles are not in the chunks at all | Only matters if it stays in the corpus | §2.2 |\n| N7 | Isolated parse and source defects seen in the samples: Lei 6.766 art. 4 \"III-A\" merged into inciso III; SC Cosit 194/2015 has words glued together in the `.docx` itself; SC Cosit 140/2015 has a layout table that comes out as fragments | Local to those chunks | §3.2 |\n\n---\n\n## 1. Item 4.1 of the results note\n\n### 1.1 Document, article and provision levels\n\nThe gold comes from `dataset/references.jsonl`. Each resolved reference gives a document, its\n`article_ids` and its `provisions[]`. The provisions are parsed from the citation text\n(`docs/20260927_213420_reference_provisions_from_citation_text.md`). Example, reference 001-03, \"Lei nº 11.482, de 31 de maio de\n2007, art. 1º, inciso X e parágrafo único\":\n\n| Level | Gold items of 001-03 | Items in the whole dataset (questions) |\n|---|---|---:|\n| document | `lei_11482_20070531` | 1,725 (596) |\n| article | `(lei_11482_20070531, art1)` | 1,958 (553) |\n| provision | `(…, art1_cpt_inc10)` and `(…, art1_par1u)` | 2,230 (558) |\n\nWhen a citation names only the article (\"art. 25\"), the provision is the whole article\n(`fragment_id = art25`). The results note's slices \"whole-article gold\" (429 questions) and\n\"sub-article gold\" (366) split on this.\n\n**Hit rules** (`ragpipe/relevance.py`, G1–G5):\n\n| Level | A retrieved chunk hits the item when… | Example for gold `art1_cpt_inc10` |\n|---|---|---|\n| document | it belongs to the document's main file or to one of its annexes | any chunk of Lei 11.482 |\n| article | it belongs to article N (the `ART` chunk, any part of a split article, the caput, any §, inciso or alínea), or it is a grouping chunk (`CAP`, `SEC`…) whose interval contains the article. Annex rule `either`: article N of the main file or of an annex | the `INC` chunk of inciso V also hits `art1` |\n| provision, **full** | its `cobre_ids` holds the unit **or an ancestor of it**, or it is a grouping chunk that contains the unit, or **all** parts of a split article that hold the unit are in the context | `art1_cpt_inc10` (INC), `art1_cpt` (CPT), `art1` (ART), the chapter, but not `art1_cpt_inc9` |\n| provision, partial | it holds only part of the unit (a descendant) | gold `art1`, retrieved `art1_par1u` |\n\n**Is the provision level \"the match up to the article component, as described in the gold\"?** No.\nThe article level is the match up to the article. The provision level matches the exact component\nthe gold cites: caput, §, inciso, alínea or item. Recall counts only **full** hits. Partial hits are\nreported separately as `partial_recall`. Two consequences explain the slices in the results note:\n\n- **Sub-article gold:** an S1 `ART` chunk that contains inciso X is a full hit, but it costs the\n whole article's tokens. S2 can fill the budget with the inciso alone. Result at 4k: S2 0.424 vs\n S1 0.313.\n- **Whole-article gold:** S2's paragraph and inciso chunks are only partial hits. Only the `ART`\n chunk, all of a split article's parts, or a grouping chunk counts as full. Result at 4k: S1 **0.337**\n vs S2 0.266.\n\n### 1.2 What the 1k–16k columns are\n\nThey are **token budgets for the retrieved context** (`--budgets 1000,2000,4000,8000,16000`). Tokens\nare counted with the Qwen3 tokenizer on the full chunk text, metadata prefix included\n(`n_tokens_qwen3`). For each question and strategy (`ragpipe/context.select`):\n\n1. dense retrieval ranks the strategy's texts by cosine similarity, and the top 1,000 are stored;\n2. the context is filled in rank order. A text whose chunk lies inside an already selected chunk of\n the same file is skipped (containment de-duplication: a child after its parent adds nothing). A text\n that does not fit in the remaining budget is skipped and filling continues (`overflow=skip`).\n Filling stops when no remaining text fits;\n3. recall@B = gold items hit by the selected texts / gold items of the question, averaged over the\n questions.\n\n**There is no sampling.** Every question with gold at the level is used (596 document / 553 article /\n558 provision), with every text of its ranking. The budget view replaces \"top-k\" because chunk sizes\ndiffer a lot by type. Median Qwen3 tokens are ART 194, PAR 150, INC 169, CAP 822 and TIT 1,556, so\ntop-10 would mean very different context sizes in S1 and S3. A budget is also what the generator\nwill receive (Phase 2 uses the same `select`).\n\nAverage number of texts per context (document level, `gold=all`):\n\n| Budget | S1 | S2 | S3 | S2c | S4 |\n|---|---:|---:|---:|---:|---:|\n| 1k | 3.8 | 4.5 | 4.4 | 4.3 | 4.2 |\n| 2k | 6.3 | 7.8 | 7.4 | 7.4 | 7.1 |\n| 4k | 11.0 | 13.6 | 12.6 | 13.1 | 12.1 |\n| 8k | 20.9 | 25.9 | 22.4 | 24.7 | 21.7 |\n| 16k | 41.0 | 50.4 | 40.6 | 48.0 | 39.3 |\n\nThe average context fills the budget to within about 17 tokens: 3,983 of 4,000 at 4k for every strategy.\n\n---\n\n## 2. Item 6 of the results note: open points\n\n### 2.1 O2: uncited documents. Can they simply be removed?\n\n\"Uncited\" means that no resolved reference points at the document (`build_report.json →\ndocuments_not_cited`). A search of the 715 answers and citation lists shows three different situations:\n\n| Document | What it is | Chunks / tokens | Where the dataset mentions it | Recommendation |\n|---|---|---:|---|---|\n| `in_rfb_1911_20191011` | IN RFB 1.911/2019 (PIS/Pasep and Cofins regulation, 60 annexes) | **4,528 / 1.93 M** | Nowhere. It was v1's wrong match for IN RFB 1.997/2019, and that reference (Q025) is now dropped | **Remove.** It is the largest distractor in the corpus (≈ 5 % of the S3 rows) and was never cited |\n| `in_rfb_1505_20141031` | IN RFB 1.505/2014 (amends IN RFB 971/2009, social-security contributions) | 11 / 5,244 | Only in Q081's dropped embedded reference (\"IN RFB 1.505, de 05 de agosto de 2014\"). Q081's answer cites nothing | **Remove** |\n| 5 service pages: `declaracao_benficios_fiscais_DBF`, `…_DIMOB`, `…_DMED`, `…_DOI`, `sistema_…_CARNE_LEAO` | Receita portal pages about the DBF, Dimob, Dmed and DOI returns and the Carnê-Leão | 21 + 6 + 7 + 6 + 5 | **Q029's answer** lists them as sources of the pre-filled return (items II–VII), and they are in its `embedded_references_text`. The v1.1 references of Q029 have only IN 2.178 and IN 1.888. (The DIRF page in the same list is in the corpus and cited by Q207.) | **Keep and add references:** 5 embedded references for Q029, document level only. Their overrides already exist in `reference_overrides.json` and are the \"override for a file name no question cites\" warnings |\n| `par_cosit_26_20000629`, `sc_cosit_153_20140611` | Parecer Cosit 26/2000 and SC Cosit 153/2014, both on the assignment of court-ordered payments (*precatórios*) | 33 / 9,447 and 13 / 9,514 | **Q576's citation block**: \"…; Parecer Cosit nº 26, de 29 de junho de 2000; Solução de Consulta Cosit nº 153, de 11 de junho de 2014; e Solução de Consulta Cosit nº 674, de 27 de dezembro de 2017)\". Q576 has `references_text = []`. All 8 of its references are `embedded`, and the list misses these two and SC 674 | **Keep and add references:** re-extract Q576's explicit references from its citation block (9 acts, including SC 674, which Q252 already cites) |\n| `lei_3071_19160101` | Código Civil de 1916 | 3,083 / 565 k | Nowhere. It came from the fetcher's `fetched_documents` and was already flagged as \"harmless extra\" in `docs/20260913_143905_*`. Its XML has 25 duplicate article ids | **Remove**, or keep as a distractor and fix the duplicate ids |\n| `lei_5869_19730111` | CPC de 1973 | 3,735 / 766 k | Nowhere in the dataset (the answers cite the CPC of 2015, Lei 13.105). Lei 9.250 art. 8 § 3 mentions it in its text | **Remove**, or keep as a distractor |\n| `decreto_7030_20091214` (new, N1) | Convention on the Law of Treaties | 3 / 411 | Only through the wrong reference 144-05 | **Drop 144-05**, then remove the document |\n\nRemoving documents changes only the chunk set (`segment_all.py` without them). Every remaining text\nalready has a vector, so no new embedding is needed. Rankings and metrics must be regenerated, and the\ncorpus counts in the notes change.\n\n### 2.2 O3: \"uncited documents with parse gaps\"\n\nThe results note calls these documents uncited. That is not right: **each is cited at the document\nlevel by one question**. What no question cites are their articles, so the gaps cannot affect article\nor provision gold. They can affect document-level retrieval when the missing text is the relevant part.\n\n| Document (citing reference) | Audit result | Detail |\n|---|---|---|\n| `decreto_7030_20091214` (144-05, wrong, see N1) | 85 articles in the `.docx`, 3 in the XML | The convention numbers its articles \"Artigo N\", which the statutory parser does not read, and its text does not reach the chunks (3 chunks, 411 tokens) |\n| `mp_2228-1_20010906` (442-07) | arts. 13, 31, 51, 73 absent; `art33` duplicated in annex 1 | All wordings of these 4 articles are struck through on Planalto, so the parser dropped them (rebuild results note, R3a: superseded text, left alone) |\n| `decreto_70951_19720809` (302-01) | 35 article labels in the `.docx`, 77 ids in the XML; `art15`, `art21`, `art23`, `art32`, `art35`, `art40`, `art48`, `art79` duplicated | More ids than labels: quoted or annexed articles were parsed as top-level articles |\n| `decreto_71733_19730118` (163-02) | `art22-15` absent; `art22`, `art23`, `art27` duplicated | Article-label variants mis-parsed |\n| `lei_12715_20120917` (442-13) | `art69`…`art78` duplicated | Articles of quoted amendment text read as top level (unclosed quote, cause 2c) |\n| `decreto_lei_58_19371210` (256-04) | `art1`…`art4` duplicated | Same pattern |\n| `decreto_lei_1535_19770413` (177-11), `lei_7290_19841219` (191-01) | `art1-15` / `art2-1` absent | One \"Art. N-A\" label each, not recognized |\n\nDuplicate ids lead to `id_ambiguo = 1` chunks. The evaluation flags matches that exist only through\nsuch chunks (G4), and there are **0** for the current gold (`reachability.csv`).\n\n### 2.3 O4: the 25 cited provision fragments missing from the XML\n\n`build_report.json → validation.fragment_ids_missing` lists 25 (reference, fragment) pairs. They\nare marked `matchable: false` and their `lexml_file` is empty. They fall into three groups.\n\n**(a) Treaty articles absent from the XML: 13 pairs, 11 articles of 9 decrees** (O1;\n`scripts/lexml/unmatchable_articles.tsv`)\n\n| Reference | Document | Cited | Why absent |\n|---|---|---|---|\n| 149-01, 150-12 | `decreto_27784_19500216` | art. V | Non-statutory treaty decree; the treaty text is not in the `.docx` |\n| 149-03, 150-05 | `decreto_59308_19660923` | art. V | Non-statutory treaty decree |\n| 152-01 | `decreto_57942_19660310` | art. 10 \"b\" | The treaty text has no article markers the parser reads (0 labels in the `.docx`) |\n| 153-01 | `decreto_57942_19660310` | art. 1º | Same |\n| 153-04 | `decreto_361_19911210` | art. 13 | The `.docx` holds only the 2-article promulgating decree |\n| 154-01 | `decreto_86084_19810608` | art. IX, item 2 | Non-statutory treaty decree |\n| 155-01 | `decreto_87563_19820913` | art. XV \"b\" | The treaty numbers its articles \"ARTIGO I…XXV\" |\n| 157-02 | `decreto_8289_20140725` | art. XIII, item 2 | Annex 1 numbers its articles \"Artigo I…XIV\" |\n| 158-02 (×2) | `decreto_85801_19810310` | arts. XII and VI | Non-statutory treaty decree; the treaty text is absent |\n| 159-01 | `decreto_93153_19860822` | art. VII | Same |\n\nFix (O1): fetch the treaty texts and map their \"ARTIGO N\" blocks by label. The non-statutory ones\nwould need article-level ids in a `DocumentoGenerico`, which the current gold matcher does not support.\n\n**(b) The article exists but is empty: 2 pairs** (new, N3)\n\n| Reference | Document | Cited | What the XML has |\n|---|---|---|---|\n| 142-03 | `decreto_56435_19650608` (Vienna Convention on Diplomatic Relations) | art. 34 \"d\" | `<Artigo id=\"art34\">` with an empty `Caput`. The text \"O agente diplomático gozará de isenção…\" and alíneas a)–f) come **after** `</Artigo>` and became chunk `#188` (TXT) plus loose `ALI`/`DSP` chunks without `artigo_id` |\n| 157-01 | `decreto_5128_20040706.anexo1` (OEI seat agreement) | art. 21 \"d\" | Same: an empty `art21`, and alíneas `ali1…` as siblings after it |\n\nCause: the source has \"Artigo 34\" (or \"ARTIGO 21\") on its own line, followed by unnumbered text. The\nparser opens an `Artigo` from the heading line but does not attach the following paragraphs to it.\nArticles whose text starts with \"1.\" work, because they become numbered items (e.g. art. 37, cited by\nQ144, is complete). Corpus-wide there are **435 label-only `ART` chunks** in 14 files:\n`decreto_67542_19701112` (149), `decreto_50656_19610524` (64), `decreto_61078_19670726` (39),\n`decreto_5128…anexo1` (35), `decreto_56435` (28), `decreto_57784_19660211` (26), `decreto_75102_19741220` (25),\n`decreto_9358_20180430.anexo1` (24), `decreto_8624_20151229.anexo1` (21), `decreto_85306_19801030` (9),\n`decreto_legislativo_92_19751105.anexo1` (9), `decreto_9358….anexo3` (4), `decreto_52288_19630724` (1),\n`lei_12431_20110624` (1). **Five cited article items** point at an empty `ART` chunk: 142-03\n(56435 art34), 151-01 (50656 art47), 151-02 (57784 art15), 153-02 (67542 art141), 157-01 (5128\nannex art21). Fix: a statutory-parser rule that attaches the paragraphs after a bare \"Artigo N\"\nheading to that article, then re-parse these 14 files.\n\n**(c) Statutory citations with a cause that can be fixed: 10 pairs**\n\n| Reference | Cited | What the source says | Diagnosis | Fix |\n|---|---|---|---|---|\n| 018-01 | Lei 9.250, art. 10, **inciso X** | Art. 10 ends at inciso IX, \"R$ 16.754,34 … a partir do ano-calendário de 2015\". The answer quotes this amount (\"limitado a R$ 16.754,34\") | Citation error in the P&R (IX), unless a later law added an inciso X that this `.docx` lacks. Check Planalto before deciding | Map to `art10_cpt_inc9` (override) or refresh the `.docx` |\n| 093-02, 093-06 | Lei 6.015, art. 167, I, **items 24 and 25** | The `.docx` (Câmara compilation) letters the items a)…; the official text numbers them 1)…. The parse has `art167_cpt_inc1_ali24` = \"x) das sentenças que nos inventários, arrolamentos e partilhas, adjudicarem bens de raiz…\" and `ali25` = \"y) dos atos de entrega de legados de imóveis, dos formais de partilha…\" | Only the numbering differs; the content matches Q093 (inheritance) | Map `ite24`→`ali24` and `ite25`→`ali25` |\n| 209-01 | Lei 6.015, art. 167, I, **item 7** | `ali7` = \"g) do usufruto e do uso sobre imóveis…\" | Same (Q209 is about usufruct) | Map `ite7`→`ali7` |\n| 460-03 | IN RFB 2.178, art. 11, **§ 2º, inciso II** | § 2º (trusts) has no incisos. § 3º II = \"bens móveis e direitos cujo valor unitário de aquisição seja inferior a R$ 5.000,00\" | Citation error in the P&R: the answer's threshold for crypto-assets (\"igual ou superior a R$ 5.000,00\") is § 3º II | Map to `art11_par3_inc2` |\n| 683-02 | Lei 12.350, art. 45, **§ 3º** | Art. 45 rewrites art. 8 of Lei 9.959; the § 3º is inside the quoted new wording (`art45_cpt_alt1`). The same question also cites Lei 9.959 art. 8 § 3º directly (683-01, matchable) | The citation points into amendment text, which has no § id of its own | Map to `art45` (whole article) |\n| 708-01, 708-11 | Lei 11.033, art. 3º, **parágrafo único** | Lei 14.754/2023 turned the parágrafo único into § 1º from 2024-01-01. The `.docx` has the new numbering: `art3_par1` \"(Parágrafo único acrescido pela Lei nº 11.196… e transformado em § 1º pela Lei nº 14.754…)\" | Renumbering; the P&R uses the 2023 numbering | Map to `art3_par1` |\n\nAll 10 can be fixed with a provision-level override in `reference_overrides.json`. The `build_v2_dataset.py`\noverride format supports files and drops today, not provisions, so a small extension is needed.\n\n### 2.4 O5: the 11 failing tests of `lexml_parser_non_statutory`\n\nRe-run on `e8c3d1e` (`PYTHONPATH=src python3 -m pytest -q`): **11 failed, 6,196 passed, 4 skipped**.\nAll 11 are `requires_corpus` tests. They read `../br-taxqa-r_v2.0/original/nao_articulados/` and the\nreferee cache, and assert numbers measured on the September corpus (233 `.docx`):\n\n| Test | Expected | Measured | What changed |\n|---|---:|---:|---|\n| `test_flatness_causes::test_the_corpus_flat_count` | 233 | 232 | Number of `.docx` documents (the folder now has 232 `.docx` + 12 PDFs) |\n| `…::test_the_corpus_cause_partition` | partition incl. `body_span: 11` | `…sections: 8` | Flatness causes of the new document set |\n| `…::test_truncation_is_visible_in_span_coverage` | 82 | 89 | Same |\n| `…::test_ad_pgfn_is_flat_but_proposes_nothing` | 15 | 16 | Same |\n| `test_profile_solucao_consulta::test_the_genre_selects_its_own_profile` | 127 | 114 | Fewer SC `.docx` files (12 SCs are now PDFs) |\n| `…::test_sc_cosit_flatness_falls` | 109 | 97 | Same |\n| `test_referee_economics::test_the_cache_answers_almost_every_question` | 681 | 554 | `/tmp/lexml_referee_cache` lost answers (results note §5.5) |\n| `…::test_the_misses_are_all_abstentions_that_change_nothing` | 10 | 14 | Same |\n| `…::test_the_overrides_reproduce_the_plans_table` | plan's table | 31 `own` headings | Same |\n| `…::test_the_referee_now_moves_flatness_86_to_83` | 86 | 94 | Rules-only baseline on the new set |\n| `…::test_the_heading_overrides_are_not_rule_learnable` | ≥ 30 | 26 | Cache contents |\n\nNone of them is a parser regression: they pin a corpus snapshot. Options: (a) freeze the 233-document\nset and the 681-answer cache as test data outside `/tmp` (this also fixes O7); (b) re-measure and\nupdate the constants. (a) is better, because these tests document a past measurement.\n\n### 2.5 O6: the linker defect\n\nFor \"art. 19, caput, da Lei nº 9.096…\" `/usr/local/bin/linkertool` (built 2025-10-31) returns\n`urn:lex:br:federal:lei:1995-09-19;9096!cpt`. The article is lost (`!art19_cpt` expected).\nReproduce with:\n\n```bash\necho 'O art. 19, caput, da Lei nº 9.096, de 19 de setembro de 1995 - Lei dos Partidos' \\\n | LC_ALL=C.UTF-8 linkertool --contexto=federal\n```\n\nThe new statutory corpus has 234 such `…!cpt…` links (227 before). Four unchanged `.docx` files had\nbetter links in the committed XML, probably from a linker built elsewhere. **Effect on this\nexperiment: none.** The links are `Remissao` attributes in the XML. Chunk texts, the gold and the\nmatcher do not use them. They matter only for a future citation-graph use or for the quality of the\nreleased XML. The fix belongs in `../lexml-linker` (the \"caput\" token after \"art. N,\" must keep the\narticle), followed by a re-parse. The text would be byte-identical.\n\n---\n\n## 3. General questions\n\n### 3.1 How do the IR metrics handle missing fragments?\n\nEvery gold item is kept, and an item no chunk can hit is marked **unreachable**\n(`ragpipe/evaluation.py`: `reachable = False` with a reason). Every metric is then reported twice:\n\n- `gold=all` (**the headline**): unreachable items stay in the denominator and count as misses for\n every strategy;\n- `gold=reachable`: unreachable items are left out, and so are questions with no reachable gold.\n\nUnreachable items (`reachability.csv`, identical for all five strategies):\n\n| Level | Gold items | Unreachable | Reason | Questions (all / with reachable gold) | Oracle recall (`gold=all`) |\n|---|---:|---:|---|---|---:|\n| document | 1,725 | 0 | — | 596 / 596 | 1.000 |\n| article | 1,958 | 13 | `article_not_in_lexml`: the treaty articles of §2.3 (a) | 553 / 549 | 0.989 |\n| provision | 2,230 | 57 | `no_lexml_id`: 22 missing fragments (the 25 of §2.3 minus 3 duplicates within a question) + 35 units with no LexML id (non-statutory \"item 19\", \"Anexo II\", \"Capítulo III\", treaty \"Seção 18\"…) | 558 / 548 | 0.965 |\n\nEffect on the reported recall (4k; the other budgets behave alike):\n\n| Level | | S1 | S2 | S3 | S2c | S4 |\n|---|---|---:|---:|---:|---:|---:|\n| article | all / reachable | 0.379 / 0.382 | 0.473 / 0.477 | 0.464 / 0.469 | 0.428 / 0.431 | 0.426 / 0.429 |\n| provision | all / reachable | 0.347 / 0.357 | 0.361 / 0.372 | 0.361 / 0.372 | 0.321 / 0.329 | 0.334 / 0.342 |\n| provision @16k | all / reachable | 0.532 / 0.551 | 0.565 / 0.585 | 0.581 / 0.601 | 0.538 / 0.558 | 0.555 / 0.574 |\n\nSo the missing fragments **lower the absolute numbers** by 0.3–2 points but **do not affect the\ncomparisons**. The unreachable items are the same for every strategy, so they add 0 to both sides of\nevery per-question difference. The 10 provision questions with only unreachable gold give a\ndifference of 0 and dilute the mean difference by 10/558 ≈ 2 %. No sign or significance in §4.2 of\nthe results note depends on them.\n\n**Caveat (N3).** The 5 cited treaty articles whose `ART` chunk is label-only count as *reachable*. A\nhit on them is a hit on \"[decree prefix] Art. 34.\". That is 5 of 1,958 article items (≤ 0.26 % of\narticle recall in the worst case, and their provision items are unreachable anyway). The per-item\ntable that would show whether any of them is ever retrieved could not be regenerated here: the\nrankings and the corpus vectors (`embeddings/jua-4b-mixed/corpus/texts.csv`) are not on disk.\nFixing N3 removes the caveat.\n\n### 3.2 Twenty segmentation samples (10 statutory, 10 non-statutory)\n\n**How they were drawn.** Stratified at random (seed `20261008`) from documents cited by at least one\nquestion, one sample per document, using the frozen chunk set and the pipeline's own\n`ragpipe.strategies.member_mask` for the ✓ columns, which are exactly what retrieval indexes:\n\n- statutory (10): 4 articles with paragraphs, 2 with incisos and no paragraph, 1 without sub-units,\n 1 article split into parts, 1 article of a category-A annex (RIR/2018), and 1 orphan dispositivo\n (`DSP`) of a category-B annex. Articles with 2–10 sub-unit chunks were preferred so the samples stay\n readable;\n- non-statutory (10): 2 SCs, 1 Parecer Normativo, 1 Ato Declaratório, 1 SCI, 1 PGFN parecer, 1 treaty\n decree, 1 service page, 1 court document (STJ súmula), 1 category-C annex table.\n\n**What to check in each sample.** The LexML parse is shown as an outline: each element `id\n[element]: Rotulo + its own text`, with quoted amendment text in «…». The next table shows every chunk\nof the unit with its `cobre_ids`, source interval and Qwen3 tokens, plus the strategies that index it.\nThe full chunk texts follow. Grouping chunks are shortened in the middle, with the omitted length\ngiven.\n\n**What the strategies should look like (design: `docs/20260923_193852_*`, `docs/20261005_184116_*`):**\n\n| | Indexed rows | Text of a paragraph-family chunk |\n|---|---|---|\n| S1 | `ART` (or its parts), `DSP`, `TXT`, `TAB` | — |\n| S2 | S1 + `CPT`, `PAR`, `INC`, `ALI`, `ITE` (`base`) | `[prefix] Art. N. § k …`: article label plus the ancestor path, **without the caput** |\n| S3 | S2 + grouping chunks ≤ 8,192 tokens (larger ones are not emitted: `groupings_over_limit.csv`) | as S2 |\n| S2c / S4 | as S2 / S3, with the `caput` twin (`#c<seq>`) replacing the `base` row | `[prefix] Art. N. <caput sentence> § k …` |\n\nRules visible in the samples:\n\n- a `CPT` chunk is emitted only when the article has paragraphs (A5, A6: articles with only a caput\n and incisos have no `CPT`);\n- caput incisos (`art_cpt_incN`) have no caput variant, because their ancestor path already holds the\n caput. Incisos of a paragraph do get one (A3: `#c4189`);\n- non-statutory units are `TXT`/`TAB` only, so **S1 = S2 = S3 = S2c = S4** for every non-statutory\n chunk. The non-statutory samples check the parse → chunk step only;\n- the metadata prefix is `[ epígrafe | ementa (≤ 128 tokens, \"…\" when cut) | annex label ]`. The\n grouping path is **not** in the prefix of article chunks; it appears only as the heading inside\n grouping chunks and, for non-statutory units, as the `heading > heading` path at the start of the\n text;\n- split units (A8, B6) carry `parte/n_partes`. A split `ART` part repeats the caput sentence in its\n head (caput plan Q2). Split non-statutory parts have an empty `cobre_ids` and the unit in\n `parcial_ids`.\n\n**Defects found in the samples:**\n\n| Sample | Observation | Scope |\n|---|---|---|\n| A8 (Lei 6.766 art. 4) | Inciso \"III-A. –\" is not recognized and is merged into inciso III (`art4_cpt_inc3`); \"III-B\" is correctly `inc3-2` | A corpus-wide pattern search finds only this case |\n| A9 (RIR/2018 art. 483) | The grouping path reads \"LIVRO DE – Apuração do Lucro Real\". The section name ends with \"… Determinação do custo\", an unnumbered sub-heading glued onto \"Seção X\" | **N4**: 404 articles under the fake LIVROs \"LIVRO DIARIO\" (4 articles) and \"LIVRO DE\" (400); LIVRO III contains 1 article; ≈ 210 articles of Livro III are outside any LIVRO; `liv3`/`liv4` are duplicated. Article texts are correct; S3/S4 grouping chunks and `agrupadores_*` are wrong for these articles |\n| B1 (SC Cosit 140/2015) | `pp1_tab1` is a layout table holding body-text fragments (\"natalista, a qual \\| afirma que o nascituro…\"), and comes out as a broken `TAB` chunk | That document |\n| B2 (SC Cosit 194/2015) | Words are glued together: \"setembrode\", \"Decretonº\", \"ouexigir\". The `.docx` itself has them (converted from `.odt`, rebuild plan §1) | This document is the clear outlier in a glued-word scan of all non-statutory sources (10 per 1,000 words; the next is 2.5) |\n| B6 (Parecer PGFN/CAT 1.503/2010) | The quoted case-law ementa has one `<p>` per printed line (hard line breaks in the source). The chunk text joins them correctly | Text is fine; only the XML is noisy |\n| B7 (Decreto 59.309) | The `nota` unit starts with the signatures \"H. Castello Branco M. Pio Corrêa\" before the agreement text | Cosmetic |\n\nEverything else in the 20 samples matches the design: the base and caput texts, the strategy\nmembership, the containment intervals of the grouping chunks, the split-part coverage and the\ncategory-A/B/C annex treatment.\n\n---\n\n## 4. Suggested next steps\n\n1. **Dataset fixes:** drop 144-05; add Q029's 5 service-page references and Q576's explicit\n references; add provision overrides for the 10 fixable fragments of §2.3 (c). This needs the\n provision-level override format.\n2. **Corpus:** remove `in_rfb_1911_20191011`, `in_rfb_1505_20141031`, `decreto_7030_20091214` and,\n unless they are kept as distractors, `lei_3071_19160101` and `lei_5869_19730111`.\n3. **Statutory parser:** attach the text after a bare \"Artigo N\" heading to its article (N3, 14 files);\n read \"Livro diário\"/\"Livro de Apuração…\" as text, not as a LIVRO, inside an article context (N4,\n RIR/2018); accept \"III-A.\" labels. Then re-parse, re-segment and evaluate.\n4. Then the tests and cache (O5/O7) and the linker (O6), which do not affect retrieval numbers.\n\n---\n\n## Appendix: the samples\n\n### A. Statutory samples\n\n#### A1. `lei_6015_19731231.xml` — `art264` (article with paragraphs (main document))\n\n- Document: `lei_6015_19731231` — LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973; cited by 3 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): TÍTULO V – DO REGISTRO DE IMÓVEIS ; CAPÍTULO IX – DO BEM DE FAMÍLIA; source interval Num 2739–2748.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart264 [Artigo]: Art. 264.\n art264_cpt [Caput]: Se for apresentada reclamação, dela fornecerá o oficial ao instituidor, cópia autêntica e lhe restituirá a escritura, com a declaração de haver sido suspenso o registro, cancelando a prenotação.\n art264_par1 [Paragrafo]: § 1º O instituidor poderá requerer ao juiz que ordene o registro, sem embargo da reclamação.\n art264_par2 [Paragrafo]: § 2º Se o juiz determinar que proceda ao registro, ressalvará ao reclamante o direito de recorrer à ação competente para anular a instituição ou de fazer execução sobre o prédio instituído, na hipótese de tratar-se de dívida anterior e cuja solução se tornou inexeqüível em virtude do ato da instituição.\n art264_par3 [Paragrafo]: § 3º O despacho do juiz será irrecorrível e, se deferir o pedido será transcrito integralmente, juntamente com o instrumento.\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_6015_19731231#114` | CPT | base | `art264_cpt` | 2740–2741 | 109 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_6015_19731231#470` | PAR | base | `art264_par1` | 2742–2743 | 77 | | ✓ | ✓ | | |\n| `lei_6015_19731231#c470` | PAR | caput | `art264_par1` | 2742–2743 | 136 | | | | ✓ | ✓ |\n| `lei_6015_19731231#471` | PAR | base | `art264_par2` | 2744–2745 | 141 | | ✓ | ✓ | | |\n| `lei_6015_19731231#c471` | PAR | caput | `art264_par2` | 2744–2745 | 200 | | | | ✓ | ✓ |\n| `lei_6015_19731231#472` | PAR | base | `art264_par3` | 2746–2747 | 86 | | ✓ | ✓ | | |\n| `lei_6015_19731231#c472` | PAR | caput | `art264_par3` | 2746–2747 | 145 | | | | ✓ | ✓ |\n| `lei_6015_19731231#796` | ART | base | `art264` | 2739–2748 | 263 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_6015_19731231#877` | CAP | base | `tit5_cap9` | 2718–2753 | 730 | | | ✓ | | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`lei_6015_19731231#114` (CPT, base):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] Art. 264. Se for apresentada reclamação, dela fornecerá o oficial ao instituidor, cópia autêntica e lhe restituirá a escritura, com a declaração de haver sido suspenso o registro, cancelando a prenotação.\n```\n`lei_6015_19731231#470` (PAR, base):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] Art. 264. § 1º O instituidor poderá requerer ao juiz que ordene o registro, sem embargo da reclamação.\n```\n`lei_6015_19731231#c470` (PAR, caput):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] Art. 264. Se for apresentada reclamação, dela fornecerá o oficial ao instituidor, cópia autêntica e lhe restituirá a escritura, com a declaração de haver sido suspenso o registro, cancelando a prenotação. § 1º O instituidor poderá requerer ao juiz que ordene o registro, sem embargo da reclamação.\n```\n`lei_6015_19731231#471` (PAR, base):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] Art. 264. § 2º Se o juiz determinar que proceda ao registro, ressalvará ao reclamante o direito de recorrer à ação competente para anular a instituição ou de fazer execução sobre o prédio instituído, na hipótese de tratar-se de dívida anterior e cuja solução se tornou inexeqüível em virtude do ato da instituição.\n```\n`lei_6015_19731231#c471` (PAR, caput):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] Art. 264. Se for apresentada reclamação, dela fornecerá o oficial ao instituidor, cópia autêntica e lhe restituirá a escritura, com a declaração de haver sido suspenso o registro, cancelando a prenotação. § 2º Se o juiz determinar que proceda ao registro, ressalvará ao reclamante o direito de recorrer à ação competente para anular a instituição ou de fazer execução sobre o prédio instituído, na hipótese de tratar-se de dívida anterior e cuja solução se tornou inexeqüível em virtude do ato da instituição.\n```\n`lei_6015_19731231#472` (PAR, base):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] Art. 264. § 3º O despacho do juiz será irrecorrível e, se deferir o pedido será transcrito integralmente, juntamente com o instrumento.\n```\n`lei_6015_19731231#c472` (PAR, caput):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] Art. 264. Se for apresentada reclamação, dela fornecerá o oficial ao instituidor, cópia autêntica e lhe restituirá a escritura, com a declaração de haver sido suspenso o registro, cancelando a prenotação. § 3º O despacho do juiz será irrecorrível e, se deferir o pedido será transcrito integralmente, juntamente com o instrumento.\n```\n`lei_6015_19731231#796` (ART, base):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] Art. 264. Se for apresentada reclamação, dela fornecerá o oficial ao instituidor, cópia autêntica e lhe restituirá a escritura, com a declaração de haver sido suspenso o registro, cancelando a prenotação. § 1º O instituidor poderá requerer ao juiz que ordene o registro, sem embargo da reclamação. § 2º Se o juiz determinar que proceda ao registro, ressalvará ao reclamante o direito de recorrer à ação competente para anular a instituição ou de fazer execução sobre o prédio instituído, na hipótese de tratar-se de dívida anterior e cuja solução se tornou inexeqüível em virtude do ato da instituição. § 3º O despacho do juiz será irrecorrível e, se deferir o pedido será transcrito integralmente, juntamente com o instrumento.\n```\n`lei_6015_19731231#877` (CAP, 730 tokens, shortened):\n```text\n[ LEI Nº 6.015, DE 31 DE DEZEMBRO DE 1973 | Dispõe sobre os registros públicos e dá outras providências. ] CAPÍTULO IX DO BEM DE FAMÍLIA Art. 260. A instituição do bem de família far-se-á por escritura pública, declarando o instituidor que determinado prédio se destina a domicílio de sua família e ficará isento de execução por dívida. Art. 261. Para a inscrição do bem de família, o instituidor apresentará ao oficial do registro a escritura pública de instituição, para que mande publicá-la na imp … [1,598 chars omitted] … Quando o bem de família for instituído juntamente com a transmissão da propriedade (Decreto-Lei nº 3.200, de 14 de abril de 1941, artigo 8º, § 5º), a inscrição far-se-á imediatamente após o registro da transmissão ou, se for o caso, com a matrícula.\n```\n\n#### A2. `lei_4504_19641130.xml` — `art126` (article with paragraphs (main document))\n\n- Document: `lei_4504_19641130` — LEI Nº 4.504, DE 30 DE NOVEMBRO DE 1964; cited by 3 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): TÍTULO IV – DAS DISPOSIÇÕES GERAIS E TRANSITÓRIAS; source interval Num 1656–1663.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart126 [Artigo]: Art. 126.\n art126_cpt [Caput]: A Carteira de Colonização do Banco do Brasil, sem prejuízo de suas atribuições legais, atuará como entidade financiadora nas operações de venda de lotes rurais ...VETADO.\n art126_par1 [Paragrafo]: § 1º As Letras Hipotecárias que o Banco do Brasil está autorizado a emitir, em provimento de recursos e em empréstimos da sua Carteira de Colonização, poderão conter cláusula de garantia contra eventual desvalorização de moeda, de acordo com índices que forem sugeridos pelo Conselho Nacional de Economia, assegurando ao mesmo Banco o ressarcimento de prejuízos já previstos no artigo 4º da Lei nº 2.237, de 19 de junho de 1954.\n art126_par2 [Paragrafo]: § 2º Caberá à Diretoria do Banco do Brasil fixar o limite do valor dos empréstimos que o Banco fica autorizado a realizar no País ou no estrangeiro para aplicação, pela sua Carteira de Colonização, revogado, portanto o limite estabelecido no parágrafo único do art. 8º da Lei número 2.237, de 19 de junho de 1964, e as disposições em contrário.\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_4504_19641130#65` | CPT | base | `art126_cpt` | 1657–1658 | 103 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_4504_19641130#259` | PAR | base | `art126_par1` | 1659–1660 | 185 | | ✓ | ✓ | | |\n| `lei_4504_19641130#c259` | PAR | caput | `art126_par1` | 1659–1660 | 235 | | | | ✓ | ✓ |\n| `lei_4504_19641130#260` | PAR | base | `art126_par2` | 1661–1662 | 164 | | ✓ | ✓ | | |\n| `lei_4504_19641130#c260` | PAR | caput | `art126_par2` | 1661–1662 | 214 | | | | ✓ | ✓ |\n| `lei_4504_19641130#394` | ART | base | `art126` | 1656–1663 | 346 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_4504_19641130#400` | TIT | base | `tit4` | 1443–1672 | 5309 | | | ✓ | | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`lei_4504_19641130#65` (CPT, base):\n```text\n[ LEI Nº 4.504, DE 30 DE NOVEMBRO DE 1964 | Dispõe sobre o Estatuto da Terra, e dá outras providências. ] Art. 126. A Carteira de Colonização do Banco do Brasil, sem prejuízo de suas atribuições legais, atuará como entidade financiadora nas operações de venda de lotes rurais ...VETADO.\n```\n`lei_4504_19641130#259` (PAR, base):\n```text\n[ LEI Nº 4.504, DE 30 DE NOVEMBRO DE 1964 | Dispõe sobre o Estatuto da Terra, e dá outras providências. ] Art. 126. § 1º As Letras Hipotecárias que o Banco do Brasil está autorizado a emitir, em provimento de recursos e em empréstimos da sua Carteira de Colonização, poderão conter cláusula de garantia contra eventual desvalorização de moeda, de acordo com índices que forem sugeridos pelo Conselho Nacional de Economia, assegurando ao mesmo Banco o ressarcimento de prejuízos já previstos no artigo 4º da Lei nº 2.237, de 19 de junho de 1954.\n```\n`lei_4504_19641130#c259` (PAR, caput):\n```text\n[ LEI Nº 4.504, DE 30 DE NOVEMBRO DE 1964 | Dispõe sobre o Estatuto da Terra, e dá outras providências. ] Art. 126. A Carteira de Colonização do Banco do Brasil, sem prejuízo de suas atribuições legais, atuará como entidade financiadora nas operações de venda de lotes rurais ...VETADO. § 1º As Letras Hipotecárias que o Banco do Brasil está autorizado a emitir, em provimento de recursos e em empréstimos da sua Carteira de Colonização, poderão conter cláusula de garantia contra eventual desvalorização de moeda, de acordo com índices que forem sugeridos pelo Conselho Nacional de Economia, assegurando ao mesmo Banco o ressarcimento de prejuízos já previstos no artigo 4º da Lei nº 2.237, de 19 de junho de 1954.\n```\n`lei_4504_19641130#260` (PAR, base):\n```text\n[ LEI Nº 4.504, DE 30 DE NOVEMBRO DE 1964 | Dispõe sobre o Estatuto da Terra, e dá outras providências. ] Art. 126. § 2º Caberá à Diretoria do Banco do Brasil fixar o limite do valor dos empréstimos que o Banco fica autorizado a realizar no País ou no estrangeiro para aplicação, pela sua Carteira de Colonização, revogado, portanto o limite estabelecido no parágrafo único do art. 8º da Lei número 2.237, de 19 de junho de 1964, e as disposições em contrário.\n```\n`lei_4504_19641130#c260` (PAR, caput):\n```text\n[ LEI Nº 4.504, DE 30 DE NOVEMBRO DE 1964 | Dispõe sobre o Estatuto da Terra, e dá outras providências. ] Art. 126. A Carteira de Colonização do Banco do Brasil, sem prejuízo de suas atribuições legais, atuará como entidade financiadora nas operações de venda de lotes rurais ...VETADO. § 2º Caberá à Diretoria do Banco do Brasil fixar o limite do valor dos empréstimos que o Banco fica autorizado a realizar no País ou no estrangeiro para aplicação, pela sua Carteira de Colonização, revogado, portanto o limite estabelecido no parágrafo único do art. 8º da Lei número 2.237, de 19 de junho de 1964, e as disposições em contrário.\n```\n`lei_4504_19641130#394` (ART, base):\n```text\n[ LEI Nº 4.504, DE 30 DE NOVEMBRO DE 1964 | Dispõe sobre o Estatuto da Terra, e dá outras providências. ] Art. 126. A Carteira de Colonização do Banco do Brasil, sem prejuízo de suas atribuições legais, atuará como entidade financiadora nas operações de venda de lotes rurais ...VETADO. § 1º As Letras Hipotecárias que o Banco do Brasil está autorizado a emitir, em provimento de recursos e em empréstimos da sua Carteira de Colonização, poderão conter cláusula de garantia contra eventual desvalorização de moeda, de acordo com índices que forem sugeridos pelo Conselho Nacional de Economia, assegurando ao mesmo Banco o ressarcimento de prejuízos já previstos no artigo 4º da Lei nº 2.237, de 19 de junho de 1954. § 2º Caberá à Diretoria do Banco do Brasil fixar o limite do valor dos empréstimos que o Banco fica autorizado a realizar no País ou no estrangeiro para aplicação, pela sua Carteira de Colonização, revogado, portanto o limite estabelecido no parágrafo único do art. 8º da Lei número 2.237, de 19 de junho de 1964, e as disposições em contrário.\n```\n`lei_4504_19641130#400` (TIT, 5309 tokens, shortened):\n```text\n[ LEI Nº 4.504, DE 30 DE NOVEMBRO DE 1964 | Dispõe sobre o Estatuto da Terra, e dá outras providências. ] TÍTULO IV DAS DISPOSIÇÕES GERAIS E TRANSITÓRIAS Art. 103. A aplicação da presente Lei deverá objetivar, antes e acima de tudo, a perfeita ordenação do sistema agrário do País, de acordo com os princípios da justiça social, conciliando a liberdade de iniciativa com a valorização do trabalho humano. § 1º Para a plena execução do disposto neste artigo, o Poder Executivo, através dos órgãos da s … [17,709 chars omitted] … to o limite estabelecido no parágrafo único do art. 8º da Lei número 2.237, de 19 de junho de 1964, e as disposições em contrário. Art. 127. VETADO. Art. 128. Esta Lei entrará em vigor na data de sua publicação, revogadas as disposições em contrário.\n```\n\n#### A3. `lei_13105_20150316.xml` — `art657` (article with paragraphs (main document))\n\n- Document: `lei_13105_20150316` — LEI Nº 13.105, DE 16 DE MARÇO DE 2015; cited by 11 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): PARTE ESPECIAL ; LIVRO I – DO PROCESSO DE CONHECIMENTO E DO CUMPRIMENTO DE SENTENÇA ; TÍTULO III – DOS PROCEDIMENTOS ESPECIAIS ; CAPÍTULO VI – DO INVENTÁRIO E DA PARTILHA ; Seção VIII – Da Partilha; source interval Num 6234–6245.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart657 [Artigo]: Art. 657.\n art657_cpt [Caput]: A partilha amigável, lavrada em instrumento público, reduzida a termo nos autos do inventário ou constante de escrito particular homologado pelo juiz, pode ser anulada por dolo, coação, erro essencial ou intervenção de incapaz, observado o disposto no § 4º do art. 966.\n art657_par1u [Paragrafo]: Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo:\n art657_par1u_inc1 [Inciso]: I – no caso de coação, do dia em que ela cessou;\n art657_par1u_inc2 [Inciso]: II – no caso de erro ou dolo, do dia em que se realizou o ato;\n art657_par1u_inc3 [Inciso]: III – quanto ao incapaz, do dia em que cessar a incapacidade.\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_13105_20150316#344` | CPT | base | `art657_cpt` | 6235–6236 | 122 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_13105_20150316#1437` | PAR | base | `art657_par1u` | 6237–6244 | 131 | | ✓ | ✓ | | |\n| `lei_13105_20150316#c1437` | PAR | caput | `art657_par1u` | 6237–6244 | 212 | | | | ✓ | ✓ |\n| `lei_13105_20150316#2754` | ART | base | `art657` | 6234–6245 | 212 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `lei_13105_20150316#4189` | INC | base | `art657_par1u_inc1` | 6238–6239 | 93 | | ✓ | ✓ | | |\n| `lei_13105_20150316#c4189` | INC | caput | `art657_par1u_inc1` | 6238–6239 | 174 | | | | ✓ | ✓ |\n| `lei_13105_20150316#4190` | INC | base | `art657_par1u_inc2` | 6240–6241 | 98 | | ✓ | ✓ | | |\n| `lei_13105_20150316#c4190` | INC | caput | `art657_par1u_inc2` | 6240–6241 | 179 | | | | ✓ | ✓ |\n| `lei_13105_20150316#4191` | INC | base | `art657_par1u_inc3` | 6242–6243 | 94 | | ✓ | ✓ | | |\n| `lei_13105_20150316#c4191` | INC | caput | `art657_par1u_inc3` | 6242–6243 | 175 | | | | ✓ | ✓ |\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_13105_20150316#3376` | SEC | base | `prt2_liv1_tit3_cap6_sec8` | 6151–6256 | 1428 | | | ✓ | | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`lei_13105_20150316#344` (CPT, base):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. A partilha amigável, lavrada em instrumento público, reduzida a termo nos autos do inventário ou constante de escrito particular homologado pelo juiz, pode ser anulada por dolo, coação, erro essencial ou intervenção de incapaz, observado o disposto no § 4º do art. 966.\n```\n`lei_13105_20150316#1437` (PAR, base):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: I – no caso de coação, do dia em que ela cessou; II – no caso de erro ou dolo, do dia em que se realizou o ato; III – quanto ao incapaz, do dia em que cessar a incapacidade.\n```\n`lei_13105_20150316#c1437` (PAR, caput):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. A partilha amigável, lavrada em instrumento público, reduzida a termo nos autos do inventário ou constante de escrito particular homologado pelo juiz, pode ser anulada por dolo, coação, erro essencial ou intervenção de incapaz, observado o disposto no § 4º do art. 966. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: I – no caso de coação, do dia em que ela cessou; II – no caso de erro ou dolo, do dia em que se realizou o ato; III – quanto ao incapaz, do dia em que cessar a incapacidade.\n```\n`lei_13105_20150316#2754` (ART, base):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. A partilha amigável, lavrada em instrumento público, reduzida a termo nos autos do inventário ou constante de escrito particular homologado pelo juiz, pode ser anulada por dolo, coação, erro essencial ou intervenção de incapaz, observado o disposto no § 4º do art. 966. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: I – no caso de coação, do dia em que ela cessou; II – no caso de erro ou dolo, do dia em que se realizou o ato; III – quanto ao incapaz, do dia em que cessar a incapacidade.\n```\n`lei_13105_20150316#4189` (INC, base):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: I – no caso de coação, do dia em que ela cessou;\n```\n`lei_13105_20150316#c4189` (INC, caput):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. A partilha amigável, lavrada em instrumento público, reduzida a termo nos autos do inventário ou constante de escrito particular homologado pelo juiz, pode ser anulada por dolo, coação, erro essencial ou intervenção de incapaz, observado o disposto no § 4º do art. 966. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: I – no caso de coação, do dia em que ela cessou;\n```\n`lei_13105_20150316#4190` (INC, base):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: II – no caso de erro ou dolo, do dia em que se realizou o ato;\n```\n`lei_13105_20150316#c4190` (INC, caput):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. A partilha amigável, lavrada em instrumento público, reduzida a termo nos autos do inventário ou constante de escrito particular homologado pelo juiz, pode ser anulada por dolo, coação, erro essencial ou intervenção de incapaz, observado o disposto no § 4º do art. 966. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: II – no caso de erro ou dolo, do dia em que se realizou o ato;\n```\n`lei_13105_20150316#4191` (INC, base):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: III – quanto ao incapaz, do dia em que cessar a incapacidade.\n```\n`lei_13105_20150316#c4191` (INC, caput):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Art. 657. A partilha amigável, lavrada em instrumento público, reduzida a termo nos autos do inventário ou constante de escrito particular homologado pelo juiz, pode ser anulada por dolo, coação, erro essencial ou intervenção de incapaz, observado o disposto no § 4º do art. 966. Parágrafo único. O direito à anulação de partilha amigável extingue-se em 1 (um) ano, contado esse prazo: III – quanto ao incapaz, do dia em que cessar a incapacidade.\n```\n`lei_13105_20150316#3376` (SEC, 1428 tokens, shortened):\n```text\n[ LEI Nº 13.105, DE 16 DE MARÇO DE 2015 | Código de Processo Civil. ] Seção VIII Da Partilha Art. 647. Cumprido o disposto no art. 642, § 3º, o juiz facultará às partes que, no prazo comum de 15 (quinze) dias, formulem o pedido de quinhão e, em seguida, proferirá a decisão de deliberação da partilha, resolvendo os pedidos das partes e designando os bens que devam constituir quinhão de cada herdeiro e legatário. Parágrafo único. O juiz poderá, em decisão fundamentada, deferir antecipadamente a qu … [3,838 chars omitted] … incapaz, do dia em que cessar a incapacidade. Art. 658. É rescindível a partilha julgada por sentença: I – nos casos mencionados no art. 657; II – se feita com preterição de formalidades legais; III – se preteriu herdeiro ou incluiu quem não o seja.\n```\n\n#### A4. `lei_10406_20020110.xml` — `art1341` (article with paragraphs (main document))\n\n- Document: `lei_10406_20020110` — LEI Nº 10.406, DE 10 DE JANEIRO DE 2002; cited by 24 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): PARTE ESPECIAL ; LIVRO III – Do Direito das Coisas ; TÍTULO III – Da Propriedade ; CAPÍTULO VII – Do Condomínio Edilício ; Seção I – Disposições Gerais; source interval Num 7936–7951.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart1341 [Artigo]: Art. 1.341.\n art1341_cpt [Caput]: A realização de obras no condomínio depende:\n art1341_cpt_inc1 [Inciso]: I – se voluptuárias, de voto de dois terços dos condôminos;\n art1341_cpt_inc2 [Inciso]: II – se úteis, de voto da maioria dos condôminos.\n art1341_par1 [Paragrafo]: § 1º As obras ou reparações necessárias podem ser realizadas, independentemente de autorização, pelo síndico, ou, em caso de omissão ou impedimento deste, por qualquer condômino.\n art1341_par2 [Paragrafo]: § 2º Se as obras ou reparos necessários forem urgentes e importarem em despesas excessivas, determinada sua realização, o síndico ou o condômino que tomou a iniciativa delas dará ciência à assembléia, que deverá ser convocada imediatamente.\n art1341_par3 [Paragrafo]: § 3º Não sendo urgentes, as obras ou reparos necessários, que importarem em despesas excessivas, somente poderão ser efetuadas após autorização da assembléia, especialmente convocada pelo síndico, ou, em caso de omissão ou impedimento deste, por qualquer dos condôminos.\n art1341_par4 [Paragrafo]: § 4º O condômino que realizar obras ou reparos necessários será reembolsado das despesas que efetuar, não tendo direito à restituição das que fizer com obras ou reparos de outra natureza, embora de interesse comum.\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_10406_20020110#381` | CPT | base | `art1341_cpt` | 7937–7942 | 95 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_10406_20020110#1178` | PAR | base | `art1341_par1` | 7943–7944 | 90 | | ✓ | ✓ | | |\n| `lei_10406_20020110#c1178` | PAR | caput | `art1341_par1` | 7943–7944 | 102 | | | | ✓ | ✓ |\n| `lei_10406_20020110#1179` | PAR | base | `art1341_par2` | 7945–7946 | 114 | | ✓ | ✓ | | |\n| `lei_10406_20020110#c1179` | PAR | caput | `art1341_par2` | 7945–7946 | 126 | | | | ✓ | ✓ |\n| `lei_10406_20020110#1180` | PAR | base | `art1341_par3` | 7947–7948 | 116 | | ✓ | ✓ | | |\n| `lei_10406_20020110#c1180` | PAR | caput | `art1341_par3` | 7947–7948 | 128 | | | | ✓ | ✓ |\n| `lei_10406_20020110#1181` | PAR | base | `art1341_par4` | 7949–7950 | 103 | | ✓ | ✓ | | |\n| `lei_10406_20020110#c1181` | PAR | caput | `art1341_par4` | 7949–7950 | 115 | | | | ✓ | ✓ |\n| `lei_10406_20020110#2901` | ART | base | `art1341` | 7936–7951 | 346 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `lei_10406_20020110#4481` | INC | base | `art1341_cpt_inc1` | 7938–7939 | 76 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_10406_20020110#4482` | INC | base | `art1341_cpt_inc2` | 7940–7941 | 74 | | ✓ | ✓ | ✓ | ✓ |\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_10406_20020110#3813` | CAP | base | `prt2_liv3_tit3_cap7` | 7838–8107 | 5667 | | | ✓ | | ✓ |\n| `lei_10406_20020110#3989` | SEC | base | `prt2_liv3_tit3_cap7_sec1` | 7839–7972 | 2555 | | | ✓ | | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`lei_10406_20020110#381` (CPT, base):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. A realização de obras no condomínio depende: I – se voluptuárias, de voto de dois terços dos condôminos; II – se úteis, de voto da maioria dos condôminos.\n```\n`lei_10406_20020110#1178` (PAR, base):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. § 1º As obras ou reparações necessárias podem ser realizadas, independentemente de autorização, pelo síndico, ou, em caso de omissão ou impedimento deste, por qualquer condômino.\n```\n`lei_10406_20020110#c1178` (PAR, caput):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. A realização de obras no condomínio depende: § 1º As obras ou reparações necessárias podem ser realizadas, independentemente de autorização, pelo síndico, ou, em caso de omissão ou impedimento deste, por qualquer condômino.\n```\n`lei_10406_20020110#1179` (PAR, base):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. § 2º Se as obras ou reparos necessários forem urgentes e importarem em despesas excessivas, determinada sua realização, o síndico ou o condômino que tomou a iniciativa delas dará ciência à assembléia, que deverá ser convocada imediatamente.\n```\n`lei_10406_20020110#c1179` (PAR, caput):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. A realização de obras no condomínio depende: § 2º Se as obras ou reparos necessários forem urgentes e importarem em despesas excessivas, determinada sua realização, o síndico ou o condômino que tomou a iniciativa delas dará ciência à assembléia, que deverá ser convocada imediatamente.\n```\n`lei_10406_20020110#1180` (PAR, base):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. § 3º Não sendo urgentes, as obras ou reparos necessários, que importarem em despesas excessivas, somente poderão ser efetuadas após autorização da assembléia, especialmente convocada pelo síndico, ou, em caso de omissão ou impedimento deste, por qualquer dos condôminos.\n```\n`lei_10406_20020110#c1180` (PAR, caput):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. A realização de obras no condomínio depende: § 3º Não sendo urgentes, as obras ou reparos necessários, que importarem em despesas excessivas, somente poderão ser efetuadas após autorização da assembléia, especialmente convocada pelo síndico, ou, em caso de omissão ou impedimento deste, por qualquer dos condôminos.\n```\n`lei_10406_20020110#1181` (PAR, base):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. § 4º O condômino que realizar obras ou reparos necessários será reembolsado das despesas que efetuar, não tendo direito à restituição das que fizer com obras ou reparos de outra natureza, embora de interesse comum.\n```\n`lei_10406_20020110#c1181` (PAR, caput):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. A realização de obras no condomínio depende: § 4º O condômino que realizar obras ou reparos necessários será reembolsado das despesas que efetuar, não tendo direito à restituição das que fizer com obras ou reparos de outra natureza, embora de interesse comum.\n```\n`lei_10406_20020110#2901` (ART, base):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. A realização de obras no condomínio depende: I – se voluptuárias, de voto de dois terços dos condôminos; II – se úteis, de voto da maioria dos condôminos. § 1º As obras ou reparações necessárias podem ser realizadas, independentemente de autorização, pelo síndico, ou, em caso de omissão ou impedimento deste, por qualquer condômino. § 2º Se as obras ou reparos necessários forem urgentes e importarem em despesas excessivas, determinada sua realização, o síndico ou o condômino que tomou a iniciativa delas dará ciência à assembléia, que deverá ser convocada imediatamente. § 3º Não sendo urgentes, as obras ou reparos necessários, que importarem em despesas excessivas, somente poderão ser efetuadas após autorização da assembléia, especialmente convocada pelo síndico, ou, em caso de omissão ou impedimento deste, por qualquer dos condôminos. § 4º O condômino que realizar obras ou reparos necessários será reembolsado das despesas que efetuar, não tendo direito à restituição das que fizer com obras ou reparos de outra natureza, embora de interesse comum.\n```\n`lei_10406_20020110#4481` (INC, base):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. A realização de obras no condomínio depende: I – se voluptuárias, de voto de dois terços dos condôminos;\n```\n`lei_10406_20020110#4482` (INC, base):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Art. 1.341. A realização de obras no condomínio depende: II – se úteis, de voto da maioria dos condôminos.\n```\n`lei_10406_20020110#3813` (CAP, 5667 tokens, shortened):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] CAPÍTULO VII Do Condomínio Edilício Seção I Disposições Gerais Art. 1.331. Pode haver, em edificações, partes que são propriedade exclusiva, e partes que são propriedade comum dos condôminos. § 1º As partes suscetíveis de utilização independente, tais como apartamentos, escritórios, salas, lojas e sobrelojas, com as respectivas frações ideais no solo e nas outras partes comuns, sujeitam-se a propriedade exclusiva, podendo ser … [16,964 chars omitted] … porador quanto aos aspectos civis e registrários. (Incluído por Lei nº 14.382 de 27.06.2022) § 3º Para fins de incorporação imobiliária, a implantação de toda a infraestrutura ficará a cargo do empreendedor. (Incluído por Lei nº 13.465 de 11.07.2017)\n```\n`lei_10406_20020110#3989` (SEC, 2555 tokens, shortened):\n```text\n[ LEI Nº 10.406, DE 10 DE JANEIRO DE 2002 | Institui o Código Civil. ] Seção I Disposições Gerais Art. 1.331. Pode haver, em edificações, partes que são propriedade exclusiva, e partes que são propriedade comum dos condôminos. § 1º As partes suscetíveis de utilização independente, tais como apartamentos, escritórios, salas, lojas e sobrelojas, com as respectivas frações ideais no solo e nas outras partes comuns, sujeitam-se a propriedade exclusiva, podendo ser alienadas e gravadas livremente por … [7,715 chars omitted] … rt. 1.345. O adquirente de unidade responde pelos débitos do alienante, em relação ao condomínio, inclusive multas e juros moratórios. Art. 1.346. É obrigatório o seguro de toda a edificação contra o risco de incêndio ou destruição, total ou parcial.\n```\n\n#### A5. `lei_8134_19901227.xml` — `art26` (article with incisos/alíneas, no paragraph (main document))\n\n- Document: `lei_8134_19901227` — LEI Nº 8.134, DE 27 DE DEZEMBRO DE 1990; cited by 9 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): —; source interval Num 237–244.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart26 [Artigo]: Art. 26.\n art26_cpt [Caput]: O disposto no artigo anterior não se aplica:\n art26_cpt_inc1 [Inciso]: I – aos resgates de quotas dos fundos de renda fixa, que continuam tributados na forma do art. 47 da Lei n° 7.799, de 1989;\n art26_cpt_inc2 [Inciso]: II – aos resgates de quotas dos fundos de aplicação de curto prazo, que continuam tributados na forma do art. 48 da Lei n° 7.799, de 1989, com as alterações do art. 1° da Lei n° 7.856, de 24 de outubro de 1989.\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_8134_19901227#72` | ART | base | `art26` | 237–244 | 203 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `lei_8134_19901227#112` | INC | base | `art26_cpt_inc1` | 239–240 | 115 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_8134_19901227#113` | INC | base | `art26_cpt_inc2` | 241–242 | 154 | | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`lei_8134_19901227#72` (ART, base):\n```text\n[ LEI Nº 8.134, DE 27 DE DEZEMBRO DE 1990 | Altera a legislação do Imposto de Renda e dá outras providências. ] Art. 26. O disposto no artigo anterior não se aplica: I – aos resgates de quotas dos fundos de renda fixa, que continuam tributados na forma do art. 47 da Lei n° 7.799, de 1989; II – aos resgates de quotas dos fundos de aplicação de curto prazo, que continuam tributados na forma do art. 48 da Lei n° 7.799, de 1989, com as alterações do art. 1° da Lei n° 7.856, de 24 de outubro de 1989.\n```\n`lei_8134_19901227#112` (INC, base):\n```text\n[ LEI Nº 8.134, DE 27 DE DEZEMBRO DE 1990 | Altera a legislação do Imposto de Renda e dá outras providências. ] Art. 26. O disposto no artigo anterior não se aplica: I – aos resgates de quotas dos fundos de renda fixa, que continuam tributados na forma do art. 47 da Lei n° 7.799, de 1989;\n```\n`lei_8134_19901227#113` (INC, base):\n```text\n[ LEI Nº 8.134, DE 27 DE DEZEMBRO DE 1990 | Altera a legislação do Imposto de Renda e dá outras providências. ] Art. 26. O disposto no artigo anterior não se aplica: II – aos resgates de quotas dos fundos de aplicação de curto prazo, que continuam tributados na forma do art. 48 da Lei n° 7.799, de 1989, com as alterações do art. 1° da Lei n° 7.856, de 24 de outubro de 1989.\n```\n\n#### A6. `decreto_3000_19990326.xml` — `art721` (article with incisos/alíneas, no paragraph (main document))\n\n- Document: `decreto_3000_19990326` — DECRETO Nº 3.000, DE 26 DE MARÇO DE 1999; cited by 1 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): LIVRO IIITRIBUTACAO – NA FONTE E SOBRE OPERAÇÕES FINANCEIRAS ; TÍTULO I – TRIBUTAÇÃO NA FONTE ; CAPÍTULO VI – RETENÇÃO E RECOLHIMENTO ; Seção I – Retenção do Imposto Responsabilidade da Fonte; source interval Num 8203–8210.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart721 [Artigo]: Art. 721.\n art721_cpt [Caput]: Compete ao procurador a retenção (Decreto-Lei nº 5.844, de 1943, art. 100, parágrafo único):\n art721_cpt_inc1 [Inciso]: I – quando se tratar de aluguéis de imóveis pertencentes a residentes no exterior;\n art721_cpt_inc2 [Inciso]: II – quando o procurador não der conhecimento à fonte de que o proprietário do rendimento reside ou é domiciliado no exterior.\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `decreto_3000_19990326#2738` | ART | base | `art721` | 8203–8210 | 183 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `decreto_3000_19990326#4598` | INC | base | `art721_cpt_inc1` | 8205–8206 | 153 | | ✓ | ✓ | ✓ | ✓ |\n| `decreto_3000_19990326#4599` | INC | base | `art721_cpt_inc2` | 8207–8208 | 160 | | ✓ | ✓ | ✓ | ✓ |\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `decreto_3000_19990326#3164` | CAP | base | `liv6_tit1_cap6` | 8171–8242 | 1778 | | | ✓ | | ✓ |\n| `decreto_3000_19990326#3377` | SEC | base | `liv6_tit1_cap6_sec1` | 8172–8235 | 1696 | | | ✓ | | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`decreto_3000_19990326#2738` (ART, base):\n```text\n[ DECRETO Nº 3.000, DE 26 DE MARÇO DE 1999 | Regulamenta a tributação, fiscalização, arrecadação e administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. ] Responsabilidade do Procurador de Residente ou Domiciliado no Exterior Art. 721. Compete ao procurador a retenção (Decreto-Lei nº 5.844, de 1943, art. 100, parágrafo único): I – quando se tratar de aluguéis de imóveis pertencentes a residentes no exterior; II – quando o procurador não der conhecimento à fonte de que o proprietário do rendimento reside ou é domiciliado no exterior.\n```\n`decreto_3000_19990326#4598` (INC, base):\n```text\n[ DECRETO Nº 3.000, DE 26 DE MARÇO DE 1999 | Regulamenta a tributação, fiscalização, arrecadação e administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. ] Responsabilidade do Procurador de Residente ou Domiciliado no Exterior Art. 721. Compete ao procurador a retenção (Decreto-Lei nº 5.844, de 1943, art. 100, parágrafo único): I – quando se tratar de aluguéis de imóveis pertencentes a residentes no exterior;\n```\n`decreto_3000_19990326#4599` (INC, base):\n```text\n[ DECRETO Nº 3.000, DE 26 DE MARÇO DE 1999 | Regulamenta a tributação, fiscalização, arrecadação e administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. ] Responsabilidade do Procurador de Residente ou Domiciliado no Exterior Art. 721. Compete ao procurador a retenção (Decreto-Lei nº 5.844, de 1943, art. 100, parágrafo único): II – quando o procurador não der conhecimento à fonte de que o proprietário do rendimento reside ou é domiciliado no exterior.\n```\n`decreto_3000_19990326#3164` (CAP, 1778 tokens, shortened):\n```text\n[ DECRETO Nº 3.000, DE 26 DE MARÇO DE 1999 | Regulamenta a tributação, fiscalização, arrecadação e administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. ] CAPÍTULO VI RETENÇÃO E RECOLHIMENTO Seção I Retenção do Imposto Responsabilidade da Fonte Art. 717. Compete à fonte reter o imposto de que trata este Título, salvo disposição em contrário (Decreto-Lei nº 5.844, de 1943, arts. 99 e 100, e Lei nº 7.713, de 1988, art. 7º, § 1º). Responsabilidade no Caso de Decisão Judicial Art. … [4,741 chars omitted] … de 1962, art. 5º, e Lei nº 8.981, de 1995, art. 63, § 2º). Seção II Prazos de Recolhimento Art. 726. Ressalvados os prazos específicos previstos neste Decreto, o imposto de renda retido na fonte deverá ser recolhido nos prazos referidos no art. 865.\n```\n`decreto_3000_19990326#3377` (SEC, 1696 tokens, shortened):\n```text\n[ DECRETO Nº 3.000, DE 26 DE MARÇO DE 1999 | Regulamenta a tributação, fiscalização, arrecadação e administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. ] Seção I Retenção do Imposto Responsabilidade da Fonte Art. 717. Compete à fonte reter o imposto de que trata este Título, salvo disposição em contrário (Decreto-Lei nº 5.844, de 1943, arts. 99 e 100, e Lei nº 7.713, de 1988, art. 7º, § 1º). Responsabilidade no Caso de Decisão Judicial Art. 718. O imposto incidente sobre os r … [4,514 chars omitted] … a líquida, cabendo o reajustamento do respectivo rendimento bruto, sobre o qual recairá o imposto, ressalvadas as hipóteses a que se referem os arts. 677 e 703, parágrafo único (Lei nº 4.154, de 1962, art. 5º, e Lei nº 8.981, de 1995, art. 63, § 2º).\n```\n\n#### A7. `lei_10833_20031229.xml` — `art20` (article without sub-units (main document))\n\n- Document: `lei_10833_20031229` — LEI Nº 10.833, DE 29 DE DEZEMBRO DE 2003; cited by 5 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): CAPÍTULO II – DAS OUTRAS DISPOSIÇÕES RELATIVAS À LEGISLAÇÃO TRIBUTÁRIA; source interval Num 482–485.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart20 [Artigo]: Art. 20.\n art20_cpt [Caput]: O art. 11 da Lei nº 8.248, de 23 de outubro de 1991, passa a vigorar com a seguinte redação: «Art. 11. Para fazer jus aos benefícios previstos no art. 4º desta Lei, as empresas de desenvolvimento ou produção de bens e serviços de informática e automação deverão investir, anualmente, em atividades de pesquisa e desenvolvimento em tecnologia da informação a serem realizadas no País, no mínimo 5% (cinco por cento) do seu faturamento bruto no mercado interno, decorrente da comercialização de bens e serviços de informática, deduzidos os tributos correspondentes a tais comercializações, bem como o valor das aquisições de produtos incentivados na forma desta Lei e da nº 8.387, de 30 de dezembro de 1991, conforme projeto elaborado pelas próprias empresas, a partir da apresentação da proposta de projeto de que trata o § 1ºC do art. 4º desta Lei.»\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_10833_20031229#309` | ART | base | `art20` | 482–485 | 301 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`lei_10833_20031229#309` (ART, base):\n```text\n[ LEI Nº 10.833, DE 29 DE DEZEMBRO DE 2003 | Altera a Legislação Tributária Federal e dá outras providências. ] Art. 20. O art. 11 da Lei nº 8.248, de 23 de outubro de 1991, passa a vigorar com a seguinte redação: Art. 11. Para fazer jus aos benefícios previstos no art. 4º desta Lei, as empresas de desenvolvimento ou produção de bens e serviços de informática e automação deverão investir, anualmente, em atividades de pesquisa e desenvolvimento em tecnologia da informação a serem realizadas no País, no mínimo 5% (cinco por cento) do seu faturamento bruto no mercado interno, decorrente da comercialização de bens e serviços de informática, deduzidos os tributos correspondentes a tais comercializações, bem como o valor das aquisições de produtos incentivados na forma desta Lei e da nº 8.387, de 30 de dezembro de 1991, conforme projeto elaborado pelas próprias empresas, a partir da apresentação da proposta de projeto de que trata o § 1ºC do art. 4º desta Lei.\n```\n\n#### A8. `lei_6766_19791219.xml` — `art4` (long article split into parts (main document))\n\n- Document: `lei_6766_19791219` — LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979; cited by 4 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): CAPÍTULO II – DOS REQUISITOS URBANÍSTICOS PARA LOTEAMENTO; source interval Num 69–94.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart4 [Artigo]: Art. 4º\n art4_cpt [Caput]: Os loteamentos deverão atender, pelo menos, aos seguintes requisitos:\n art4_cpt_inc1 [Inciso]: I – as áreas destinadas a sistemas de circulação, a implantação de equipamento urbano e comunitário, bem como a espaços livres de uso público, serão proporcionais à densidade de ocupação prevista pelo plano diretor ou aprovada por lei municipal para a zona em que se situem. (Inciso com redação dada pela Lei nº 9.785, de 29.1.1999)\n art4_cpt_inc2 [Inciso]: II – os lotes terão área mínima de 125 m2 (cento e vinte e cinco metros quadrados) e frente mínima de 5 (cinco) metros, salvo quando a legislação estadual ou municipal determinar maiores exigências, ou quando o loteamento se destinar a urbanização específica ou edificação de conjuntos habitacionais de interesse social, previamente aprovados pelos órgãos públicos competentes;\n art4_cpt_inc3 [Inciso]: III – ao longo das faixas de domínio público das rodovias, a reserva de faixa não edificável de, no mínimo, 15 (quinze) metros de cada lado poderá ser reduzida por lei municipal ou distrital que aprovar o instrumento do planejamento territorial, até o limite mínimo de 5 (cinco) metros de cada lado. (Inciso com redação dada pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019) III-A. - ao longo da faixa de domínio das ferrovias, será obrigatória a reserva de uma faixa não edificável de, no mínimo, 15 (quinze) metros de cada lado; (Inciso acrescido pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019, com redação dada pela Lei nº 14.285, de 29.12.2021)\n art4_cpt_inc3-2 [Inciso]: III-B – ao longo das águas correntes e dormentes, as áreas de faixas não edificáveis deverão respeitar a lei municipal ou distrital que aprovar o instrumento de planejamento territorial e que definir e regulamentar a largura das faixas marginais de cursos d´água naturais em área urbana consolidada, nos termos da Lei nº 12.651, de 25 de maio de 2012, com obrigatoriedade de reserva de uma faixa não edificável para cada trecho de margem, indicada em diagnóstico socioambiental elaborado pelo Município; (Inciso acrescido pela Lei nº 14.285, de 29.12.2021)\n art4_cpt_inc4 [Inciso]: IV – as vias de loteamento deverão articular-se com as vias adjacentes oficiais, existentes ou projetadas, e harmonizar-se com a topografia local.\n art4_par1 [Paragrafo]: § 1º A legislação municipal definirá, para cada zona em que se divida o território do Município, os usos permitidos e os índices urbanísticos de parcelamento e ocupação do solo, que incluirão, obrigatoriamente, as áreas mínimas e máximas de lotes e os coeficientes máximos de aproveitamento. (Parágrafo com redação dada pela Lei nº 9.785, de 29.1.1999)\n art4_par2 [Paragrafo]: § 2º Consideram-se comunitários os equipamentos públicos de educação, cultura, saúde, lazer e similares.\n art4_par3 [Paragrafo]: § 3º Se necessária, a reserva de faixa não-edificável vinculada a dutovias será exigida no âmbito do respectivo licenciamento ambiental, observados critérios e parâmetros que garantam a segurança da população e a proteção do meio ambiente, conforme estabelecido nas normas técnicas pertinentes. (Parágrafo acrescido com redação dada pela Lei nº 10.932, de 3.8.2004)\n art4_par4 [Paragrafo]: § 4º No caso de lotes integrantes de condomínio de lotes, poderão ser instituídas limitações administrativas e direitos reais sobre coisa alheia em benefício do poder público, da população em geral e da proteção da paisagem urbana, tais como servidões de passagem, usufrutos e restrições à construção de muros. (Parágrafo acrescido pela Lei nº 13.465, de 11.7.2017)\n art4_par5 [Paragrafo]: § 5º As edificações localizadas nas áreas contíguas às faixas de domínio público dos trechos de rodovia que atravessem perímetros urbanos ou áreas urbanizadas passíveis de serem incluídas em perímetro urbano, desde que construídas até a data de promulgação deste parágrafo, ficam dispensadas da observância da exigência prevista no inciso III do caput deste artigo, salvo por ato devidamente fundamentado do poder público municipal ou distrital. (Parágrafo acrescido pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019)\n art4_par6 [Paragrafo]: § 6º (VETADO na Lei nº 14.285, de 29.12.2021)\n art4_par7 [Paragrafo]: § 7º (VETADO na Lei nº 14.285, de 29.12.2021)\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_6766_19791219#4` | CPT | base | `art4_cpt` | 69–80 | 755 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_6766_19791219#48` | PAR | base | `art4_par1` | 81–82 | 166 | | ✓ | ✓ | | |\n| `lei_6766_19791219#c48` | PAR | caput | `art4_par1` | 81–82 | 184 | | | | ✓ | ✓ |\n| `lei_6766_19791219#49` | PAR | base | `art4_par2` | 83–84 | 79 | | ✓ | ✓ | | |\n| `lei_6766_19791219#c49` | PAR | caput | `art4_par2` | 83–84 | 97 | | | | ✓ | ✓ |\n| `lei_6766_19791219#50` | PAR | base | `art4_par3` | 85–86 | 162 | | ✓ | ✓ | | |\n| `lei_6766_19791219#c50` | PAR | caput | `art4_par3` | 85–86 | 180 | | | | ✓ | ✓ |\n| `lei_6766_19791219#51` | PAR | base | `art4_par4` | 87–88 | 164 | | ✓ | ✓ | | |\n| `lei_6766_19791219#c51` | PAR | caput | `art4_par4` | 87–88 | 182 | | | | ✓ | ✓ |\n| `lei_6766_19791219#52` | PAR | base | `art4_par5` | 89–90 | 225 | | ✓ | ✓ | | |\n| `lei_6766_19791219#c52` | PAR | caput | `art4_par5` | 89–90 | 243 | | | | ✓ | ✓ |\n| `lei_6766_19791219#53` | PAR | base | `art4_par6` | 91–92 | 83 | | ✓ | ✓ | | |\n| `lei_6766_19791219#c53` | PAR | caput | `art4_par6` | 91–92 | 101 | | | | ✓ | ✓ |\n| `lei_6766_19791219#54` | PAR | base | `art4_par7` | 93–94 | 83 | | ✓ | ✓ | | |\n| `lei_6766_19791219#c54` | PAR | caput | `art4_par7` | 93–94 | 101 | | | | ✓ | ✓ |\n| `lei_6766_19791219#148` | ART | base | `art4_cpt;art4_par1;art4_par2;art4_par3` | 69–86 | 1009 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `lei_6766_19791219#149` | ART | base | `art4_par4;art4_par5;art4_par6;art4_par7` | 87–94 | 420 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `lei_6766_19791219#232` | INC | base | `art4_cpt_inc1` | 70–71 | 167 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_6766_19791219#233` | INC | base | `art4_cpt_inc2` | 72–73 | 170 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_6766_19791219#234` | INC | base | `art4_cpt_inc3` | 74–75 | 337 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_6766_19791219#235` | INC | base | `art4_cpt_inc3-2` | 76–77 | 248 | | ✓ | ✓ | ✓ | ✓ |\n| `lei_6766_19791219#236` | INC | base | `art4_cpt_inc4` | 78–79 | 109 | | ✓ | ✓ | ✓ | ✓ |\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_6766_19791219#214` | CAP | base | `cap2` | 67–102 | 1481 | | | ✓ | | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`lei_6766_19791219#4` (CPT, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: I – as áreas destinadas a sistemas de circulação, a implantação de equipamento urbano e comunitário, bem como a espaços livres de uso público, serão proporcionais à densidade de ocupação prevista pelo plano diretor ou aprovada por lei municipal para a zona em que se situem. (Inciso com redação dada pela Lei nº 9.785, de 29.1.1999) II – os lotes terão área mínima de 125 m2 (cento e vinte e cinco metros quadrados) e frente mínima de 5 (cinco) metros, salvo quando a legislação estadual ou municipal determinar maiores exigências, ou quando o loteamento se destinar a urbanização específica ou edificação de conjuntos habitacionais de interesse social, previamente aprovados pelos órgãos públicos competentes; III – ao longo das faixas de domínio público das rodovias, a reserva de faixa não edificável de, no mínimo, 15 (quinze) metros de cada lado poderá ser reduzida por lei municipal ou distrital que aprovar o instrumento do planejamento territorial, até o limite mínimo de 5 (cinco) metros de cada lado. (Inciso com redação dada pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019) III-A. - ao longo da faixa de domínio das ferrovias, será obrigatória a reserva de uma faixa não edificável de, no mínimo, 15 (quinze) metros de cada lado; (Inciso acrescido pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019, com redação dada pela Lei nº 14.285, de 29.12.2021) III-B – ao longo das águas correntes e dormentes, as áreas de faixas não edificáveis deverão respeitar a lei municipal ou distrital que aprovar o instrumento de planejamento territorial e que definir e regulamentar a largura das faixas marginais de cursos d´água naturais em área urbana consolidada, nos termos da Lei nº 12.651, de 25 de maio de 2012, com obrigatoriedade de reserva de uma faixa não edificável para cada trecho de margem, indicada em diagnóstico socioambiental elaborado pelo Município; (Inciso acrescido pela Lei nº 14.285, de 29.12.2021) IV – as vias de loteamento deverão articular-se com as vias adjacentes oficiais, existentes ou projetadas, e harmonizar-se com a topografia local.\n```\n`lei_6766_19791219#48` (PAR, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º § 1º A legislação municipal definirá, para cada zona em que se divida o território do Município, os usos permitidos e os índices urbanísticos de parcelamento e ocupação do solo, que incluirão, obrigatoriamente, as áreas mínimas e máximas de lotes e os coeficientes máximos de aproveitamento. (Parágrafo com redação dada pela Lei nº 9.785, de 29.1.1999)\n```\n`lei_6766_19791219#c48` (PAR, caput):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: § 1º A legislação municipal definirá, para cada zona em que se divida o território do Município, os usos permitidos e os índices urbanísticos de parcelamento e ocupação do solo, que incluirão, obrigatoriamente, as áreas mínimas e máximas de lotes e os coeficientes máximos de aproveitamento. (Parágrafo com redação dada pela Lei nº 9.785, de 29.1.1999)\n```\n`lei_6766_19791219#49` (PAR, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º § 2º Consideram-se comunitários os equipamentos públicos de educação, cultura, saúde, lazer e similares.\n```\n`lei_6766_19791219#c49` (PAR, caput):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: § 2º Consideram-se comunitários os equipamentos públicos de educação, cultura, saúde, lazer e similares.\n```\n`lei_6766_19791219#50` (PAR, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º § 3º Se necessária, a reserva de faixa não-edificável vinculada a dutovias será exigida no âmbito do respectivo licenciamento ambiental, observados critérios e parâmetros que garantam a segurança da população e a proteção do meio ambiente, conforme estabelecido nas normas técnicas pertinentes. (Parágrafo acrescido com redação dada pela Lei nº 10.932, de 3.8.2004)\n```\n`lei_6766_19791219#c50` (PAR, caput):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: § 3º Se necessária, a reserva de faixa não-edificável vinculada a dutovias será exigida no âmbito do respectivo licenciamento ambiental, observados critérios e parâmetros que garantam a segurança da população e a proteção do meio ambiente, conforme estabelecido nas normas técnicas pertinentes. (Parágrafo acrescido com redação dada pela Lei nº 10.932, de 3.8.2004)\n```\n`lei_6766_19791219#51` (PAR, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º § 4º No caso de lotes integrantes de condomínio de lotes, poderão ser instituídas limitações administrativas e direitos reais sobre coisa alheia em benefício do poder público, da população em geral e da proteção da paisagem urbana, tais como servidões de passagem, usufrutos e restrições à construção de muros. (Parágrafo acrescido pela Lei nº 13.465, de 11.7.2017)\n```\n`lei_6766_19791219#c51` (PAR, caput):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: § 4º No caso de lotes integrantes de condomínio de lotes, poderão ser instituídas limitações administrativas e direitos reais sobre coisa alheia em benefício do poder público, da população em geral e da proteção da paisagem urbana, tais como servidões de passagem, usufrutos e restrições à construção de muros. (Parágrafo acrescido pela Lei nº 13.465, de 11.7.2017)\n```\n`lei_6766_19791219#52` (PAR, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º § 5º As edificações localizadas nas áreas contíguas às faixas de domínio público dos trechos de rodovia que atravessem perímetros urbanos ou áreas urbanizadas passíveis de serem incluídas em perímetro urbano, desde que construídas até a data de promulgação deste parágrafo, ficam dispensadas da observância da exigência prevista no inciso III do caput deste artigo, salvo por ato devidamente fundamentado do poder público municipal ou distrital. (Parágrafo acrescido pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019)\n```\n`lei_6766_19791219#c52` (PAR, caput):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: § 5º As edificações localizadas nas áreas contíguas às faixas de domínio público dos trechos de rodovia que atravessem perímetros urbanos ou áreas urbanizadas passíveis de serem incluídas em perímetro urbano, desde que construídas até a data de promulgação deste parágrafo, ficam dispensadas da observância da exigência prevista no inciso III do caput deste artigo, salvo por ato devidamente fundamentado do poder público municipal ou distrital. (Parágrafo acrescido pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019)\n```\n`lei_6766_19791219#53` (PAR, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º § 6º (VETADO na Lei nº 14.285, de 29.12.2021)\n```\n`lei_6766_19791219#c53` (PAR, caput):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: § 6º (VETADO na Lei nº 14.285, de 29.12.2021)\n```\n`lei_6766_19791219#54` (PAR, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º § 7º (VETADO na Lei nº 14.285, de 29.12.2021)\n```\n`lei_6766_19791219#c54` (PAR, caput):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: § 7º (VETADO na Lei nº 14.285, de 29.12.2021)\n```\n`lei_6766_19791219#148` (ART, base, part 1/2):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: I – as áreas destinadas a sistemas de circulação, a implantação de equipamento urbano e comunitário, bem como a espaços livres de uso público, serão proporcionais à densidade de ocupação prevista pelo plano diretor ou aprovada por lei municipal para a zona em que se situem. (Inciso com redação dada pela Lei nº 9.785, de 29.1.1999) II – os lotes terão área mínima de 125 m2 (cento e vinte e cinco metros quadrados) e frente mínima de 5 (cinco) metros, salvo quando a legislação estadual ou municipal determinar maiores exigências, ou quando o loteamento se destinar a urbanização específica ou edificação de conjuntos habitacionais de interesse social, previamente aprovados pelos órgãos públicos competentes; III – ao longo das faixas de domínio público das rodovias, a reserva de faixa não edificável de, no mínimo, 15 (quinze) metros de cada lado poderá ser reduzida por lei municipal ou distrital que aprovar o instrumento do planejamento territorial, até o limite mínimo de 5 (cinco) metros de cada lado. (Inciso com redação dada pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019) III-A. - ao longo da faixa de domínio das ferrovias, será obrigatória a reserva de uma faixa não edificável de, no mínimo, 15 (quinze) metros de cada lado; (Inciso acrescido pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019, com redação dada pela Lei nº 14.285, de 29.12.2021) III-B – ao longo das águas correntes e dormentes, as áreas de faixas não edificáveis deverão respeitar a lei municipal ou distrital que aprovar o instrumento de planejamento territorial e que definir e regulamentar a largura das faixas marginais de cursos d´água naturais em área urbana consolidada, nos termos da Lei nº 12.651, de 25 de maio de 2012, com obrigatoriedade de reserva de uma faixa não edificável para cada trecho de margem, indicada em diagnóstico socioambiental elaborado pelo Município; (Inciso acrescido pela Lei nº 14.285, de 29.12.2021) IV – as vias de loteamento deverão articular-se com as vias adjacentes oficiais, existentes ou projetadas, e harmonizar-se com a topografia local. § 1º A legislação municipal definirá, para cada zona em que se divida o território do Município, os usos permitidos e os índices urbanísticos de parcelamento e ocupação do solo, que incluirão, obrigatoriamente, as áreas mínimas e máximas de lotes e os coeficientes máximos de aproveitamento. (Parágrafo com redação dada pela Lei nº 9.785, de 29.1.1999) § 2º Consideram-se comunitários os equipamentos públicos de educação, cultura, saúde, lazer e similares. § 3º Se necessária, a reserva de faixa não-edificável vinculada a dutovias será exigida no âmbito do respectivo licenciamento ambiental, observados critérios e parâmetros que garantam a segurança da população e a proteção do meio ambiente, conforme estabelecido nas normas técnicas pertinentes. (Parágrafo acrescido com redação dada pela Lei nº 10.932, de 3.8.2004)\n```\n`lei_6766_19791219#149` (ART, base, part 2/2):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: § 4º No caso de lotes integrantes de condomínio de lotes, poderão ser instituídas limitações administrativas e direitos reais sobre coisa alheia em benefício do poder público, da população em geral e da proteção da paisagem urbana, tais como servidões de passagem, usufrutos e restrições à construção de muros. (Parágrafo acrescido pela Lei nº 13.465, de 11.7.2017) § 5º As edificações localizadas nas áreas contíguas às faixas de domínio público dos trechos de rodovia que atravessem perímetros urbanos ou áreas urbanizadas passíveis de serem incluídas em perímetro urbano, desde que construídas até a data de promulgação deste parágrafo, ficam dispensadas da observância da exigência prevista no inciso III do caput deste artigo, salvo por ato devidamente fundamentado do poder público municipal ou distrital. (Parágrafo acrescido pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019) § 6º (VETADO na Lei nº 14.285, de 29.12.2021) § 7º (VETADO na Lei nº 14.285, de 29.12.2021)\n```\n`lei_6766_19791219#232` (INC, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: I – as áreas destinadas a sistemas de circulação, a implantação de equipamento urbano e comunitário, bem como a espaços livres de uso público, serão proporcionais à densidade de ocupação prevista pelo plano diretor ou aprovada por lei municipal para a zona em que se situem. (Inciso com redação dada pela Lei nº 9.785, de 29.1.1999)\n```\n`lei_6766_19791219#233` (INC, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: II – os lotes terão área mínima de 125 m2 (cento e vinte e cinco metros quadrados) e frente mínima de 5 (cinco) metros, salvo quando a legislação estadual ou municipal determinar maiores exigências, ou quando o loteamento se destinar a urbanização específica ou edificação de conjuntos habitacionais de interesse social, previamente aprovados pelos órgãos públicos competentes;\n```\n`lei_6766_19791219#234` (INC, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: III – ao longo das faixas de domínio público das rodovias, a reserva de faixa não edificável de, no mínimo, 15 (quinze) metros de cada lado poderá ser reduzida por lei municipal ou distrital que aprovar o instrumento do planejamento territorial, até o limite mínimo de 5 (cinco) metros de cada lado. (Inciso com redação dada pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019) III-A. - ao longo da faixa de domínio das ferrovias, será obrigatória a reserva de uma faixa não edificável de, no mínimo, 15 (quinze) metros de cada lado; (Inciso acrescido pela Lei nº 13.913, de 25.11.2019, republicada na Edição Extra do DOU de 26.11.2019, com redação dada pela Lei nº 14.285, de 29.12.2021)\n```\n`lei_6766_19791219#235` (INC, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: III-B – ao longo das águas correntes e dormentes, as áreas de faixas não edificáveis deverão respeitar a lei municipal ou distrital que aprovar o instrumento de planejamento territorial e que definir e regulamentar a largura das faixas marginais de cursos d´água naturais em área urbana consolidada, nos termos da Lei nº 12.651, de 25 de maio de 2012, com obrigatoriedade de reserva de uma faixa não edificável para cada trecho de margem, indicada em diagnóstico socioambiental elaborado pelo Município; (Inciso acrescido pela Lei nº 14.285, de 29.12.2021)\n```\n`lei_6766_19791219#236` (INC, base):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: IV – as vias de loteamento deverão articular-se com as vias adjacentes oficiais, existentes ou projetadas, e harmonizar-se com a topografia local.\n```\n`lei_6766_19791219#214` (CAP, 1481 tokens, shortened):\n```text\n[ LEI Nº 6.766, DE 19 DE DEZEMBRO DE 1979 | Dispõe sobre o parcelamento do solo urbano e dá outras providências. ] CAPÍTULO II DOS REQUISITOS URBANÍSTICOS PARA LOTEAMENTO Art. 4º Os loteamentos deverão atender, pelo menos, aos seguintes requisitos: I – as áreas destinadas a sistemas de circulação, a implantação de equipamento urbano e comunitário, bem como a espaços livres de uso público, serão proporcionais à densidade de ocupação prevista pelo plano diretor ou aprovada por lei municipal para a … [3,815 chars omitted] … a de faixa non aedificandi destinada a equipamentos urbanos. Parágrafo único. Consideram-se urbanos os equipamentos públicos de abastecimento de água, serviços de esgotos, energia elétrica, coletas de águas pluviais, rede telefônica e gás canalizado.\n```\n\n#### A9. `decreto_9580_20181122.anexo1.xml` — `art483` (article of a category-A annex (articulated annex, e.g. RIR/2018))\n\n- Document: `decreto_9580_20181122` — DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018; cited by 260 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): LIVRO DE – Apuração do Lucro Real ; CAPÍTULO VI – DISPOSIÇÕES ESPECIAIS SOBRE ATIVIDADES DAS PESSOAS JURÍDICAS ; Seção X – Da compra e da venda, do loteamento, da incorporação, da construção e da reforma de imóveis Determinação do custo; source interval Num 6704–6713.\n\n**LexML parse** (`id [element]: Rotulo + own text`; «…» = quoted amendment text):\n\n```text\nart483 [Artigo]: Art. 483.\n art483_cpt [Caput]: Se a venda for contratada antes de completado o empreendimento, o contribuinte poderá computar no custo do imóvel vendido, além dos custos pagos, incorridos ou contratados, os orçados para a conclusão das obras ou dos melhoramentos a que estiver contratualmente obrigado a realizar ( Decreto-Lei nº 1.598, de 1977, art. 28, caput ).\n art483_par1 [Paragrafo]: § 1º O custo orçado será baseado nos custos usuais no tipo de empreendimento imobiliário ( Decreto-Lei nº 1.598, de 1977, art. 28, § 1º ).\n art483_par2 [Paragrafo]: § 2º Se a execução das obras ou dos melhoramentos a que se obrigou o contribuinte se estender além do período de apuração da venda e o custo efetivamente realizado for inferior, em mais de quinze por cento, ao custo orçado computado na determinação do lucro bruto, o contribuinte ficará obrigado a pagar juros de mora sobre o valor do imposto postergado pela dedução de custo orçado excedente ao realizado ( Decreto-Lei nº 1.598, de 1977, art. 28, § 2º ).\n art483_par3 [Paragrafo]: § 3º Os juros de mora de que trata o § 2º deverão ser pagos juntamente ao imposto sobre a renda incidente no período de apuração em que tiver terminado a execução das obras ou dos melhoramentos ( Decreto-Lei nº 1.598, de 1977, art. 28, § 3º ).\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `decreto_9580_20181122.anexo1#320` | CPT | base | `art483_cpt` | 6705–6706 | 195 | | ✓ | ✓ | ✓ | ✓ |\n| `decreto_9580_20181122.anexo1#1578` | PAR | base | `art483_par1` | 6707–6708 | 153 | | ✓ | ✓ | | |\n| `decreto_9580_20181122.anexo1#c1578` | PAR | caput | `art483_par1` | 6707–6708 | 253 | | | | ✓ | ✓ |\n| `decreto_9580_20181122.anexo1#1579` | PAR | base | `art483_par2` | 6709–6710 | 237 | | ✓ | ✓ | | |\n| `decreto_9580_20181122.anexo1#c1579` | PAR | caput | `art483_par2` | 6709–6710 | 337 | | | | ✓ | ✓ |\n| `decreto_9580_20181122.anexo1#1580` | PAR | base | `art483_par3` | 6711–6712 | 182 | | ✓ | ✓ | | |\n| `decreto_9580_20181122.anexo1#c1580` | PAR | caput | `art483_par3` | 6711–6712 | 282 | | | | ✓ | ✓ |\n| `decreto_9580_20181122.anexo1#3042` | ART | base | `art483` | 6704–6713 | 482 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `decreto_9580_20181122.anexo1#3926` | SEC | base | `liv4_cap6_sec10` | 6687–6862 | 5498 | | | ✓ | | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`decreto_9580_20181122.anexo1#320` (CPT, base):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Venda anterior ao término do empreendimento Art. 483. Se a venda for contratada antes de completado o empreendimento, o contribuinte poderá computar no custo do imóvel vendido, além dos custos pagos, incorridos ou contratados, os orçados para a conclusão das obras ou dos melhoramentos a que estiver contratualmente obrigado a realizar ( Decreto-Lei nº 1.598, de 1977, art. 28, caput ).\n```\n`decreto_9580_20181122.anexo1#1578` (PAR, base):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Venda anterior ao término do empreendimento Art. 483. § 1º O custo orçado será baseado nos custos usuais no tipo de empreendimento imobiliário ( Decreto-Lei nº 1.598, de 1977, art. 28, § 1º ).\n```\n`decreto_9580_20181122.anexo1#c1578` (PAR, caput):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Venda anterior ao término do empreendimento Art. 483. Se a venda for contratada antes de completado o empreendimento, o contribuinte poderá computar no custo do imóvel vendido, além dos custos pagos, incorridos ou contratados, os orçados para a conclusão das obras ou dos melhoramentos a que estiver contratualmente obrigado a realizar ( Decreto-Lei nº 1.598, de 1977, art. 28, caput ). § 1º O custo orçado será baseado nos custos usuais no tipo de empreendimento imobiliário ( Decreto-Lei nº 1.598, de 1977, art. 28, § 1º ).\n```\n`decreto_9580_20181122.anexo1#1579` (PAR, base):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Venda anterior ao término do empreendimento Art. 483. § 2º Se a execução das obras ou dos melhoramentos a que se obrigou o contribuinte se estender além do período de apuração da venda e o custo efetivamente realizado for inferior, em mais de quinze por cento, ao custo orçado computado na determinação do lucro bruto, o contribuinte ficará obrigado a pagar juros de mora sobre o valor do imposto postergado pela dedução de custo orçado excedente ao realizado ( Decreto-Lei nº 1.598, de 1977, art. 28, § 2º ).\n```\n`decreto_9580_20181122.anexo1#c1579` (PAR, caput):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Venda anterior ao término do empreendimento Art. 483. Se a venda for contratada antes de completado o empreendimento, o contribuinte poderá computar no custo do imóvel vendido, além dos custos pagos, incorridos ou contratados, os orçados para a conclusão das obras ou dos melhoramentos a que estiver contratualmente obrigado a realizar ( Decreto-Lei nº 1.598, de 1977, art. 28, caput ). § 2º Se a execução das obras ou dos melhoramentos a que se obrigou o contribuinte se estender além do período de apuração da venda e o custo efetivamente realizado for inferior, em mais de quinze por cento, ao custo orçado computado na determinação do lucro bruto, o contribuinte ficará obrigado a pagar juros de mora sobre o valor do imposto postergado pela dedução de custo orçado excedente ao realizado ( Decreto-Lei nº 1.598, de 1977, art. 28, § 2º ).\n```\n`decreto_9580_20181122.anexo1#1580` (PAR, base):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Venda anterior ao término do empreendimento Art. 483. § 3º Os juros de mora de que trata o § 2º deverão ser pagos juntamente ao imposto sobre a renda incidente no período de apuração em que tiver terminado a execução das obras ou dos melhoramentos ( Decreto-Lei nº 1.598, de 1977, art. 28, § 3º ).\n```\n`decreto_9580_20181122.anexo1#c1580` (PAR, caput):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Venda anterior ao término do empreendimento Art. 483. Se a venda for contratada antes de completado o empreendimento, o contribuinte poderá computar no custo do imóvel vendido, além dos custos pagos, incorridos ou contratados, os orçados para a conclusão das obras ou dos melhoramentos a que estiver contratualmente obrigado a realizar ( Decreto-Lei nº 1.598, de 1977, art. 28, caput ). § 3º Os juros de mora de que trata o § 2º deverão ser pagos juntamente ao imposto sobre a renda incidente no período de apuração em que tiver terminado a execução das obras ou dos melhoramentos ( Decreto-Lei nº 1.598, de 1977, art. 28, § 3º ).\n```\n`decreto_9580_20181122.anexo1#3042` (ART, base):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Venda anterior ao término do empreendimento Art. 483. Se a venda for contratada antes de completado o empreendimento, o contribuinte poderá computar no custo do imóvel vendido, além dos custos pagos, incorridos ou contratados, os orçados para a conclusão das obras ou dos melhoramentos a que estiver contratualmente obrigado a realizar ( Decreto-Lei nº 1.598, de 1977, art. 28, caput ). § 1º O custo orçado será baseado nos custos usuais no tipo de empreendimento imobiliário ( Decreto-Lei nº 1.598, de 1977, art. 28, § 1º ). § 2º Se a execução das obras ou dos melhoramentos a que se obrigou o contribuinte se estender além do período de apuração da venda e o custo efetivamente realizado for inferior, em mais de quinze por cento, ao custo orçado computado na determinação do lucro bruto, o contribuinte ficará obrigado a pagar juros de mora sobre o valor do imposto postergado pela dedução de custo orçado excedente ao realizado ( Decreto-Lei nº 1.598, de 1977, art. 28, § 2º ). § 3º Os juros de mora de que trata o § 2º deverão ser pagos juntamente ao imposto sobre a renda incidente no período de apuração em que tiver terminado a execução das obras ou dos melhoramentos ( Decreto-Lei nº 1.598, de 1977, art. 28, § 3º ).\n```\n`decreto_9580_20181122.anexo1#3926` (SEC, 5498 tokens, shortened):\n```text\n[ DECRETO Nº 9.580, DE 22 DE NOVEMBRO DE 2018 | Regulamenta a tributação, a fiscalização, a arrecadação e a administração do Imposto sobre a Renda e Proventos de Qualquer Natureza. | Anexo 1 – ANEXO ] Seção X Da compra e da venda, do loteamento, da incorporação, da construção e da reforma de imóveis Determinação do custo Art. 481. O contribuinte que comprar imóvel para venda ou promover empreendimento de desmembramento ou loteamento de terrenos, incorporação imobiliária ou construção de prédio d … [15,731 chars omitted] … mpresa construa unidades habitacionais para vendê-las prontas, o pagamento unificado dos tributos a que se refere o caput será equivalente a um por cento da receita mensal auferida pelo contrato de alienação ( Lei nº 12.024, de 2009, art. 2º, § 7º ).\n```\n\n#### A10. `lei_9504_19970930.anexo1.xml` — `ite6-1` (orphan dispositivo of a category-B annex (DSP))\n\n- Document: `lei_9504_19970930` — LEI Nº 9.504, DE 30 DE SETEMBRO DE 1997; cited by 1 question(s); this article is not cited.\n- Groupings (`agrupadores_rotulos`): —; source interval Num 121–122.\n\n**LexML parse** (the orphan dispositivo, not inside an `Artigo`):\n\n```text\nite6-1 [Item]: 6. DATA DA EMISSÃO - informar a data em que o cheque foi emitido pelo doador, no formato dia, mês e ano;\n```\n\n**Chunks and strategy membership** (✓ = indexed by the strategy):\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `lei_9504_19970930.anexo1#34` | DSP | base | `ite6-1` | 121–122 | 82 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts** (in `chunk_id` order; grouping chunks shortened):\n\n`lei_9504_19970930.anexo1#34` (DSP, base):\n```text\n[ LEI Nº 9.504, DE 30 DE SETEMBRO DE 1997 | Estabelece normas para as eleições. | Anexo 1 – ANEXO ] 6. DATA DA EMISSÃO - informar a data em que o cheque foi emitido pelo doador, no formato dia, mês e ano;\n```\n\n### B. Non-statutory samples\n\n#### B1. `sc_cosit_140_20150605` — unit `pp1_tab1` (ministerio.fazenda_secretaria.receita.federal_solucao.consulta)\n\n- File: `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta_2015-06-05_140.xml`; cited by 1 question(s); the document has 16 chunks; unit heading path: —.\n\n**LexML parse of the unit:**\n\n```text\npp1_tab1 [table ]:\n | natalista, a qual | afirma que o nascituro possui mera expectativa de direito, só fazendo jus à | |\n | personalidade após o nascimento com vida, conforme se depreende da leitura d | | o art. 2º da Lei |\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta_2015-06-05_140#13` | TAB | base | `pp1_tab1` | 27–28 | 215 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta_2015-06-05_140#13` (TAB):\n```text\n[ Solução de Consulta Cosit nº 140, de 5 de junho de 2015 | IMPOSTO SOBRE A RENDA DE PESSOA FÍSICA – IRPF EMENTA: DESPESAS MÉDICAS. FERTILIZAÇÃO IN VITRO. DEDUTIBILIDADE. DECLARAÇÃO DE QUALQUER DOS CÔNJUGES. Os pagamentos efetuados a médicos e a hospitais, assim como as despesas com exames laboratoriais, realizados no âmbito de procedimento de reprodução assistida por fertilização in vitro, devidamente comprovados, são dedutíveis … ] Tabela: natalista, a qual | afirma que o nascituro possui mera expectativa de direito, só fazendo jus à | ; personalidade após o nascimento com vida, conforme se depreende da leitura d | | o art. 2º da Lei\n```\n\n#### B2. `sc_cosit_194_20150805` — unit `pp1_agr4` (ministerio.fazenda_secretaria.receita.federal_solucao.consulta)\n\n- File: `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta_2015-08-05_194.xml`; cited by 3 question(s); the document has 3 chunks; unit heading path: —.\n\n**LexML parse of the unit:**\n\n```text\npp1_agr4 [Agrupamento texto]:\n <p> DISPOSITIVOS LEGAIS: Decreto nº 59.308, de 23 de setembrode 1966; Decreto nº 52.288, de 24 de junho de 1963; Decretonº 27.784, de 16 de fevereiro de 1950; Nota PGFN/CRJ nº 1.549, de3 de dezembro de 2012; REsp nº 1.306.393/DF; Solução de ConsultaCosit nº 64, de 7 de março de 2014.\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta_2015-08-05_194#2` | TXT | base | `pp1_agr4` | 3–4 | 305 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta_2015-08-05_194#2` (TXT):\n```text\n[ SOLUÇÃO DE CONSULTA Nº 194,DE 5 DE AGOSTO DE 2015 | EMENTA: PERITOS DE ASSISTÊNCIA TÉCNICA.AGÊNCIA ESPECIALIZADA DA ONU. A Receita Federal do Brasil está impedida de constituir ouexigir créditos tributários relativos à incidência do IRPF sobre osrendimentos do trabalho recebidos por peritos de assistência técnicacontratados no Brasil para atuarem como consultores da ONU ou desuas Agências Especializadas, nem inscrevê-los em Dívida Ativa daUnião, devendo, ainda, rever de … ] DISPOSITIVOS LEGAIS: Decreto nº 59.308, de 23 de setembrode 1966; Decreto nº 52.288, de 24 de junho de 1963; Decretonº 27.784, de 16 de fevereiro de 1950; Nota PGFN/CRJ nº 1.549, de3 de dezembro de 2012; REsp nº 1.306.393/DF; Solução de ConsultaCosit nº 64, de 7 de março de 2014.\n```\n\n#### B3. `pn_cst_1_19850204` — unit `pp1_agh2_agh2_txt1` (ministerio.fazenda_secretaria.receita.federal_parecer)\n\n- File: `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_parecer_1985-02-04_1.xml`; cited by 1 question(s); the document has 9 chunks; unit heading path: 3. ; 3.2..\n\n**LexML parse of the unit:**\n\n```text\npp1_agh2_agh2_txt1 [Agrupamento texto]:\n <p> Diversamente, porém, ocorre com a \"Nota Promissória Rural\", disciplinada nos artigos 42 e 43 do Decreto-lei nº 167. de 14.02.67. Eis que, tratando-se de promessa de pagamento, está vinculada à operação de venda que lhe deu origem, tanto que os produtos objeto da venda são nela indicados (art. 43, VI DL 167/67). Assim, quando estiver corretamente preenchida e não apresentar contradição com a correspondente \"nota fiscal de produtor rural\", a \"Nota Promissória Rural\" comprova o caráter creditício da operação e, por aplicação de regime financeiro, a receita será apropriada ao resultado do período-base em que efetivamente o vendedor vier a receber o pagamento prometido, o qual poderá ocorrer no desconto antecipado, no vencimento ou posteriormente como nas hipóteses de atraso de pagamento ou até de cobrança judicial.\n <p> À consideração superior.\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_parecer_1985-02-04_1#7` | TXT | base | `pp1_agh2_agh2_txt1` | 13–14 | 318 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_ministerio.fazenda_secretaria.receita.federal_parecer_1985-02-04_1#7` (TXT):\n```text\n[ Parecer Normativo CST nº 1, de 4 de fevereiro de 1985 | A receita correspondente à \"Nota Promissória Rural\" será apropriada ao resultado do ano-base em que efetivamente o vendedor vier a receber o pagamento garantido pelo título. ] 3. > 3.2. Diversamente, porém, ocorre com a \"Nota Promissória Rural\", disciplinada nos artigos 42 e 43 do Decreto-lei nº 167. de 14.02.67. Eis que, tratando-se de promessa de pagamento, está vinculada à operação de venda que lhe deu origem, tanto que os produtos objeto da venda são nela indicados (art. 43, VI DL 167/67). Assim, quando estiver corretamente preenchida e não apresentar contradição com a correspondente \"nota fiscal de produtor rural\", a \"Nota Promissória Rural\" comprova o caráter creditício da operação e, por aplicação de regime financeiro, a receita será apropriada ao resultado do período-base em que efetivamente o vendedor vier a receber o pagamento prometido, o qual poderá ocorrer no desconto antecipado, no vencimento ou posteriormente como nas hipóteses de atraso de pagamento ou até de cobrança judicial. À consideração superior.\n```\n\n#### B4. `adn_cosit_9_19990401` — unit `pp1_agh3_txt1` (ministerio.fazenda_secretaria.receita.federal_ato.declaratorio)\n\n- File: `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_ato.declaratorio_1999-04-01_9.xml`; cited by 3 question(s); the document has 4 chunks; unit heading path: III -.\n\n**LexML parse of the unit:**\n\n```text\npp1_agh3_txt1 [Agrupamento texto]:\n <p> fica revogado o Ato Declaratório Normativo Cosit nº 06, de 12 de março de 1999, publicado no Diário Oficial da União de 15 de março de 1999.\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_ato.declaratorio_1999-04-01_9#4` | TXT | base | `pp1_agh3_txt1` | 7–8 | 107 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_ministerio.fazenda_secretaria.receita.federal_ato.declaratorio_1999-04-01_9#4` (TXT):\n```text\n[ Ato Declaratório Normativo Cosit nº 9, de 1º de abril de 1999 | Dispõe sobre a dedutibilidade das contribuições às entidades de previdência privada. ] III - fica revogado o Ato Declaratório Normativo Cosit nº 06, de 12 de março de 1999, publicado no Diário Oficial da União de 15 de março de 1999.\n```\n\n#### B5. `sci_cosit_5_20130215` — unit `pp1_tab1` (ministerio.fazenda_secretaria.receita.federal_solucao.consulta.interna)\n\n- File: `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta.interna_2013-02-15_5.xml`; cited by 4 question(s); the document has 21 chunks; unit heading path: Fundamentos ; b) ; c).\n\n**LexML parse of the unit:**\n\n```text\npp1_tab1 [table ]:\n | DATA | COTAÇÃO DE COMPRA | COTAÇÃO DE VENDA |\n | 02/06/20XX | 2,42 | 2,50 |\n | 29/06/20XX | 2,80 | 2,88 |\n | 13/10/20XX | 2,00 | 2,03 |\n | 20/12/20XX | 2,10 | 2,18 |\n | 28/12/20XX | 2,30 | 2,38 |\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta.interna_2013-02-15_5#7` | TAB | base | `pp1_tab1` | 15–16 | 296 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_ministerio.fazenda_secretaria.receita.federal_solucao.consulta.interna_2013-02-15_5#7` (TAB):\n```text\n[ Solução de Consulta Interna Cosit nº 5, de 15 de fevereiro de 2013 | Ementa: Aplicação em moeda estrangeira no exterior. Rendimentos auferidos originariamente em Reais. Tributação do Ganho de Capital. Liquidação. Resgate. Crédito de rendimentos. A tributação da variação cambial só ocorre no momento da liquidação ou resgate (parcial ou total) da aplicação financeira, ou seja, no momento em que qualquer montante do capital investido tenha sido movimentado pelo beneficiário. ] Fundamentos > b) > c) Cotações do dólar dos Estados Unidos da América (EUA): Tabela: DATA | COTAÇÃO DE COMPRA | COTAÇÃO DE VENDA ; 02/06/20XX | 2,42 | 2,50 ; 29/06/20XX | 2,80 | 2,88 ; 13/10/20XX | 2,00 | 2,03 ; 20/12/20XX | 2,10 | 2,18 ; 28/12/20XX | 2,30 | 2,38\n```\n\n#### B6. `parecer_pgfncat_1503_2010` — unit `pp1_agrf4` (procuradoria.geral.fazenda.nacional_parecer)\n\n- File: `urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503.xml`; cited by 2 question(s); the document has 24 chunks; unit heading path: —.\n\n**LexML parse of the unit:**\n\n```text\npp1_agrf4 [Agrupamento nota]:\n <p> POR MORTE. RECONHECIMENTO DE UNIÃO ESTÁVEL. RELACIONAMENTO HOMOAFETIVO. POSSIBILIDADE.\n <p> PROVA TESTEMUNHAL ROBUSTA. DEPENDÊNCIA ECONÔMICA PRESUMIDA. CONCESSÃO DO BENEFÍCIO.\n <p> JUROS DE MORA. CORREÇÃO MONETÁRIA. HONORÁRIOS ADVOCATÍCIOS. 1. Remessa oficial, tida por\n <p> interposta, de sentença proferida na vigência da Lei nº 9.469, de 10 de julho de\n <p> 1997. Não incide, na hipótese, os artigos 475, § 2º, do Código de Processo Civil ou\n <p> 13 da Lei nº 10.259/01, em virtude de não ter sido demonstrado que o conteúdo\n <p> econômico do pleito é de valor inferior a 60 salários mínimos. 2. \"A lei, só por si,\n <p> não extingue comportamentos racistas, preconceituosos, discriminatórios ou\n <p> mesmo criminosos, necessitando, antes, de uma conscientização da coletividade\n <p> sobre serem odiosas as condutas assim tipificadas. Não é a falta de uma lei\n <p> específica sobre o reconhecimento das uniões homoafetivas que vai alijar o\n <p> requerente do seu direito de obter, comprovados os requisitos objetivos da união\n <p> (convivência, relação amorosa, dependência econômica e publicidade da condição),\n <p> o reconhecimento da existência de uma união estável propiciadora da pensão por\n <p> morte requestada\" (AC 2002.38.00.043831-2/MG, Rel. Desembargadora Federal\n <p> Neuza Maria Alves da Silva, Segunda Turma, DJ p.25 de 19/01/2007) 3. A\n <p> declaração particular colacionada aos autos, equiparável à prova testemunhal,\n <p> bem como as testemunhas ouvidas em juízo, as fotos do casal, cartões,\n <p> correspondências e títulos bancários com endereço comum, são uníssonos em\n <p> confirmar a relação duradoura de companheirismo entre o autor e seu falecido\n <p> companheiro. 4. A Lei nº. 8.213/91 somente exige início de prova material para fins\n <p> de comprovação de tempo de serviço, não ocorrendo tal exigência para fins de\n <p> comprovação de união estável. No mais, a teor do art. 16, §4º, da Lei 8.213/91, a\n <p> dependência mútua entre companheiros é presumida. 5. Atendidos os requisitos\n <p> indispensáveis à concessão do benefício previdenciário (arts. 74, da Lei 8.213/91), é\n <p> devida a pensão por morte, desde a data do requerimento administrativo. Sentença\n <p> mantida. 6. Os juros de mora de 1% ao mês devem ser contados da citação, no\n <p> tocante às prestações a ela anteriores e, da data do vencimento, para as posteriores.\n <p> Orientação da Primeira Seção e do STJ. 7. A correção monetária incide sobre o\n <p> débito previdenciário, a partir do vencimento de cada prestação, nos termos da Lei\n <p> nº. 6.899, de 8 de abril de 1981, conforme Manual de Orientação de Procedimentos\n <p> para os Cálculos na Justiça Federal. 8. Os honorários de advogado devem ser\n <p> reduzidos para 10% sobre o valor da condenação, correspondente às parcelas\n <p> vencidas até o momento da prolação da sentença, de acordo com a Súmula nº. 111\n <p> do Superior Tribunal de Justiça e artigo 20, § 3º, do CPC. 9. Apelação e remessa\n <p> oficial, tida por interposta, parcialmente providas, na forma dos itens 6 a 8. AC -\n <p> APELAÇÃO CIVEL – 200535000067997 TRF1 e-DJF1 DATA:05/03/2009\n <p> PAGINA:174\n <p> ADMINISTRATIVO E PROCESSUAL CIVIL – MILITAR – PENSÃO POR\n <p> MORTE. COMPANHEIRO - UNIÃO ESTÁVEL HOMOAFETIVA - INTELIGÊNCIA DO ARTIGO 226, CF;\n <p> ART.1723, CC/02 – PRINCÍPIOS\n <p> FUNDAMENTAIS DA DIGNIDADE DA PESSOA HUMANA, DA LIBERDADE,\n <p> DA IGUALDADE, DA NÃO DISCRIMINAÇÃO - INSTRUÇÃO NORMATIVA\n <p> 25/00/INSS – APLICAÇÃO – ISONOMIA - COMPROVAÇÃO – PASEP –\n <p> LEVANTAMENTO DE VALORES – IMPOSSIBILIDADE – INCOMPETÊNCIA\n <p> ABSOLUTA DO JUÍZO - HONORÁRIOS ADVOCATÍCIOS - ART.20, §4º, CPC\n <p> - APRECIAÇÃO EQÜITATIVA DO JUIZ - PRECEDENTES. -Objetivando a\n <p> parte autora, o reconhecimento da união estável que manteve com militar falecido\n <p> -Sr.Luiz Carlos Pinto de Freitas-, e o levantamento dos valores existentes na conta\n <p> do PASEP, ajuizou o presente feito. -Restou o mesmo julgado parcialmente\n <p> procedente, \"para RECONHECER, exclusivamente para fins previdenciários\n <p> junto à Marinha do Brasil, a existência de sociedade de fato entre o Autor e o\n <p> Sr.Luiz Carlos Pinto de Freitas, bem como para CONDENAR a UNIÃO\n <p> FEDERAL a conceder a pensão por morte pleiteada e pagar as parcelas devidas, a\n <p> contar da data do óbito, cujos valores deverão ser corrigidos monetariamente e\n <p> acrescidos de juros de mora no percentual de 0,5% (meio por cento) ao mês (STF,\n <p> Plenário, RE453740/RJ, Rel.Min.Gilmar Mendes, DJ de 24.08.07), estes a partir da\n <p> data da citação, e, em conseqüência, DELARO a nulidade do ato administrativo\n <p> que reconheceu direito à mesma pensão ao segundo réu, Sr.ALARCON\n <p> BARBOSA DE FREITAS, isentando-o de devolução das quantias recebidas até a\n <p> definitiva suspensão dos pagamentos mensais. Faculto à União Federal promover a\n <p> imediata suspensão dos pagamentos mensais referentes à pensão que vem sendo\n <p> paga ao segundo Réu, independentemente do trânsito em julgado da\n <p> sentença.\".Condenada a União Federal na verba honorária de 5% sobre o\n <p> montante devido, e o Alarcon Barbosa de Freitas, em 5% do valor da causa,\n <p> monetariamente atualizado, com custas ex lege. -No que concerne à liberação dos\n <p> valores creditados, em nome do de cujus, na conta do PASEP, nos termos do\n <p> verbete nº 161, da Súmula da jurisprudência do STJ, a competência para autorizar\n <p> levantamento dos valores relativos ao PIS/PASEP e FGTS, em decorrência do\n <p> falecimento do titular da conta, é da Justiça Estadual, pelo que, absoluta\n <p> incompetência do Juízo, como decidido. -\"Há que se aplicar o direito à luz de\n <p> diversos preceitos constitucionais e não apenas atendo-se à interpretação literal do\n <p> art. 226, §3º da Constituição Federal, que não diz respeito ao âmbito\n <p> previdenciário, inserindo-se no capítulo 'Da Família', sendo certo que não houve\n <p> de parte do constituinte, exclusão dos relacionamentos homoafetivos, com vista à\n <p> produção de efeitos no campo do direito previdenciário, configurando-se mera\n <p> lacuna, que deverá ser preenchida a partir de outras fontes do direito\" (STJ, RESP\n <p> 395904, Rel. Min. Hélio Quaglia Barbosa, DJ de 06/02/2006). -Conforme registrado\n <p> pelo STF no julgamento da ADI 3300 MC/DF, o magistério da doutrina, apoiando-\n <p> se em valiosa hermenêutica construtiva, utilizando-se da analogia e invocando\n <p> princípios fundamentais (como os da dignidade da pessoa humana, da liberdade,\n <p> da autodeterminação, da igualdade, do pluralismo, da intimidade, da não-\n <p> discriminação e da busca da felicidade), tem revelado admirável percepção do alto\n <p> significado de que se revestem tanto o reconhecimento do direito personalíssimo à\n <p> orientação sexual, de um lado, quanto a proclamação da legitimidade ético-jurídica\n <p> da união homoafetiva como entidade familiar, de outro, em ordem a permitir que\n <p> se extraiam, em favor de parceiros homossexuais, relevantes conseqüências no\n <p> plano do Direito e na esfera das relações sociais. -\"Uma vez reconhecida, numa\n <p> interpretação dos princípios norteadores da Constituição pátria, a união entre\n <p> homossexuais como possível de ser abarcada dentro do conceito de entidade\n <p> familiar e afastados quaisquer impedimentos de natureza atuarial, deve a relação\n <p> da Previdência para com os casais de mesmo sexo dar-se nos mesmos moldes das\n <p> uniões estáveis entre heterossexuais, devendo ser exigido dos primeiros o mesmo\n <p> que se exige dos segundos para fins de comprovação do vínculo afetivo e\n <p> dependência econômica presumida entre os casais (...), quando do processamento\n <p> dos pedidos de pensão por morte e auxílio-reclusão.\" (Revista do TRF/4ª Região,\n <p> vol. 57/309-348, 310, Rel. Des. Federal João Batista Pinto Silveira - grifei) in STF,\n <p> ADI 3300 MC/DF. -\"(...) O reconhecimento do direito à pensão previdenciária\n <p> para companheiro(a) de homossexual, no RGPS, consubstanciado na Instrução\n <p> Normativa nº 25, de 7 de junho de 2000, editada pelo INSS, pode ser utilizada, por\n <p> analogia, para a concessão de tal benefício aos servidores públicos federais, em\n <p> homenagem ao princípio da isonomia (...)\"(TRF 5ª R. - AC 238.842 - RN - 1ª T. -\n <p> Relª Desª Fed. Margarida Cantarelli - DJU 13.03.2002). -Inexistindo situação\n <p> destoante, in casu, do apreciado, em epígrafe por este Colegiado, o inconformismo\n <p> não tem como prosperar. -Destarte, comungo do mesmo sentir da decisão de piso,\n <p> na medida em que, a meu juízo, o acervo probatório, conforme ali declinado, cuja\n <p> fundamentação, ora se incorpora, bem delineou a sociedade de fato constituída, em\n <p> especial o seguro de vida instituído pelo de cujus em favor do companheiro, ora\n <p> apelado, o que conduz à manutenção do decisum, sob esta vertente. -Quanto ao\n <p> termo inicial para o pagamento da pensão em comento, não há que se falar em\n <p> habilitação tardia, face ao que se extrai dos documentos acostados aos autos\n <p> (fls.59; 72), e como bem explicitado na sentença objurgada, no sentido de que, \"O\n <p> direito do autor retroage à data do óbito, pois requereu administrativamente a\n <p> pensão apenas doze dias após (fl.59), e muito antes do deferimento da pensão em\n <p> favor do segundo Réu, em 02.05.2001 (fl.72). (...).\", pelo que, de rigor a sua\n <p> manutenção, também sob este flanco. -Por derradeiro, por força da remessa\n <p> necessária, no que pertine à verba honorária fixada em desfavor do ente\n <p> federativo, a teor do §4º, do artigo 20, do CPC, sopesados os critérios estabelecidos\n <p> nas alíneas \"a\", \"b\" e \"c\" do parágrafo 3º do citado artigo, e ante a ausência de\n <p> complexidade da vexata quaestio, a reforma, neste aspecto deve ser efetivada, de\n <p> molde a se preservar a regra, arbitrando-se em R$ 1.500,00 (um mil e quinhentos\n <p> reais). -Recurso desprovido, remessa necessária, parcialmente provida. APELRE -\n <p> APELAÇÃO/REEXAME NECESSÁRIO – 464994 TRF2 E-DJF2R -\n <p> Data::05/05/2010 - Página::187/188\"\n <p> 74.\n <p> Fácil antever o resultado provável de eventual judicialização do assunto mercê de\n <p> deferimento administrativo, mormente quando a própria AGU, na condição de representante judicial da\n <p> União e em sede de controle abstrato de constitucionalidade, reconhece direito análogo ao ora\n <p> vindicado. A previsibilidade do desfecho de potencial contencioso jurisdicional permite prevenir os\n <p> ônus que a sucumbência acarretaria em detrimento do princípio da economicidade administrativa.\n <p> V\n <p> 75.\n <p> Sem embargo do acima, mister salientar, por derradeiro, que o art. 226, §3º, da CF/88\n <p> não proíbe o reconhecimento de direitos civis à união de pessoas do mesmo sexo. Limita-se a conferir\n <p> proteção à união estável entre o homem e a mulher como entidade familiar, para efeito de a lei facilitar\n <p> sua conversão em casamento, no que foi seguida pela legislação ordinária.\n <p> 76.\n <p> A tutela do modelo tradicional de família prevista na Lei Maior longe está de constituir\n <p> a chamada \"norma de clausura\", segundo a qual tudo o que não for juridicamente permitido encontra-\n <p> se automaticamente proibido. Isso levaria a compreender que o silêncio equivale a proibição, com\n <p> negação de outras formas de organização familiar, sem atentar para preceptivos de igual ou superior\n <p> valor principiológico espraiados no texto constitucional.\n <p> 77.\n <p> A interpretação isolada do artigo 226, §3º da CF/88 deve ser substituída por uma\n <p> interpretação sistemática, que não pressupõe incompatibilidade entre a união estável entre pessoas do\n <p> mesmo sexo e a união estável entre pessoas de sexos diferentes. Sustenta Luís Roberto Barroso em\n <p> Parecer sobre o tema:\n <p> \"O não reconhecimento jurídico das uniões homoafetivas não beneficia, em\n <p> nenhuma medida, as uniões convencionais e tampouco promove qualquer valor\n <p> constitucionalmente protegido. (...) a referência a homem e mulher não traduz uma\n <p> vedação da extensão do mesmo regime às relações homoafetivas. Extrair desse\n <p> preceito tal conseqüência seria desvirtuar a sua natureza: a de uma norma de\n <p> inclusão. (...) Não se deve interpretar uma regra constitucional contrariando os\n <p> princípios constitucionais e os fins que a justificaram.\" (5 in DIFERENTES, MAS IGUAIS:\n <p> O RECONHECIMENTO JURÍDICO DAS RELAÇÕES HOMOAFETIVAS NO BRASIL, Trabalho desenvolvido com a colaboração de Cláudio Pereira de Souza\n <p> Neto, Eduardo Mendonça e Nelson Nascimento Diz, que participaram da pesquisa e da discussão de idéias e\n <p> de teses.)\n <p> 78.\n <p> A par do art. 226, §3º, \"a Constituição Federal proclama o direito à vida, à\n <p> liberdade, à igualdade e à intimidade (art. 5º, caput) e prevê como objetivo fundamental, a\n <p> promoção do bem de todos, 'sem preconceitos de origem, raça, sexo, cor, idade e quaisquer\n <p> outras formas de discriminação' (art. 3º, IV). Dispõe, ainda, que 'a lei punirá qualquer\n <p> discriminação atentatória dos direitos e liberdades fundamentais' (art. 5º, XLI). Portanto, sua\n <p> intenção é a promoção do bem dos cidadãos, que são livres para ser, rechaçando qualquer forma\n <p> de exclusão social ou tratamento desigual\" (6 TJ/RS, j. 17 nov. 2004, AC 70009550070, Rel. Des. Maria Berenice Dias, apud Luís Roberto Barroso).\n <p> 79.\n <p> O princípio constitucional da dignidade da pessoa humana e da expressa vedação de\n <p> qualquer forma de discriminação sexual constitui impediente jurídico à proscrição do reconhecimento\n <p> de união estável entre pessoas do mesmo sexo, com os efeitos fiscais que lhe são imanentes. As uniões\n <p> homoafetivas são fatos lícitos e relativos à vida privada de cada indivíduo, fugindo à atuação estatal\n <p> intervir na orientação sexual para marginalizar ou excluir do seu manto as relações homoafetivas.\n <p> 80.\n <p> O centro da tutela constitucional não se põe na exclusividade do casamento. Antes\n <p> abarca a pluralidade dos modelos familiares que, fundados ou não no vínculo conjugal, contenham os\n <p> pressupostos para a tutela da dignidade da pessoa humana. Far-se-á ilegítima qualquer interpretação\n <p> restritiva dos núcleos familiares calcada na orientação sexual dos conviventes em desapreço aos\n <p> princípios constitucionais acima aludidos.\n <p> 81.\n <p> Não se entenda, com isso, que ao intérprete se outorga qualquer liberdade nesse mister.\n <p> A revés, encontra-se ele condicionado por todo o contexto constitucional, pelas exigências dos\n <p> princípios fundamentais e pela exegese sistemática e axiológica, suficientemente vigorosas a orientá-lo\n <p> com segurança.\n <p> 82.\n <p> Malgrado se reconheça que determinadas situações estão fora da zona de certeza de um\n <p> termo preciso, o art. 246 da CF há de ser interpretado em consonância com princípios constitucionais\n <p> outros, como o da dignidade da pessoa humana, posto inviável segregar-lhe o núcleo conceitual.\n <p> 84.\n <p> E a Administração tributária, por óbvio, também se subordina aos direitos fundamentais.\n <p> A vinculação da administração fazendária às normas de direitos fundamentais torna nulos os atos\n <p> praticados com ofensa ao sistema desses direitos.\n <p> 85.\n <p> Não se trata, in specie, de exercer juízo de inconstitucionalidade de uma lei e recusar-lhe\n <p> aplicação por entendê-la discordante de um direito fundamental. Mas compreender a lei conforme a\n <p> Constituição, dando-lhe sentido compatível com a norma fundamental.\n <p> VI\n <p> 86.\n <p> Por todo o exposto, conclui-se:\n <p> (i) a expressão companheiro ou companheira não encontra definição na legislação tributária, sendo\n <p> desimportante a sexualidade dos companheiros para aplicação dos arts. 4º, III e 8º, II, \"b\" e \"c\"\n <p> da Lei nº 9.250/95, e 77 do Decreto nº 3.000/99 (RIR/99);\n <p> (ii) as uniões homoafetivas estão compreendidas na polissemia dos arts. 35, II da Lei nº 9.250/95 e\n <p> 77, § 1º, inciso II do Decreto nº 3.000/99, razão pela qual vedado ao intérprete limitar o que a\n <p> lei expressamente não limita;\n <p> (iii) a paridade de tratamento tributário é direito constitucional que interdita qualquer\n <p> exegese fundada na discriminação de gênero. Embora certo que na perspectiva biológica,\n <p> sociológica ou antropológica constituam realidades distintas a união duradoura entre pessoas do\n <p> mesmo sexo e a de duas pessoas de sexo diverso, no domínio tributário a equiparação de\n <p> tratamento é fundamento material de incidência;\n <p> (iv) não se colhe do art. 226, §3º, da CF/88 \"norma de clausura\", a tornar proibido tudo o\n <p> que não estiver literalmente previsto. Além da sua interpretação sistemática com outros\n <p> preceptivos de igual ou superior hierarquia axiológica, o elemento fundamental do art. 246 da\n <p> CF é a família, não o sexo dos parceiros, cujo objetivo foi alargar a cobertura constitucional dos\n <p> direitos fundamentais, não o de restringir ou limitar, implícita ou explicitamente, à união\n <p> heterossexual;\n <p> (v) as relações homoafetivas, à míngua de previsão explícita na legislação tributária, não podem ser\n <p> tratadas como união de vida de 2ª categoria para efeitos fiscais. Não implica isso extravagância\n <p> ou juízo de inconstitucionalidade, mas compreensão da lei tributária conforme a Constituição,\n <p> dando-lhe sentido compatível com a norma fundamental;\n <p> VII\n <p> 87.\n <p> Posto isto, uma vez demonstrado, quantum satis, a viabilidade e procedência do\n <p> requerimento administrativo objeto da Nota Técnica nº 47/2010/COGES/DENOP/SRH/MP, opina-\n <p> se pela juridicidade da inclusão cadastral de companheira homoafetiva como dependente de\n <p> servidora pública federal para efeito de dedução do Imposto de Renda, desde que preenchidos os\n <p> demais requisitos exigíveis à comprovação da união estável disciplinada nos arts. 4º, III e 8º, II, \"b\"\n <p> e \"c\" da Lei nº 9.250/95, e no art. 77 do Decreto nº 3.000/99 (RIR/99).\n <p> É o Parecer jurídico. À consideração superior.\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#14` | TXT | base | `` | 32–33 | 780 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#15` | TXT | base | `` | 34–35 | 344 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#16` | TXT | base | `` | 36–37 | 1010 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#17` | TXT | base | `` | 38–39 | 1022 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#18` | TXT | base | `` | 40–41 | 785 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#19` | TXT | base | `` | 42–43 | 943 | ✓ | ✓ | ✓ | ✓ | ✓ |\n| `urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#20` | TXT | base | `` | 44–45 | 666 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#14` (TXT, part 1/7):\n```text\n[ PARECER PGFN/CAT/Nº 1503//2010 | Requerimento administrativo de servidora federal ] POR MORTE. RECONHECIMENTO DE UNIÃO ESTÁVEL. RELACIONAMENTO HOMOAFETIVO. POSSIBILIDADE. PROVA TESTEMUNHAL ROBUSTA. DEPENDÊNCIA ECONÔMICA PRESUMIDA. CONCESSÃO DO BENEFÍCIO. JUROS DE MORA. CORREÇÃO MONETÁRIA. HONORÁRIOS ADVOCATÍCIOS. 1. Remessa oficial, tida por interposta, de sentença proferida na vigência da Lei nº 9.469, de 10 de julho de 1997. Não incide, na hipótese, os artigos 475, § 2º, do Código de Processo Civil ou 13 da Lei nº 10.259/01, em virtude de não ter sido demonstrado que o conteúdo econômico do pleito é de valor inferior a 60 salários mínimos. 2. \"A lei, só por si, não extingue comportamentos racistas, preconceituosos, discriminatórios ou mesmo criminosos, necessitando, antes, de uma conscientização da coletividade sobre serem odiosas as condutas assim tipificadas. Não é a falta de uma lei específica sobre o reconhecimento das uniões homoafetivas que vai alijar o requerente do seu direito de obter, comprovados os requisitos objetivos da união (convivência, relação amorosa, dependência econômica e publicidade da condição), o reconhecimento da existência de uma união estável propiciadora da pensão por morte requestada\" (AC 2002.38.00.043831-2/MG, Rel. Desembargadora Federal Neuza Maria Alves da Silva, Segunda Turma, DJ p.25 de 19/01/2007) 3. A declaração particular colacionada aos autos, equiparável à prova testemunhal, bem como as testemunhas ouvidas em juízo, as fotos do casal, cartões, correspondências e títulos bancários com endereço comum, são uníssonos em confirmar a relação duradoura de companheirismo entre o autor e seu falecido companheiro. 4. A Lei nº. 8.213/91 somente exige início de prova material para fins de comprovação de tempo de serviço, não ocorrendo tal exigência para fins de comprovação de união estável. No mais, a teor do art. 16, §4º, da Lei 8.213/91, a dependência mútua entre companheiros é presumida. 5. Atendidos os requisitos indispensáveis à concessão do benefício previdenciário (arts. 74, da Lei 8.213/91), é devida a pensão por morte, desde a data do requerimento administrativo. Sentença mantida. 6. Os juros de mora de 1% ao mês devem ser contados da citação, no tocante às prestações a ela anteriores e, da data do vencimento, para as posteriores.\n```\n`urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#15` (TXT, part 2/7):\n```text\n[ PARECER PGFN/CAT/Nº 1503//2010 | Requerimento administrativo de servidora federal ] Orientação da Primeira Seção e do STJ. 7. A correção monetária incide sobre o débito previdenciário, a partir do vencimento de cada prestação, nos termos da Lei nº. 6.899, de 8 de abril de 1981, conforme Manual de Orientação de Procedimentos para os Cálculos na Justiça Federal. 8. Os honorários de advogado devem ser reduzidos para 10% sobre o valor da condenação, correspondente às parcelas vencidas até o momento da prolação da sentença, de acordo com a Súmula nº. 111 do Superior Tribunal de Justiça e artigo 20, § 3º, do CPC. 9. Apelação e remessa oficial, tida por interposta, parcialmente providas, na forma dos itens 6 a 8. AC - APELAÇÃO CIVEL – 200535000067997 TRF1 e-DJF1 DATA:05/03/2009 PAGINA:174 ADMINISTRATIVO E PROCESSUAL CIVIL – MILITAR – PENSÃO POR MORTE. COMPANHEIRO - UNIÃO ESTÁVEL HOMOAFETIVA - INTELIGÊNCIA DO ARTIGO 226, CF;\n```\n`urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#16` (TXT, part 3/7):\n```text\n[ PARECER PGFN/CAT/Nº 1503//2010 | Requerimento administrativo de servidora federal ] ART.1723, CC/02 – PRINCÍPIOS FUNDAMENTAIS DA DIGNIDADE DA PESSOA HUMANA, DA LIBERDADE, DA IGUALDADE, DA NÃO DISCRIMINAÇÃO - INSTRUÇÃO NORMATIVA 25/00/INSS – APLICAÇÃO – ISONOMIA - COMPROVAÇÃO – PASEP – LEVANTAMENTO DE VALORES – IMPOSSIBILIDADE – INCOMPETÊNCIA ABSOLUTA DO JUÍZO - HONORÁRIOS ADVOCATÍCIOS - ART.20, §4º, CPC - APRECIAÇÃO EQÜITATIVA DO JUIZ - PRECEDENTES. -Objetivando a parte autora, o reconhecimento da união estável que manteve com militar falecido -Sr.Luiz Carlos Pinto de Freitas-, e o levantamento dos valores existentes na conta do PASEP, ajuizou o presente feito. -Restou o mesmo julgado parcialmente procedente, \"para RECONHECER, exclusivamente para fins previdenciários junto à Marinha do Brasil, a existência de sociedade de fato entre o Autor e o Sr.Luiz Carlos Pinto de Freitas, bem como para CONDENAR a UNIÃO FEDERAL a conceder a pensão por morte pleiteada e pagar as parcelas devidas, a contar da data do óbito, cujos valores deverão ser corrigidos monetariamente e acrescidos de juros de mora no percentual de 0,5% (meio por cento) ao mês (STF, Plenário, RE453740/RJ, Rel.Min.Gilmar Mendes, DJ de 24.08.07), estes a partir da data da citação, e, em conseqüência, DELARO a nulidade do ato administrativo que reconheceu direito à mesma pensão ao segundo réu, Sr.ALARCON BARBOSA DE FREITAS, isentando-o de devolução das quantias recebidas até a definitiva suspensão dos pagamentos mensais. Faculto à União Federal promover a imediata suspensão dos pagamentos mensais referentes à pensão que vem sendo paga ao segundo Réu, independentemente do trânsito em julgado da sentença.\".Condenada a União Federal na verba honorária de 5% sobre o montante devido, e o Alarcon Barbosa de Freitas, em 5% do valor da causa, monetariamente atualizado, com custas ex lege. -No que concerne à liberação dos valores creditados, em nome do de cujus, na conta do PASEP, nos termos do verbete nº 161, da Súmula da jurisprudência do STJ, a competência para autorizar levantamento dos valores relativos ao PIS/PASEP e FGTS, em decorrência do falecimento do titular da conta, é da Justiça Estadual, pelo que, absoluta incompetência do Juízo, como decidido. -\"Há que se aplicar o direito à luz de diversos preceitos constitucionais e não apenas atendo-se à interpretação literal do art. 226, §3º da Constituição Federal, que não diz respeito ao âmbito previdenciário, inserindo-se no capítulo 'Da Família', sendo certo que não houve de parte do constituinte, exclusão dos relacionamentos homoafetivos, com vista à produção de efeitos no campo do direito previdenciário, configurando-se mera lacuna, que deverá ser preenchida a partir de outras fontes do direito\" (STJ, RESP 395904, Rel. Min. Hélio Quaglia Barbosa, DJ de 06/02/2006). -Conforme registrado pelo STF no julgamento da ADI 3300 MC/DF, o magistério da doutrina, apoiando- se em valiosa hermenêutica construtiva, utilizando-se da analogia e invocando princípios fundamentais (como os da dignidade da pessoa humana, da liberdade,\n```\n`urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#17` (TXT, part 4/7):\n```text\n[ PARECER PGFN/CAT/Nº 1503//2010 | Requerimento administrativo de servidora federal ] da autodeterminação, da igualdade, do pluralismo, da intimidade, da não- discriminação e da busca da felicidade), tem revelado admirável percepção do alto significado de que se revestem tanto o reconhecimento do direito personalíssimo à orientação sexual, de um lado, quanto a proclamação da legitimidade ético-jurídica da união homoafetiva como entidade familiar, de outro, em ordem a permitir que se extraiam, em favor de parceiros homossexuais, relevantes conseqüências no plano do Direito e na esfera das relações sociais. -\"Uma vez reconhecida, numa interpretação dos princípios norteadores da Constituição pátria, a união entre homossexuais como possível de ser abarcada dentro do conceito de entidade familiar e afastados quaisquer impedimentos de natureza atuarial, deve a relação da Previdência para com os casais de mesmo sexo dar-se nos mesmos moldes das uniões estáveis entre heterossexuais, devendo ser exigido dos primeiros o mesmo que se exige dos segundos para fins de comprovação do vínculo afetivo e dependência econômica presumida entre os casais (...), quando do processamento dos pedidos de pensão por morte e auxílio-reclusão.\" (Revista do TRF/4ª Região, vol. 57/309-348, 310, Rel. Des. Federal João Batista Pinto Silveira - grifei) in STF, ADI 3300 MC/DF. -\"(...) O reconhecimento do direito à pensão previdenciária para companheiro(a) de homossexual, no RGPS, consubstanciado na Instrução Normativa nº 25, de 7 de junho de 2000, editada pelo INSS, pode ser utilizada, por analogia, para a concessão de tal benefício aos servidores públicos federais, em homenagem ao princípio da isonomia (...)\"(TRF 5ª R. - AC 238.842 - RN - 1ª T. - Relª Desª Fed. Margarida Cantarelli - DJU 13.03.2002). -Inexistindo situação destoante, in casu, do apreciado, em epígrafe por este Colegiado, o inconformismo não tem como prosperar. -Destarte, comungo do mesmo sentir da decisão de piso, na medida em que, a meu juízo, o acervo probatório, conforme ali declinado, cuja fundamentação, ora se incorpora, bem delineou a sociedade de fato constituída, em especial o seguro de vida instituído pelo de cujus em favor do companheiro, ora apelado, o que conduz à manutenção do decisum, sob esta vertente. -Quanto ao termo inicial para o pagamento da pensão em comento, não há que se falar em habilitação tardia, face ao que se extrai dos documentos acostados aos autos (fls.59; 72), e como bem explicitado na sentença objurgada, no sentido de que, \"O direito do autor retroage à data do óbito, pois requereu administrativamente a pensão apenas doze dias após (fl.59), e muito antes do deferimento da pensão em favor do segundo Réu, em 02.05.2001 (fl.72). (...).\", pelo que, de rigor a sua manutenção, também sob este flanco. -Por derradeiro, por força da remessa necessária, no que pertine à verba honorária fixada em desfavor do ente federativo, a teor do §4º, do artigo 20, do CPC, sopesados os critérios estabelecidos nas alíneas \"a\", \"b\" e \"c\" do parágrafo 3º do citado artigo, e ante a ausência de complexidade da vexata quaestio, a reforma, neste aspecto deve ser efetivada, de molde a se preservar a regra, arbitrando-se em R$ 1.500,00 (um mil e quinhentos\n```\n`urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#18` (TXT, part 5/7):\n```text\n[ PARECER PGFN/CAT/Nº 1503//2010 | Requerimento administrativo de servidora federal ] reais). -Recurso desprovido, remessa necessária, parcialmente provida. APELRE - APELAÇÃO/REEXAME NECESSÁRIO – 464994 TRF2 E-DJF2R - Data::05/05/2010 - Página::187/188\" 74. Fácil antever o resultado provável de eventual judicialização do assunto mercê de deferimento administrativo, mormente quando a própria AGU, na condição de representante judicial da União e em sede de controle abstrato de constitucionalidade, reconhece direito análogo ao ora vindicado. A previsibilidade do desfecho de potencial contencioso jurisdicional permite prevenir os ônus que a sucumbência acarretaria em detrimento do princípio da economicidade administrativa. V 75. Sem embargo do acima, mister salientar, por derradeiro, que o art. 226, §3º, da CF/88 não proíbe o reconhecimento de direitos civis à união de pessoas do mesmo sexo. Limita-se a conferir proteção à união estável entre o homem e a mulher como entidade familiar, para efeito de a lei facilitar sua conversão em casamento, no que foi seguida pela legislação ordinária. 76. A tutela do modelo tradicional de família prevista na Lei Maior longe está de constituir a chamada \"norma de clausura\", segundo a qual tudo o que não for juridicamente permitido encontra- se automaticamente proibido. Isso levaria a compreender que o silêncio equivale a proibição, com negação de outras formas de organização familiar, sem atentar para preceptivos de igual ou superior valor principiológico espraiados no texto constitucional. 77. A interpretação isolada do artigo 226, §3º da CF/88 deve ser substituída por uma interpretação sistemática, que não pressupõe incompatibilidade entre a união estável entre pessoas do mesmo sexo e a união estável entre pessoas de sexos diferentes. Sustenta Luís Roberto Barroso em Parecer sobre o tema: \"O não reconhecimento jurídico das uniões homoafetivas não beneficia, em nenhuma medida, as uniões convencionais e tampouco promove qualquer valor constitucionalmente protegido. (...) a referência a homem e mulher não traduz uma vedação da extensão do mesmo regime às relações homoafetivas. Extrair desse preceito tal conseqüência seria desvirtuar a sua natureza: a de uma norma de inclusão. (...) Não se deve interpretar uma regra constitucional contrariando os princípios constitucionais e os fins que a justificaram.\" (5 in DIFERENTES, MAS IGUAIS: O RECONHECIMENTO JURÍDICO DAS RELAÇÕES HOMOAFETIVAS NO BRASIL, Trabalho desenvolvido com a colaboração de Cláudio Pereira de Souza Neto, Eduardo Mendonça e Nelson Nascimento Diz, que participaram da pesquisa e da discussão de idéias e de teses.)\n```\n`urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#19` (TXT, part 6/7):\n```text\n[ PARECER PGFN/CAT/Nº 1503//2010 | Requerimento administrativo de servidora federal ] 78. A par do art. 226, §3º, \"a Constituição Federal proclama o direito à vida, à liberdade, à igualdade e à intimidade (art. 5º, caput) e prevê como objetivo fundamental, a promoção do bem de todos, 'sem preconceitos de origem, raça, sexo, cor, idade e quaisquer outras formas de discriminação' (art. 3º, IV). Dispõe, ainda, que 'a lei punirá qualquer discriminação atentatória dos direitos e liberdades fundamentais' (art. 5º, XLI). Portanto, sua intenção é a promoção do bem dos cidadãos, que são livres para ser, rechaçando qualquer forma de exclusão social ou tratamento desigual\" (6 TJ/RS, j. 17 nov. 2004, AC 70009550070, Rel. Des. Maria Berenice Dias, apud Luís Roberto Barroso). 79. O princípio constitucional da dignidade da pessoa humana e da expressa vedação de qualquer forma de discriminação sexual constitui impediente jurídico à proscrição do reconhecimento de união estável entre pessoas do mesmo sexo, com os efeitos fiscais que lhe são imanentes. As uniões homoafetivas são fatos lícitos e relativos à vida privada de cada indivíduo, fugindo à atuação estatal intervir na orientação sexual para marginalizar ou excluir do seu manto as relações homoafetivas. 80. O centro da tutela constitucional não se põe na exclusividade do casamento. Antes abarca a pluralidade dos modelos familiares que, fundados ou não no vínculo conjugal, contenham os pressupostos para a tutela da dignidade da pessoa humana. Far-se-á ilegítima qualquer interpretação restritiva dos núcleos familiares calcada na orientação sexual dos conviventes em desapreço aos princípios constitucionais acima aludidos. 81. Não se entenda, com isso, que ao intérprete se outorga qualquer liberdade nesse mister. A revés, encontra-se ele condicionado por todo o contexto constitucional, pelas exigências dos princípios fundamentais e pela exegese sistemática e axiológica, suficientemente vigorosas a orientá-lo com segurança. 82. Malgrado se reconheça que determinadas situações estão fora da zona de certeza de um termo preciso, o art. 246 da CF há de ser interpretado em consonância com princípios constitucionais outros, como o da dignidade da pessoa humana, posto inviável segregar-lhe o núcleo conceitual. 84. E a Administração tributária, por óbvio, também se subordina aos direitos fundamentais. A vinculação da administração fazendária às normas de direitos fundamentais torna nulos os atos praticados com ofensa ao sistema desses direitos. 85. Não se trata, in specie, de exercer juízo de inconstitucionalidade de uma lei e recusar-lhe aplicação por entendê-la discordante de um direito fundamental. Mas compreender a lei conforme a Constituição, dando-lhe sentido compatível com a norma fundamental. VI 86. Por todo o exposto, conclui-se: (i) a expressão companheiro ou companheira não encontra definição na legislação tributária, sendo desimportante a sexualidade dos companheiros para aplicação dos arts. 4º, III e 8º, II, \"b\" e \"c\" da Lei nº 9.250/95, e 77 do Decreto nº 3.000/99 (RIR/99);\n```\n`urn_lex_br_procuradoria.geral.fazenda.nacional_parecer_2010_1503#20` (TXT, part 7/7):\n```text\n[ PARECER PGFN/CAT/Nº 1503//2010 | Requerimento administrativo de servidora federal ] (ii) as uniões homoafetivas estão compreendidas na polissemia dos arts. 35, II da Lei nº 9.250/95 e 77, § 1º, inciso II do Decreto nº 3.000/99, razão pela qual vedado ao intérprete limitar o que a lei expressamente não limita; (iii) a paridade de tratamento tributário é direito constitucional que interdita qualquer exegese fundada na discriminação de gênero. Embora certo que na perspectiva biológica, sociológica ou antropológica constituam realidades distintas a união duradoura entre pessoas do mesmo sexo e a de duas pessoas de sexo diverso, no domínio tributário a equiparação de tratamento é fundamento material de incidência; (iv) não se colhe do art. 226, §3º, da CF/88 \"norma de clausura\", a tornar proibido tudo o que não estiver literalmente previsto. Além da sua interpretação sistemática com outros preceptivos de igual ou superior hierarquia axiológica, o elemento fundamental do art. 246 da CF é a família, não o sexo dos parceiros, cujo objetivo foi alargar a cobertura constitucional dos direitos fundamentais, não o de restringir ou limitar, implícita ou explicitamente, à união heterossexual; (v) as relações homoafetivas, à míngua de previsão explícita na legislação tributária, não podem ser tratadas como união de vida de 2ª categoria para efeitos fiscais. Não implica isso extravagância ou juízo de inconstitucionalidade, mas compreensão da lei tributária conforme a Constituição, dando-lhe sentido compatível com a norma fundamental; VII 87. Posto isto, uma vez demonstrado, quantum satis, a viabilidade e procedência do requerimento administrativo objeto da Nota Técnica nº 47/2010/COGES/DENOP/SRH/MP, opina- se pela juridicidade da inclusão cadastral de companheira homoafetiva como dependente de servidora pública federal para efeito de dedução do Imposto de Renda, desde que preenchidos os demais requisitos exigíveis à comprovação da união estável disciplinada nos arts. 4º, III e 8º, II, \"b\" e \"c\" da Lei nº 9.250/95, e no art. 77 do Decreto nº 3.000/99 (RIR/99). É o Parecer jurídico. À consideração superior.\n```\n\n#### B7. `decreto_59309_19660923` — unit `pp1_agrf2` (federal_decreto)\n\n- File: `urn_lex_br_federal_decreto_1966-09-23_59309.xml`; cited by 1 question(s); the document has 16 chunks; unit heading path: —.\n\n**LexML parse of the unit:**\n\n```text\npp1_agrf2 [Agrupamento nota]:\n <p> H. Castello Branco\n <p> M. Pio Corrêa\n <p> ACÔRDO SÔBRE PRIVILÉGIOS E IMUNIDADES DA AGÊNCIA INTERNACIONAL DE ENERGIA ATÔMICA.\n <p> CONSIDERANDO que o parágrafo C do Artigo XV do Estatuto da Agência Internacional de Energia Atômica dispõe que a capacidade jurídica e os privilégios e imunidades mencionados no referido artigo devem ser definidos em um ou mais acôrdos distintos que serão concluídos entre a Agência representada para êste fim pelo Diretor-Geral que procederá de acôrdo com as instruções do Conselho de governadores e seus Membros;\n <p> CONSIDERANDO que, de acôrdo com o disposto no artigo XVI do Estatuto, foi adotado um acôrdo que regula as relações entre a Agência e a Organização das Nações Unidas;\n <p> CONSIDERANDO que a Assembléia Geral da Organização das Nações Unidas desejando a unificação, na medida do possível, dos privilégios e imunidades de que gozam a Organização das Nações Unidas e as diversas instituições que mantém relações com a mencionada Organização, adotou a Convenção sôbre os privilégios e imunidades das agências especializadas e que vários Estados Membros da Organização das Nações Unidas aderiram à mencionada Convenção;\n <p> O Conselho de Governadores\n <p> 1. Aprovou, sem obrigar os governos representados no Conselho, o seguinte texto, que, de uma maneira geral, repete as disposições da Convenção sôbre os privilégios e imunidades das agências especializadas.\n <p> 2. Convida os Estados Membros da Agência a examinar êste acôrdo e se o julgar oportuno, a aceitá-lo.\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_federal_decreto_1966-09-23_59309#3` | TXT | base | `pp1_agrf2` | 5–6 | 511 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_federal_decreto_1966-09-23_59309#3` (TXT):\n```text\n[ DECRETO Nº 59.309, DE 23 DE SETEMBRO DE 1966. | Promulga o Acôrdo sôbre Privilégios e Imunidades da Agência Internacional de Energia Atômica. ] H. Castello Branco M. Pio Corrêa ACÔRDO SÔBRE PRIVILÉGIOS E IMUNIDADES DA AGÊNCIA INTERNACIONAL DE ENERGIA ATÔMICA. CONSIDERANDO que o parágrafo C do Artigo XV do Estatuto da Agência Internacional de Energia Atômica dispõe que a capacidade jurídica e os privilégios e imunidades mencionados no referido artigo devem ser definidos em um ou mais acôrdos distintos que serão concluídos entre a Agência representada para êste fim pelo Diretor-Geral que procederá de acôrdo com as instruções do Conselho de governadores e seus Membros; CONSIDERANDO que, de acôrdo com o disposto no artigo XVI do Estatuto, foi adotado um acôrdo que regula as relações entre a Agência e a Organização das Nações Unidas; CONSIDERANDO que a Assembléia Geral da Organização das Nações Unidas desejando a unificação, na medida do possível, dos privilégios e imunidades de que gozam a Organização das Nações Unidas e as diversas instituições que mantém relações com a mencionada Organização, adotou a Convenção sôbre os privilégios e imunidades das agências especializadas e que vários Estados Membros da Organização das Nações Unidas aderiram à mencionada Convenção; O Conselho de Governadores 1. Aprovou, sem obrigar os governos representados no Conselho, o seguinte texto, que, de uma maneira geral, repete as disposições da Convenção sôbre os privilégios e imunidades das agências especializadas. 2. Convida os Estados Membros da Agência a examinar êste acôrdo e se o julgar oportuno, a aceitá-lo.\n```\n\n#### B8. `declaração_de_imposto_de_renda_retido_na_fonte_DIRF` — unit `pp1_agh2_txt1` (servico)\n\n- File: `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_servico_2026_dirf.xml`; cited by 1 question(s); the document has 6 chunks; unit heading path: Etapas para a realização deste serviço.\n\n**LexML parse of the unit:**\n\n```text\npp1_agh2_txt1 [Agrupamento texto]:\n <p> Preencher declaração\n <p> Baixe o programa que corresponde ao exercício da declaração e preencha as informações que devem ser declaradas à Receita Federal.\n <p> Canais de prestação\n <p> Web :\n <p> Baixar o programa\n <p> Tempo de duração da etapa\n <p> Atendimento imediato\n <p> Enviar a declaração à Receita Federal\n <p> Após o preenchimento, grave a declaração e envie à Receita Federal utilizando o programa ReceitaNet.\n <p> O ReceitaNet valida e transmite, via Internet, as declarações de impostos e contribuições federais de pessoas físicas e jurídicas. Os arquivos podem ser transmitidos diariamente das 05 à 01 hora da manhã do dia seguinte (20 horas diárias).\n <p> Canais de prestação\n <p> Web :\n <p> Baixar o ReceitaNet\n <p> Tempo de duração da etapa\n <p> Atendimento imediato\n <p> Acompanhar o processamento da declaração\n <p> Acompanhe o processamento da declaração para verificar a situação da entrega.\n <p> Canais de prestação\n <p> Web :\n <p> Extrato do Processamento da DIRF (Simplificado)\n <p> Web :\n <p> Consultar DIRF\n <p> Tempo de duração da etapa\n <p> Atendimento imediato\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_ministerio.fazenda_secretaria.receita.federal_servico_2026_dirf#4` | TXT | base | `pp1_agh2_txt1` | 7–8 | 283 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_ministerio.fazenda_secretaria.receita.federal_servico_2026_dirf#4` (TXT):\n```text\n[ Declaração de Imposto de Renda Retido na Fonte (DIRF) ] Etapas para a realização deste serviço Preencher declaração Baixe o programa que corresponde ao exercício da declaração e preencha as informações que devem ser declaradas à Receita Federal. Canais de prestação Web : Baixar o programa Tempo de duração da etapa Atendimento imediato Enviar a declaração à Receita Federal Após o preenchimento, grave a declaração e envie à Receita Federal utilizando o programa ReceitaNet. O ReceitaNet valida e transmite, via Internet, as declarações de impostos e contribuições federais de pessoas físicas e jurídicas. Os arquivos podem ser transmitidos diariamente das 05 à 01 hora da manhã do dia seguinte (20 horas diárias). Canais de prestação Web : Baixar o ReceitaNet Tempo de duração da etapa Atendimento imediato Acompanhar o processamento da declaração Acompanhe o processamento da declaração para verificar a situação da entrega. Canais de prestação Web : Extrato do Processamento da DIRF (Simplificado) Web : Consultar DIRF Tempo de duração da etapa Atendimento imediato\n```\n\n#### B9. `sumula_stj_125` — unit `pp1_agh7_agh3_txt1` (superior.tribunal.justica_sumula)\n\n- File: `urn_lex_br_superior.tribunal.justica_sumula_1994-12-06_125.xml`; cited by 1 question(s); the document has 55 chunks; unit heading path: RECURSO ESPECIAL N. 52.208-SP (1994/0023969-6) ; RELATÓRIO.\n\n**LexML parse of the unit:**\n\n```text\npp1_agh7_agh3_txt1 [Agrupamento texto]:\n <p> O Sr. Ministro Demócrito Reinaldo: Leandro Pereira Leite, promotor de justiça da capital do Estado de São Paulo impetrou mandado de segurança contra ato do Secretário da Fazenda daquele Estado, visando a que na indenização das suas férias não gozadas por necessidade do serviço deixasse de incidir o imposto de renda.\n <p> Denegada a segurança, em primeira instância, em grau de apelação, a egrégia Sexta Câmara Civil do Tribunal de Justiça de São Paulo concedeu o mandamus, ao fundamento basilar de que não se configura hipótese de incidência de imposto de renda, porquanto da indenização por férias não gozadas não decorre acréscimo patrimonial (fl s. 259-261).\n <p> Irresignada, a Fazenda Estadual manifesta recurso especial, sob o pálio da letra a do admissivo constitucional, alegando violação ao art. 1º da Lei n. 5.021/1966 (fl s. 317-321).\n <p> Admitido na origem e contra-arrazoado (fl s. 323-326), subiram os autos e me vieram conclusos para julgamento.\n <p> É o relatório.\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `urn_lex_br_superior.tribunal.justica_sumula_1994-12-06_125#47` | TXT | base | `pp1_agh7_agh3_txt1` | 105–106 | 390 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`urn_lex_br_superior.tribunal.justica_sumula_1994-12-06_125#47` (TXT):\n```text\n[ SÚMULA N. 125 | O pagamento de férias não gozadas por necessidade do serviço não está sujeito à incidência do Imposto de Renda. ] RECURSO ESPECIAL N. 52.208-SP (1994/0023969-6) > RELATÓRIO O Sr. Ministro Demócrito Reinaldo: Leandro Pereira Leite, promotor de justiça da capital do Estado de São Paulo impetrou mandado de segurança contra ato do Secretário da Fazenda daquele Estado, visando a que na indenização das suas férias não gozadas por necessidade do serviço deixasse de incidir o imposto de renda. Denegada a segurança, em primeira instância, em grau de apelação, a egrégia Sexta Câmara Civil do Tribunal de Justiça de São Paulo concedeu o mandamus, ao fundamento basilar de que não se configura hipótese de incidência de imposto de renda, porquanto da indenização por férias não gozadas não decorre acréscimo patrimonial (fl s. 259-261). Irresignada, a Fazenda Estadual manifesta recurso especial, sob o pálio da letra a do admissivo constitucional, alegando violação ao art. 1º da Lei n. 5.021/1966 (fl s. 317-321). Admitido na origem e contra-arrazoado (fl s. 323-326), subiram os autos e me vieram conclusos para julgamento. É o relatório.\n```\n\n#### B10. `resol_cgsn_140_20180522` — unit `anexo12_tab3` (category-C annex of a statutory document)\n\n- File: `resol_cgsn_140_20180522.anexo12.xml`; cited by 2 question(s); the document has 4 chunks; unit heading path: —.\n\n**LexML parse of the unit:**\n\n```text\nanexo12_tab3 [table ]:\n | Subclasse | DENOMINAÇÃO |\n | 6431-0/00 | BANCOS MÚLTIPLOS, SEM CARTEIRA COMERCIAL |\n | 6432-8/00 | BANCOS DE INVESTIMENTO |\n | 6433-6/00 | BANCOS DE DESENVOLVIMENTO |\n | 6434-4/00 | AGÊNCIAS DE FOMENTO |\n | 6435-2/01 | SOCIEDADES DE CRÉDITO IMOBILIÁRIO |\n | 6435-2/02 | ASSOCIAÇÕES DE POUPANÇA E EMPRÉSTIMO |\n | 6435-2/03 | COMPANHIAS HIPOTECÁRIAS |\n | 6436-1/00 | SOCIEDADES DE CRÉDITO, FINANCIAMENTO E INVESTIMENTO - FINANCEIRAS |\n | 6437-9/00 | SOCIEDADES DE CRÉDITO AO MICROEMPREENDEDOR |\n | 6438-7/01 | BANCOS DE CÂMBIO |\n | 6438-7/99 | OUTRAS INSTITUIÇÕES DE INTERMEDIAÇÃO NÃO MONETÁRIA NÃO |\n | | ESPECIFICADAS ANTERIORMENTE |\n | 6440-9/00 | ARRENDAMENTO MERCANTIL |\n | 6450-6/00 | SOCIEDADES DE CAPITALIZAÇÃO |\n | 6461-1/00 | HOLDINGS DE INSTITUIÇÕES FINANCEIRAS |\n | 6462-0/00 | HOLDINGS DE INSTITUIÇÕES NÃO FINANCEIRAS |\n | 6463-8/00 | OUTRAS SOCIEDADES DE PARTICIPAÇÃO, EXCETO HOLDINGS |\n | 6470-1/01 | FUNDOS DE INVESTIMENTO, EXCETO PREVIDENCIÁRIOS E IMOBILIÁRIOS |\n | 6470-1/02 | FUNDOS DE INVESTIMENTO PREVIDENCIÁRIOS |\n | 6470-1/03 | FUNDOS DE INVESTIMENTO IMOBILIÁRIOS |\n | 6491-3/00 | SOCIEDADES DE FOMENTO MERCANTIL - FACTORING |\n | 6492-1/00 | SECURITIZAÇÃO DE CRÉDITOS |\n | 6499-9/01 | CLUBES DE INVESTIMENTO |\n | 6499-9/02 | SOCIEDADES DE INVESTIMENTO |\n | 6499-9/03 | FUNDO GARANTIDOR DE CRÉDITO |\n | 6499-9/04 | CAIXAS DE FINANCIAMENTO DE CORPORAÇÕES |\n | 6499-9/05 | CONCESSÃO DE CRÉDITO PELAS OSCIP |\n | 6499-9/99 | OUTRAS ATIVIDADES DE SERVIÇOS FINANCEIROS NÃO ESPECIFICADAS |\n | | ANTERIORMENTE |\n | 6511-1/01 | SOCIEDADE SEGURADORA DE SEGUROS VIDA |\n | 6511-1/02 | PLANOS DE AUXÍLIO-FUNERAL |\n | 6512-0/00 | SOCIEDADE SEGURADORA DE SEGUROS NÃO VIDA |\n | 6520-1/00 | SOCIEDADE SEGURADORA DE SEGUROS SAÚDE |\n | 6530-8/00 | RESSEGUROS |\n | 6541-3/00 | PREVIDÊNCIA COMPLEMENTAR FECHADA |\n```\n\n**Chunks and strategy membership:**\n\n| chunk_id | Tipo | variante | cobre_ids | Num | tokens | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---:|---|---|---|---|---|\n| `resol_cgsn_140_20180522.anexo12#2` | TAB | base | `anexo12_tab3` | 3–4 | 988 | ✓ | ✓ | ✓ | ✓ | ✓ |\n\n**Chunk texts:**\n\n`resol_cgsn_140_20180522.anexo12#2` (TAB):\n```text\n[ RESOLUÇÃO Nº 140, DE 22 DE MAIO DE 2018 | Dispõe sobre o Regime Especial Unificado de Arrecadação de Tributos e Contribuições devidos pelas Microempresas e Empresas de Pequeno Porte (Simples Nacional). | Anexo 12 – ANEXO VI DA RESOLUÇÃO CGSN Nº 140, DE 2018. (ART. 8º, § 1º) ] Tabela: Subclasse | DENOMINAÇÃO ; 6431-0/00 | BANCOS MÚLTIPLOS, SEM CARTEIRA COMERCIAL ; 6432-8/00 | BANCOS DE INVESTIMENTO ; 6433-6/00 | BANCOS DE DESENVOLVIMENTO ; 6434-4/00 | AGÊNCIAS DE FOMENTO ; 6435-2/01 | SOCIEDADES DE CRÉDITO IMOBILIÁRIO ; 6435-2/02 | ASSOCIAÇÕES DE POUPANÇA E EMPRÉSTIMO ; 6435-2/03 | COMPANHIAS HIPOTECÁRIAS ; 6436-1/00 | SOCIEDADES DE CRÉDITO, FINANCIAMENTO E INVESTIMENTO - FINANCEIRAS ; 6437-9/00 | SOCIEDADES DE CRÉDITO AO MICROEMPREENDEDOR ; 6438-7/01 | BANCOS DE CÂMBIO ; 6438-7/99 | OUTRAS INSTITUIÇÕES DE INTERMEDIAÇÃO NÃO MONETÁRIA NÃO ; | ESPECIFICADAS ANTERIORMENTE ; 6440-9/00 | ARRENDAMENTO MERCANTIL ; 6450-6/00 | SOCIEDADES DE CAPITALIZAÇÃO ; 6461-1/00 | HOLDINGS DE INSTITUIÇÕES FINANCEIRAS ; 6462-0/00 | HOLDINGS DE INSTITUIÇÕES NÃO FINANCEIRAS ; 6463-8/00 | OUTRAS SOCIEDADES DE PARTICIPAÇÃO, EXCETO HOLDINGS ; 6470-1/01 | FUNDOS DE INVESTIMENTO, EXCETO PREVIDENCIÁRIOS E IMOBILIÁRIOS ; 6470-1/02 | FUNDOS DE INVESTIMENTO PREVIDENCIÁRIOS ; 6470-1/03 | FUNDOS DE INVESTIMENTO IMOBILIÁRIOS ; 6491-3/00 | SOCIEDADES DE FOMENTO MERCANTIL - FACTORING ; 6492-1/00 | SECURITIZAÇÃO DE CRÉDITOS ; 6499-9/01 | CLUBES DE INVESTIMENTO ; 6499-9/02 | SOCIEDADES DE INVESTIMENTO ; 6499-9/03 | FUNDO GARANTIDOR DE CRÉDITO ; 6499-9/04 | CAIXAS DE FINANCIAMENTO DE CORPORAÇÕES ; 6499-9/05 | CONCESSÃO DE CRÉDITO PELAS OSCIP ; 6499-9/99 | OUTRAS ATIVIDADES DE SERVIÇOS FINANCEIROS NÃO ESPECIFICADAS ; | ANTERIORMENTE ; 6511-1/01 | SOCIEDADE SEGURADORA DE SEGUROS VIDA ; 6511-1/02 | PLANOS DE AUXÍLIO-FUNERAL ; 6512-0/00 | SOCIEDADE SEGURADORA DE SEGUROS NÃO VIDA ; 6520-1/00 | SOCIEDADE SEGURADORA DE SEGUROS SAÚDE ; 6530-8/00 | RESSEGUROS ; 6541-3/00 | PREVIDÊNCIA COMPLEMENTAR FECHADA\n```\n\n","20261008_190226_reference_fixes_and_label_only_articles_investigation.md":"# Reference Fixes (Q144, §2.3 (c)) and Investigation of the Label-Only Article Chunks (N3)\n\n**Generated:** 2026-10-08 19:02:26 (local time, from `date +%Y%m%d_%H%M%S`)\n**About:** follow-up to `docs/20261008_133726_corpus_rebuild_review_answers.md` (**the review note**).\nThe user has already applied, outside this note: the SC Cosit 194/2015 and 140/2015 `.docx` repairs,\nthe removal of `in_rfb_1911_20191011`, `lei_3071_19160101` and `lei_5869_19730111`, the RIR/2018\nLIVRO and Lei 6.766 \"III-A\" parser fixes (`lexml-parser-projeto-lei` `c587f6b`) and the linker fix.\nThis note covers what the user asked next:\n\n1. drop the wrong reference 144-05 (review note N1);\n2. fix the 10 pairs of review note §2.3 (c) by **changing the mapping**;\n3. investigate how to fix the 435 label-only article chunks (N3), either in the Scala statutory\n parser or with the Python non-statutory parser.\n\nNothing was re-parsed, re-segmented or re-embedded. The only file changed is\n`scripts/dataset/reference_overrides.json`.\n\n---\n\n## 0. Summary\n\n- **Reference fixes: done in `reference_overrides.json` and verified with a scratch build.** One\n `drop` entry (144-05) and 8 `citations` entries cover the 10 pairs. No code change was needed. The\n review note said the override format had to be extended, but that was wrong: the existing\n `citations` override already replaces a reference's provisions. In the scratch build, missing\n fragments fall from 25 to 15. Each of the 10 pairs becomes `matchable: true`, and nothing else\n changes apart from what is listed in §1.3.\n- **`dataset/` was not regenerated.** The local `../br-taxqa-document-fetcher` checkout is at\n `d4b7323` (2026-07-31). It does not contain `c7f4b8f`, the commit with the 27 canonical-record\n corrections that the committed dataset was built from (`build_report.json → git.fetcher_commit`),\n and `git fetch` fails here (no SSH key). A build against the stale list stops with 19 unresolved\n file names. **Pull the fetcher, then run the build** (§1.4).\n- **N3 is three parser defects, not one, and all three are in the Scala parser:**\n - **D1 (`Block.scala`).** A bare article label (\"Artigo 34\", \"ARTIGO 4º\") never receives the\n paragraphs that follow it. The parser attaches following text to agrupadores, but no rule\n does this for articles. This produces the 438 label-only `Artigo` elements in 16 files. In\n some of these, the orphan text then becomes the `TituloDispositivo` of the *next* article.\n - **D2 (`LexmlRenderer.renderAnexoArticulado`).** In annexes rendered as `DocumentoArticulado`,\n every non-`Dispositivo` block after the first article is **silently dropped**. Decreto 8.624\n annex 1 loses 79 source paragraphs and Decreto 9.358 loses 43, mostly the D1 article bodies.\n IN SRF 81 (16) and IN RFB 1.548 (5) lose form text. This loss was not visible in the review\n note's \"loose `TXT` chunks\" description.\n - **D3 (`LexmlRenderer.renderAnexoBlocks`).** In annexes rendered as `DocumentoGenerico`, all\n paragraphs and tables are emitted first and all dispositivos after them, so text order is lost.\n The Decreto 5.128 annex has 53 article bodies stacked on top, followed by 85 label-only\n articles and loose alíneas.\n- **Recommendation: fix D1–D3 in the Scala parser** and re-parse the affected files. The Python\n non-statutory parser is not an option. Even with `--emitter norma` forced on\n `decreto_56435_19650608.docx`, its statutory emitter refuses the document and falls back to a\n flat `DocumentoGenerico` with **0 `Artigo` elements**. That would remove the article ids that\n today's gold matches (143-01/144-01 `art37_cpt_ite2/ite4`, 149-02, 151-01, 160-02…), and it would\n make S1 = S2 = S3 for these documents.\n\n---\n\n## 1. Reference fixes\n\n### 1.1 Q144: drop 144-05\n\n| Field | Value |\n|---|---|\n| Reference | 144-05, `embedded`, cited title \"Convenção de Viena sobre o Direito dos Tratados\", v1 file `Convenção de Viena sobre o Direito dos Tratados.txt` → `decreto_7030_20091214` |\n| Why wrong | The \"Convenção de Viena\" in Q144 is the Convention on Diplomatic Relations (Decreto 56.435/1965), which is already reference 144-01 (art. 37, items 2 and 4) |\n| Override | `drop` entry `{question_number: \"144\", file: \"Convenção de Viena sobre o Direito dos Tratados.txt\"}` |\n\nThe same v1 file name is also used by Q160, where an existing `reassign` override maps it to\n`decreto_8624_20151229`. So the file name is still in use and the \"dead override\" guard does not fire.\nAfter the drop, **`decreto_7030_20091214` is cited by no question** (`documents_not_cited`). The\nreview note (§2.1) recommends removing it from the corpus. That has not been done: it is the user's\ndecision, like the other removals.\n\n### 1.2 Review note §2.3 (c): change the mapping\n\nEach pair now has a `citations` override (question + origin + v1 file → hand-written citation,\nparsed by the same `citations.py`). Every target id was checked in the LexML before the edit:\n\n| Reference(s) | Cited | Override citation | New fragment(s) | Text of the target (LexML) |\n|---|---|---|---|---|\n| 018-01 | Lei 9.250 art. 10, **inciso X** | `art. 10, inciso IX` | `art10_cpt_inc9` | \"IX – R$ 16.754,34 … a partir do ano-calendário de 2015\" (the amount the answer quotes) |\n| 093-02, 093-06 | Lei 6.015 art. 167, I, **itens 24 e 25** | `art. 167, inciso I, alíneas \"x\" e \"y\"` | `…_ali24`, `…_ali25` | \"x) das sentenças que nos inventários…\", \"y) dos atos de entrega de legados…\" |\n| 209-01 | Lei 6.015 art. 167, I, **item 7** (+ art. 220, V) | `arts. 167, inciso I, alínea \"g\", e 220, inciso V` | `art167_cpt_inc1_ali7` (+ `art220_cpt_inc5` unchanged) | \"g) do usufruto e do uso sobre imóveis…\" |\n| 460-03 | IN RFB 2.178 art. 11, **§ 2º, inciso II** | `art. 11, § 3º, inciso II` | `art11_par3_inc2` | \"II – bens móveis e direitos cujo valor unitário … inferior a R$ 5.000,00\" |\n| 683-02 | Lei 12.350 art. 45, **§ 3º** | `art. 45` | `art45` | Art. 45 rewrites art. 8 of Lei 9.959; the § 3º is inside the quoted wording |\n| 708-01 | Lei 11.033 art. 3º, incisos II a V, **e parágrafo único** | `art. 3º, incisos II a V, e § 1º` | `art3_cpt_inc2…inc5`, `art3_par1` | \"§ 1º … (Parágrafo único acrescido pela Lei nº 11.196 … e transformado em § 1º pela Lei nº 14.754…)\" |\n| 708-11 | Lei 11.033 **parágrafo único do art. 3º** | `§ 1º do art. 3º` | `art3_par1` | same |\n\nEvery entry's `reason` starts with \"user fix (2026-10-08, review answers note §2.3 (c))\" and gives\nthe diagnosis. The `provisions_note` of each reference carries this reason. 018-01 maps to inciso IX\nas the user decided. The review note's other option, checking Planalto for an inciso X that this\n`.docx` lacks, was not taken.\n\n### 1.3 Verification (scratch build)\n\n`build_v2_dataset.py` reads `reference_overrides.json` next to itself, so the check ran on a copy\nin the session scratchpad. The copy had 19 stand-in `files` entries for the unresolved names (each\npointing at the `document_id` the committed dataset gives that file name), and\n`ROOT` pointed at this repository. Diff against the committed `dataset/references.jsonl`:\n\n| Change | References |\n|---|---|\n| removed | 144-05 |\n| provisions changed (all now `matchable: true`) | 018-01, 093-02, 093-06, 209-01, 460-03, 683-02, 708-01, 708-11 |\n| `document_id` changed | 150-03, 280-08: **artifacts of the stale fetcher list** (these are two of the 27 `c7f4b8f` corrections), not of this change |\n\nCounts: references 1,917 → 1,916; `fragment_ids_missing` 25 → **15** (the 13 treaty pairs of §2.3 (a)\nplus the 2 N3 pairs 142-03 and 157-01); `documents_not_cited` gains `decreto_7030_20091214`. (It also\ngains `ad_pgfn_3_20160330`, another stale-list artifact, and loses the three removed documents.)\n`python3 -m pytest scripts/dataset/tests`: 36 passed.\n\n### 1.4 To do before the rebuild\n\n```bash\ngit -C ../br-taxqa-document-fetcher pull # must contain c7f4b8f\npython3 scripts/dataset/build_v2_dataset.py --questions ../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json\n```\n\nThe default `--questions` path (`../questions_QA_2024_v1.1_manual_fix.json`) does not exist in this\ncheckout. `../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json` has the SHA-256 recorded in\n`build_report.json` (`097abfc4…`), so it is the same input. Check after the build that\n`git.fetcher_commit` is `c7f4b8f…` and that the diff matches §1.3 without the two stale-list rows.\nThe build should run **after** the re-parse (§2), because the 2 N3 pairs become matchable only then.\n\n---\n\n## 2. N3: the label-only article chunks\n\n### 2.1 What the XML looks like\n\nA scan of `lexml/articulados/*.xml` for `Artigo` elements with no text outside their `Rotulo`\nfinds **438 in 16 files**: the review note's 14 files, plus `in_rfb_1505` (2, inside amendment\ntext, and the document is a removal candidate) and `mp_2189-49` (1, a revoked article inside\namendment text: correct). Classified by the article's next sibling:\n\n| Next sibling | Count | Example | Source | What happened |\n|---|---:|---|---|---|\n| `p` (body text) | 286 | `decreto_56435` art34, `decreto_67542` art10 | `Artigo 34` / `O agente diplomático gozará…` / `a) …` | Body left as a sibling `p`, which also blocks the following alíneas from being absorbed |\n| none (last child of its parent) | 69 | `decreto_50656` art1 (in `cap1`) | `CAPÍTULO I` / `Nome e objeto` / `ARTIGO 1` / two body paragraphs / `CAPÍTULO II` | The chapter absorbs the article but stops at the paragraphs, which end up *after* the chapter |\n| `Artigo` | 51 | `decreto_50656` art43; `decreto_5128` annex art4–art7 | `Artigo 43` / body / `Artigo 44` / body | Body of art. 43 became the `TituloDispositivo` of art. 44 (step `identificaTitulos`); in the 5128 annex the bodies were moved to the top (D3) |\n| `Item` / `Alinea` / `Inciso` | 24 | `decreto_9358` annex 1 art102 | `Artigo 102` / `Composição, funcionamento e reuniões … (Const. 17)` / `1. …` | The article title (after the label, treaty style) is a sibling `p`, so the numbered items are not absorbed; in the articulated annex the title is then dropped (D2) |\n| `Capitulo` | 5 | `decreto_8624` annex 1 art15 | `Artigo 15` / `Transparência e Prestação de contas` / `O Banco assegurará…` / `Capítulo IV` | Title and body **dropped** (D2) |\n| inside `Alteracao` | 3 | `in_rfb_1505`, `mp_2189-49` | n/a | Not a defect (amendment text, revoked article) |\n\n### 2.2 Root causes in `../lexml-parser-projeto-lei`\n\nThe articulation pipeline is `ProjetoLei.parseArticulacao` (`ProjetoLei.scala:290-345`):\n`reconheceDispositivos` → `reconheceOmissis` → **`identificaTextosAgregadores`** (6) →\n**`identificaTitulos`** (7) → `limpaParagrafosVazios` → **`organizaDispositivos`** (8) → …\n\n**D1: a bare article label gets no body** (`block/Block.scala`)\n\n- Step 6 (`identificaTextosAgregadores`, `Block.scala:953`) appends the following non-empty paragraphs\n to an agrupador (`d.rotulo.isAgregador`) as its name. No equivalent exists for `RotuloArtigo`.\n- Step 7 (`identificaTitulos`, `Block.scala:990`) takes a paragraph *before* any dispositivo as\n its title when it has no `.`, `;` or `:` (`podeSerTitulo`). This is the Brazilian style, where the\n epígrafe sits above \"Art. N\". With D1, the orphan body of article N that has no such punctuation becomes the\n title of article N+1 (`decreto_50656` art44).\n- Step 8 (`organizaDispositivos.agrupa`, `Block.scala:658`) attaches a following paragraph to an\n *agrupador* with empty content (`Block.scala:697`). It also continues an article whose caput\n ends in `,` `;` `-` (`Block.scala:708`), but it does nothing for an article with **no** content.\n `spanNivel` then stops at that paragraph, so any alíneas or items after it stay siblings.\n Articles whose text starts with \"1.\" work (Vienna art. 37 → `art37_cpt_ite2`). The numbered\n paragraphs are dispositivos, so `spanNivel` absorbs them.\n\n**D2: articulated annexes drop loose paragraphs** (`output/LexmlRenderer.scala:458`,\n`renderAnexoArticulado`)\n\n```scala\nval (leading, rest) = a.blocks.span(!_.isInstanceOf[Dispositivo])\nval dispositivos = rest.collect { case d: Dispositivo => d } // Paragraphs in `rest` are discarded\n```\n\nLeading paragraphs go to the `Preambulo`. Every `Paragraph` after the first `Dispositivo` is lost\nwithout a warning. `isArticulatedAnexo` (line 425) chooses this path whenever the annex has only\n`Dispositivo`s and `Paragraph`s. A text-coverage scan (each source paragraph of ≥ 40 characters, label\nstripped, searched in the normalized text of the document's XML files) over the 17 documents with\n`DocumentoArticulado` annexes:\n\n| Document | Source paragraphs lost | What they are |\n|---|---:|---|\n| `decreto_8624_20151229` (NDB agreement, cited by Q160) | 79 | article titles and bodies of the label-only articles |\n| `decreto_9358_20180430` (UPU convention, Q150) | 43 | article titles (\"Composição, funcionamento…\"), dash items |\n| `in_srf_81_20011011` (cited by 20+ questions) | 16 | annex form fields (the cited articles are in the main file and complete) |\n| `in_rfb_1548_20150213` (Q058, Q059) | 5 | annex model-form lines |\n| `decreto_lei_5452_19430501` (CLT) | 3 | odd labels (\"­­­I -\" with soft hyphens, \"§ lº\", \"§ 10º\"), a different cause, not D2 |\n| `in_srf_698`, `in_rfb_2060`, `in_srf_256` | 1–2 | table/header noise |\n\n**D3: generic annexes reorder text** (`output/LexmlRenderer.scala:395`, `renderAnexoBlocks`)\n\n```scala\nval (dispositivos, simples) = a.blocks.partition { case _: Dispositivo => true; case _ => false }\n...\nNodeSeq.fromSeq(simplesNodes) ++ dispNodes // all p/table first, all dispositivos after\n```\n\n`decreto_5128_20040706.anexo1.xml` (OEI seat agreement, Q157) went this way because it holds a\nnon-paragraph block. Its `PartePrincipal` has 53 `p` (the preamble *and* every article body) and\nthen 85 dispositivos (label-only articles and loose alíneas). No text is lost, but the chunks are\nmeaningless: alínea \"d\" of art. 21 (cited by 157-01) is a loose `ALI` chunk far from its caput. Other\ngeneric annexes with this shape (`lei_12249` annexes 2–9, `lei_comp_123` annexes 1–5…) have a few\nheader paragraphs and one table-like dispositivo, so the reordering is harmless there. Check them\nwhen re-parsing anyway.\n\n### 2.3 Why not the Python non-statutory parser\n\n`lexml_parser_non_statutory` has a statutory emitter (`render/norma.py`, `render_norma_checked`).\nIt is built to *refuse* articulation it cannot prove (\"statutory detection's main job is refusing\nfalse positives\"). Run on the Vienna convention:\n\n```bash\nPYTHONPATH=src python3 -m lexml_nonstat parse --emitter norma \\\n --urn 'urn:lex:br:federal:decreto:1965-06-08;56435' --summary -o <scratch> \\\n ../br-taxqa-r_v2.0/original/articulados/decreto_56435_19650608.docx\n# route: generico (0.75), emitter: generico, hierarchy: flat (0.00)\n```\n\nThe output is a flat `DocumentoGenerico` with 219 `p` and **0 `Artigo` elements**, and \"Artigo 34\" is\na plain `<p>`. Moving the 14 files to the non-statutory route would therefore:\n\n- remove every article id from these documents. The article and provision gold that matches today\n would become unreachable: 143-01 and 144-01 `art37_cpt_ite2/ite4`, 149-02/150-13 `art6`, 151-01\n `art47`, 151-02 `art15`, 153-02 `art141`, 160-02 `art34_cpt_ali2`. The gold matcher does not\n support article ids in a `DocumentoGenerico` (review note §2.3 (a));\n- make every chunk a `TXT`, so S1 = S2 = S3 = S2c = S4 for these documents, which removes them from\n the segmentation comparison;\n- still not fix D2/D3 for the statutory documents that are not treaties (IN SRF 81, IN RFB 1.548).\n\nThe Scala parser already recognizes \"Artigo N\" / \"ARTIGO N\" labels and builds the right ids. Only the\nattachment and rendering steps are wrong, so the fix belongs there.\n\n### 2.4 Proposed fix (Scala, `../lexml-parser-projeto-lei`)\n\n**F1: attach the text after a bare article label (D1).** Add a new pass between step 6 and step 7.\nIt must run before `identificaTitulos`, which would otherwise take the orphan body as the next\narticle's title. For a `Dispositivo` with `RotuloArtigo`, empty content (`None` or a blank\n`Paragraph`), no sub-dispositivos, and outside `Alteracao`, followed (after empty paragraphs) by\nnon-empty paragraphs:\n\n1. **Title (treaty style).** The first paragraph becomes `titulo` (`TituloDispositivo`) when it is\n short (≤ 150 characters), does not end in `.`, `;`, `:` or `,`, and is followed by another\n non-empty paragraph or by a sub-article dispositivo (`§`, inciso, alínea, item). Examples:\n \"Composição, funcionamento e reuniões do Conselho de Administração (Const. 17)\", \"Transparência e\n Prestação de contas\", \"Utilização de recursos\". Short sentences that end in a period stay caput\n text (\"O Banco assegurará…\", \"O presente Tratado terá duração ilimitada.\").\n2. **Caput.** The following non-empty paragraphs up to the next `Dispositivo` become the caput. The\n model holds one `Paragraph` per dispositivo, so join them with a space, as step 6 does for\n agrupadores. (The rigid schema allows several `p` in a dispositivo, so a later renderer change\n could keep them separate.) Stop at closing formulas so the treaty's final clause is not swallowed\n into the last article: `^(EM FÉ DO QUE|EM TESTEMUNHO|FEITO EM|Feito em|Assinado|Pel[oa] Governo)`.\n3. Nothing else changes. Step 8's `spanNivel` then absorbs the alíneas, items and incisos that follow\n (as it already does for Vienna art. 37), which gives `art34_cpt_ali4` and `art21_cpt_ali4`.\n\n**F2: never drop text in articulated annexes (D2).** In `isArticulatedAnexo`, also require that\nno non-empty `Paragraph` follows the first `Dispositivo`. Otherwise fall back to\n`renderAnexoGenerico`, as the method already does for tables. After F1 the treaty annexes no\nlonger have such paragraphs and stay articulated. Form annexes (IN SRF 81, IN RFB 1.548) fall back\nand keep their text. Also log the fallback to the `.err.log`, so a future loss is visible.\n\n**F3: keep the order in generic annexes (D3).** `renderAnexoBlocks` should walk `a.blocks` in\norder and emit each maximal run of `Dispositivo`s through `renderBlocks` at its own position. The\ntable ids keep their running index.\n\n**Tests.** Add unit tests next to `RotuloParserTest` with small block lists: (a) a bare label + body + alíneas;\n(b) a bare label + title + numbered items; (c) a bare label + body at the end of a chapter;\n(d) Brazilian-style title above \"Art. N\" (must be unchanged); (e) the last article + \"EM FÉ DO QUE\";\n(f) inside `Alteracao` (must be unchanged). Add one renderer test each for F2 and F3.\n\n**Expected effect on the corpus.**\n\n| Measure | Now | After F1–F3 |\n|---|---:|---|\n| label-only `Artigo` outside `Alteracao` | 435 (14 files) | ≈ 0 (left-overs listed and reviewed) |\n| cited article items on an empty `ART` chunk | 5 (142-03, 151-01, 151-02, 153-02, 157-01) | 0 |\n| `fragment_ids_missing` | 15 (after §1) | 13: 142-03 `art34_cpt_ali4` and 157-01 `art21_cpt_ali4` become matchable |\n| source paragraphs lost in articulated annexes | 143 (8624, 9358, IN SRF 81, IN RFB 1.548) | 0 |\n| loose `TXT`/`ALI`/`DSP` chunks in these 14 files | many | only the real preamble and closing text |\n\n**Verification after the re-parse.** Re-parse all statutory files, not only the 14, and diff the\nXML against the current `lexml/articulados/`. Only the 14 treaty files, the 5 documents with D2\nlosses and generic annexes with interleaved dispositivos should change. Every other change is a\nregression of F1's title rule. Then re-run `scripts/lexml/audit_article_coverage.py`, the\nlabel-only scan and the text-coverage scan from this note.\n\n### 2.5 Related, not fixed here\n\n- `decreto_lei_5452` (CLT): 3 paragraphs lost to unusual labels (\"­­­I -\" with soft hyphens, \"§ lº\"\n with a lowercase L, \"§ 10º\"). This is a different cause and needs its own look.\n- The treaty decrees of review note §2.3 (a) (O1) have no treaty text, or have labels the parser\n does not read (\"Artigo I…XXV\" in some annexes, `decreto_57942` without markers). F1 does not\n change them.\n\n---\n\n## 3. Corpus state to settle before the re-parse\n\n- The LexML files of the removed documents are still in `lexml/articulados/`:\n `in_rfb_1911_20191011` (61 files), `lei_3071_19160101`, `lei_5869_19730111`. Delete them with\n their `.err.log` files, or make sure the re-parse and `segment_all.py` start from an empty\n output folder. Otherwise their chunks come back.\n- Still pending from the review note, these are the user's decisions:\n - remove `in_rfb_1505_20141031` and `decreto_7030_20091214` (both cited by no question after this\n note);\n - add the Q029 service-page references and re-extract Q576's references (N2);\n - O5 and O7: the test snapshot and the referee cache.\n- Suggested order: (1) pull the fetcher; (2) F1–F3 + tests in `../lexml-parser-projeto-lei`;\n (3) re-parse statutory documents (all) and non-statutory documents (SC 140/194); (4) dataset build\n (§1.4); (5) segmentation, embedding of the new texts, retrieval and evaluation.\n","20261009_121822_nonstat_reparse_decision_and_pipeline_rerun_log.md":"# Non-Statutory Re-Parse: Decision, Execution Log and the Pipeline Re-Run (v2d IR result)\n\n**Generated:** 2026-10-09 12:18:22 (local time, from `date +%Y%m%d_%H%M%S`)\n**About:** the user asked for (a) a check of the activities recorded in\n`docs/20261008_010441_corpus_rebuild_results.md` (**the results note**),\n`docs/20261008_133726_corpus_rebuild_review_answers.md` (**the review note**) and\n`docs/20261008_190226_reference_fixes_and_label_only_articles_investigation.md` (**the investigation\nnote**); (b) a decision on whether every non-statutory document must be re-parsed before re-segmenting\nand re-embedding with `jua-4b-mixed`; and (c) an updated IR result after all the fixes, with every\ncommand recorded for audit and reproduction.\n**Status (2026-10-09 14:38):** all done. The note was written in two phases. §0–§7 date from the\nmorning, when the dataset build was blocked because fetcher commit `c7f4b8f` was only on the user's\nother computer. §8–§10 date from the afternoon, after the user brought the commit over and decided to\ngo on without the other computer's referee cache. They record the execution and the **updated IR\nresult (eval `v2d_either_containment_skip`, §9)**. Committed on 2026-10-09 (§10.2):\n`a80a5cf` (`.docx` fixes + `lexml/nao_articulados/`), `f13bcf3` (`segmented/`), `31293c5` (`dataset/`),\n`ffbc7a3` (`strategies.yaml`, `embeddings/` manifests, `runs/`, this note), then the clean-tree dataset\nrebuild (`build_report.json` only). Scratch outputs and tools are in\n`$S` = `/tmp/claude-0/-work-unicamp-articles-RAG-evaluation-br-taxqa-r-v2-0/36df1725-581b-4996-9f90-469e4024fdaa/scratchpad`\n(volatile; the scripts the reproduction needs are inlined or described in §3.4 and §8.2).\n\n---\n\n## 0. Summary\n\n**Outcome (afternoon, §8–§9).** The non-statutory corpus was re-parsed and installed (fixed linker,\nrepaired SC 140/194). The whole corpus was re-segmented (104,574 rows) and the dataset rebuilt against\n`c7f4b8f` (1,916 references, 13 missing fragments, all treaty articles). The corpus was re-embedded\nin full with `jua-4b-mixed` (101,943 texts, $1.23), then retrieved and evaluated. **The IR picture of\n2026-10-08 holds.** S2 is the best strategy at 4k (document 0.667, article 0.473, provision 0.362;\nsub-article provision gold 0.425). Adding the caput sentence still hurts (S2c − S2 and S4 − S3 are\nnegative at every level and budget, p ≤ 0.002). Every headline number moved by at most +0.006. The\ncorpus fixes matter for individual questions (the treaty provisions 142-03 and 157-01 are now real\nchunks, ranked 17 and 6) and for the gold, not for the averages.\n\n**Morning analysis (§1–§7):**\n\n- **Yes, all non-statutory documents must be re-parsed** (§2). There are three reasons:\n 1. two sources changed: SC Cosit 140/2015 and 194/2015 (`fed0813`);\n 2. the linker was rebuilt with the \"art. N, caput\" fix (`../lexml-linker` `51874d9`). The non-statutory\n parser renders a `Remissao` for every paragraph, so every file with a citation is affected;\n 3. the statutory side already carries the fixed links (`a94c2bf`, 54 files with link-only changes),\n and the two halves of the corpus should come from the same linker.\n- **The parser's linker cache must be replaced, not reused.** `lexml_nonstat` keys its linker cache by\n (context URN, paragraph text) only, by design (`src/lexml_nonstat/refs/cache.py`). All 16,315\n entries in `../lexml_parser_non_statutory/.cache/linker` predate the linker build (2026-10-08 17:29).\n Re-running the R3c command as recorded would silently re-serve the old links. The re-parse used a new\n `.cache/linker_51874d9`.\n- **Re-parse result (scratch):** 245/245 files, exit 0, deterministic. A second run made 0 referee calls\n and wrote byte-identical files. Against the committed `lexml/nao_articulados/`: 83 identical,\n 131 link-only, 8 link-span-only (text equal), **23 with a different structure** (§3).\n- **The 23 structural differences are mostly unintended.** Only SC 140/2015 and SC 194/2015 should\n change in text. The other 21 come from **31 referee cache misses**. The local\n `/tmp/lexml_referee_cache` holds only answers from 2026-09-16. The 513 answers bought by the\n 2026-10-08 R3c parse are not on this machine: that parse ran on the user's other computer, like the\n fetcher commit. The fresh answers moved borderline headings in 21 cited documents (§4).\n- **Recommendation (superseded by the user's decision D1 in §8: proceed without that cache):** do not install this parse. Bring two things from the other computer, the fetcher\n commit `c7f4b8f` **and** that computer's `/tmp/lexml_referee_cache`. Merge the cache, re-run the\n parse (§6, step P1), and check that only SC 140, SC 194 and links change. Then run the rest of\n §6 unchanged.\n- **Source repairs only partly worked.** The SC 140/2015 `.docx` still has the layout table with the\n \"natalista…\" body fragments (review note B1). SC 194/2015 still has one glued word (\"ouexigir\") (§3.3).\n- **The statutory corpus is reproducible from committed code.** A jar rebuilt at\n `../lexml-parser-projeto-lei` `4c85e81` re-parses all 209 `.docx` into 386 XML files that are\n byte-identical to `lexml/articulados/` (§5.2). That folder needs no further work before the\n re-segmentation.\n\n---\n\n## 1. What the three notes leave pending, and the state found on 2026-10-09\n\n| Item (source) | State on 2026-10-09 |\n|---|---|\n| Statutory re-parse after F1–F3, linker fix, RIR/1999 LIVROs, \"III-A\" (investigation note §2.4, §3) | **Done** in `a94c2bf` (`lexml/articulados/PARSER_VERSION`: 209 `.docx`, 386 XML, label-only articles 440 → 1). The parser fix was uncommitted at parse time; it is now `../lexml-parser-projeto-lei` `4c85e81` |\n| Removed documents (`in_rfb_1911`, `lei_3071`, `lei_5869`, `decreto_7030`, `in_rfb_1505`) | `.docx` removed (`fed0813`, `6c6fdde`); no leftover XML in `lexml/articulados/` (checked: every XML stem has a `.docx`) |\n| SC Cosit 140/2015 and 194/2015 `.docx` repairs (review note N7/B1/B2) | Committed in `fed0813`; **not re-parsed** (the committed non-statutory XML is from `bf79a58`, 2026-10-08 00:39) |\n| Linker fix (review note §2.5, O6) | Committed (`../lexml-linker` `51874d9`); `/usr/local/bin/linkertool` → binary sha256 `6b4cf768…b28f` (built 2026-10-08 17:29); used by the statutory parse; **not yet used** for non-statutory documents |\n| Reference fixes 144-05 + 10 pairs (investigation note §1) | In `scripts/dataset/reference_overrides.json` (`6c6fdde`); **`dataset/` not rebuilt** |\n| Fetcher `c7f4b8f` (investigation note §1.4) | **Not on this machine**: `../br-taxqa-document-fetcher` is at `d4b7323`, `git fetch` fails (no SSH key), and no other clone exists. The user confirmed it was never pushed |\n| Segmentation, embeddings, retrieval | Still from 2026-10-08 (R7/R8/R9). They predate the statutory re-parse and are therefore stale |\n| `lexml_parser_non_statutory` code | Unchanged since `e8c3d1e`, the commit used by R3c |\n\n---\n\n## 2. Decision: re-parse every non-statutory document\n\nThe question was whether re-parsing only SC 140 and SC 194 (`lexml_nonstat parse` takes a file list)\nwould do. It would not:\n\n1. **Linker.** The linker fix changes `Remissao` spans and targets in non-statutory text as much as in\n statutory text. In the scratch parse, links rose from 4,561 to 5,277, links resolved down to an\n article (`!art…`) from 1,700 to 3,808, and the defective `…;NNNN!cpt` links (article lost) fell from\n 153 to 20. 139 of 245 files change only through links (§3). Chunk text does not use links. The\n released LexML does, and so would any later citation graph.\n2. **Consistency.** `lexml/articulados` was parsed with the fixed linker on 2026-10-08. Leaving\n `lexml/nao_articulados` on the old one would mix two linker versions in one release.\n3. **Cost.** A full parse takes about 5 minutes. With a warm referee cache it makes no API calls.\n\nThe linker cache detail matters for (1). The cache docstring says a linker upgrade \"must show up as a\nreviewed diff in a re-recorded fixture rather than as a new cache key\". So reusing `.cache/linker`\ngives the **old** answers with no error. A new cache directory, named after the linker commit, is\nrequired.\n\n---\n\n## 3. Execution log (non-statutory re-parse, scratch)\n\nEvery command below ran on 2026-10-09 on this machine, in the order given.\n\n### 3.1 Commands\n\n```bash\n# E0. State checks (read-only)\ncd /work/unicamp/articles/RAG_evaluation/br-taxqa-r_v2.0\ngit log --oneline -8 -- lexml/nao_articulados original/nao_articulados scripts/lexml\nfor r in lexml_parser_non_statutory lexml-parser-projeto-lei lexml-linker br-taxqa-document-fetcher; do\n git -C ../$r log --oneline -6; git -C ../$r status --short; done\ngit -C ../br-taxqa-document-fetcher fetch # fails: \"Please make sure you have the correct access rights\"\ngit -C ../br-taxqa-document-fetcher cat-file -t c7f4b8f # fatal: Not a valid object name\nsha256sum \"$(readlink -f /usr/local/bin/linkertool)\" # 6b4cf7683bf0483f35e1712e54ce578d113a44b0115f46240fc9bc433303b28f\nstat -c '%y' \"$(readlink -f /usr/local/bin/linkertool)\" # 2026-10-08 17:29:31\nfind ../lexml_parser_non_statutory/.cache/linker -newer \"$(readlink -f /usr/local/bin/linkertool)\" | wc -l # 0 (of 16,315)\ncomm -13 <(ls original/articulados/ | sed 's/\\.docx$//' | sort) \\\n <(ls lexml/articulados/*.xml | xargs -n1 basename | sed -E 's/(\\.anexo[0-9]+)?\\.xml$//' | sort -u) # empty\n\n# E1. Back up the referee cache (it lives in /tmp)\nS=/tmp/claude-0/-work-unicamp-articles-RAG-evaluation-br-taxqa-r-v2-0/36df1725-581b-4996-9f90-469e4024fdaa/scratchpad\nmkdir -p $S/nonstat_out $S/backup\ncp -a /tmp/lexml_referee_cache $S/backup/lexml_referee_cache_20261009 # 630 entries\n\n# E2. Full non-statutory parse: R3c's command with a NEW linker cache and a scratch output folder\ncd ../lexml_parser_non_statutory && set -a && . ./.env && set +a && \\\nLC_ALL=C.UTF-8 PYTHONPATH=src python3 -m lexml_nonstat parse --emitter=generico-aninhado \\\n --generation=proposed --referee=api --referee-cache=/tmp/lexml_referee_cache \\\n --linker=/usr/local/bin/linkertool --linker-cache=.cache/linker_51874d9 \\\n --metadata ../br-taxqa-r_v2.0/scripts/lexml/nonstat_metadata.tsv \\\n -o $S/nonstat_out \\\n ../br-taxqa-r_v2.0/original/nao_articulados/*.docx ../br-taxqa-r_v2.0/lexml/nao_articulados/_text/*.txt \\\n > $S/nonstat_parse.log 2>&1\n# exit 0; 245 XML files; referee cache 630 -> 661 entries (31 API calls, model gpt-5.6-luna)\n\n# E3. Determinism: same command again, into $S/nonstat_out2\n# -> exit 0; referee cache 661 -> 661 (no calls); `diff -rq $S/nonstat_out $S/nonstat_out2`: identical\n\n# E4. Classify the differences against the committed folder (scripts in $S/tools/, listed in §3.4)\n.venv/bin/python $S/tools/diff_lexml.py lexml/nao_articulados $S/nonstat_out # identical / link-only / other\n.venv/bin/python $S/tools/diff_lexml2.py lexml/nao_articulados $S/nonstat_out # text equal? structure equal?\ncomm -13 <(ls $S/backup/lexml_referee_cache_20261009) <(ls /tmp/lexml_referee_cache) > $S/new_referee_keys.txt\n```\n\n### 3.2 Result\n\n| Class (vs committed `lexml/nao_articulados/`, 245 files) | Files |\n|---|---:|\n| byte-identical | 83 |\n| differ only in `Remissao` elements (links stripped → identical XML) | 131 |\n| text and structure equal, but a `Remissao` now spans more text (e.g. \"Lei 13709/2018, art. 5º, II\" becomes one link instead of \"Lei 13709/2018\" + plain \", art. 5º, II\"): the 7 service pages and ADI STF 5.422 | 8 |\n| text changed by the source repair, structure equal: SC 194/2015 | 1 |\n| **structure changed** (headings / hierarchy): SC 140/2015 (source repair) + 21 others (§4) | 22 |\n| | **245** |\n\n(`diff_lexml2.py` prints 23 \"text differs\" rows: 22 structural plus SC 194. Its text comparison counts a\nheading moved into a `Rotulo` as a text change.)\n\n### 3.3 The two repaired sources\n\n- **SC 194/2015 (B2).** The glued words \"setembrode\", \"Decretonº\" and \"ouexigir\" appear 5 times in the\n committed XML and once in the new one. The one left is \"constituir **ouexigir** créditos tributários\":\n the repaired `.docx` still has it.\n- **SC 140/2015 (B1).** The repaired `.docx` has 107 paragraphs (129 before). It **still holds the\n one-table layout block** whose cells are body-text fragments (\"natalista, a qual afirma que o\n nascituro…\"). The new XML still has `pp1_tab1` with those fragments, so the broken `TAB` chunk of\n the review note stays. To fix it, unwrap the table in the `.docx` (copy the cell paragraphs into the\n body in reading order), then re-parse.\n\n### 3.4 Scratch tools\n\n- `$S/tools/diff_lexml.py OLD NEW`: byte-identical / identical after `etree.strip_tags(Remissao)` /\n other. For \"other\" it prints word counts and a word-level `difflib` change count.\n- `$S/tools/diff_lexml2.py OLD NEW`: for each changed file, compares the whitespace-normalized\n concatenated text with links stripped, and the element skeleton (tag, `id`, `nome` of every\n non-inline element in document order).\n\n---\n\n## 4. Finding: the referee cache of the 2026-10-08 parse is not on this machine\n\n- All 630 entries of `/tmp/lexml_referee_cache` (and of the E1 backup) date from **2026-09-16**. The\n results note says that R3c (2026-10-08 00:31) bought 513 new answers and that \"the cache now holds\n 554\". None of those answers is here. Together with the missing fetcher commit, this shows that R1–R10\n ran on the user's other computer, apart from the later statutory re-parse.\n- The cache key is `sha256(model, kind, excerpt, ctx[, next_ctx])`, and all entries, old and new, are\n for `gpt-5.6-luna` (the current `LEXML_REFEREE_MODEL`). The 31 misses are 19 `own_articulation` and\n 12 `heading` questions (\"DECRETA:\", \"TRIBUTAÇÃO NA FONTE\", formulas such as \"IRF = (BCIR - P).i -\n PD\", quoted \"Art. N\" lines). Only 3 of them repeat an excerpt already in the local cache, with a\n different context. One of those 3 got a different verdict: \"Art. 133. Fica isento…\", `quoted` before\n and `own` now.\n- Effect: **21 cited documents** get different borderline headings and nesting. These are 17 SCs/SCI,\n 4 PGFN pareceres/notes and Súmula STJ 125. Together they are cited by 25 questions (079, 177, 180,\n 229, 235, 246, 282, 307, 335, 416, 421, 460, 539, 540, 560, 583, 600, 601, 618–620, 646, 657); 384\n cites SC 140, which changes anyway. The text is the same up to heading placement, but chunk\n boundaries and the `heading > heading` path at the start of chunks move. This is noise, not a fix. If\n installed, it would mix with the effect the next IR run is meant to measure.\n- The parse **is** deterministic once the cache is warm (E3). With the other computer's cache the\n committed decisions come back, and only the new questions from the SC 140/194 repairs need the API.\n\n---\n\n## 5. Blockers and checks\n\n### 5.1 Blocked: dataset build\n\n`scripts/dataset/build_v2_dataset.py` reads the canonical list\n`../br-taxqa-document-fetcher/output_canonical/canonical_referred_documents.json` (`--canonical`,\nline 280). The list maps each v1.1 reference file name to the cited act. The 27 corrections of R4\n(`c7f4b8f`: `fix_canonical_records.py` + `canonical_corrections_20261008.json`) exist only on the\nother computer. Building against `d4b7323` would undo them: 19 names unresolved, and 150-03 and 280-08\nwould point at the wrong documents (investigation note §1.3). Without a rebuild, `dataset/` still has\n144-05 → `decreto_7030_20091214`, which is no longer in the corpus, and none of the 10 reference fixes.\nSo no IR result can be produced on the fixed gold yet.\n\n### 5.2 Statutory reproducibility check (`4c85e81`)\n\n`lexml/articulados/PARSER_VERSION` records the parse as \"c587f6b + UNCOMMITTED working tree\" with\n`ArtigoSemCaputTest.scala` sha256 `360b7167…`. The committed `4c85e81` has that file at `0afda6e4…`\n(the test changed after the parse), so the check rebuilt the jar at `4c85e81` and re-parsed:\n\n```bash\ncp -a ../lexml-parser-projeto-lei/target/lexml-parser-projeto-lei-1.15.0-onejar.jar $S/backup/onejar_4f1b97.jar # the jar of a94c2bf\ncd ../lexml-parser-projeto-lei && LC_ALL=C.UTF-8 mvn -q -Ponejar package -DskipTests # HEAD 4c85e81, clean tree; 78 s\nsha256sum target/lexml-parser-projeto-lei-1.15.0-onejar.jar # a018af01…6c57 (jar bytes differ: build timestamps)\ncd ../br-taxqa-r_v2.0 && python3 ../lexml-parser-projeto-lei/scripts/batch_parse.py --no-justificativa \\\n --linker /usr/local/bin/linkertool original/articulados $S/stat_out > $S/stat_parse.log 2>&1\ndiff -rq lexml/articulados $S/stat_out | grep '\\.xml differ'\n```\n\nResult: exit 0, `converted=209 skipped=0 failed=0`, 386 XML files (27 min 41 s). **All 386 are\nbyte-identical** to the committed `lexml/articulados/` (`xml differ: 0`; the only extra file in the\ncommitted folder is `main_body_lexml.txt`). The committed statutory corpus is therefore reproduced by\n`../lexml-parser-projeto-lei` `4c85e81`. The uncommitted tree recorded in `PARSER_VERSION` differed\nfrom it only in the test file.\n\n---\n\n## 6. Remaining pipeline (to run once `c7f4b8f` and the referee cache are here)\n\nRun from `/work/unicamp/articles/RAG_evaluation/br-taxqa-r_v2.0` unless noted. The order follows the\nresults note (segmentation before the dataset build, which checks `cited_documents_without_chunks`\nagainst the chunks).\n\n```bash\nS=<scratch dir>\n\n# P0. Bring the inputs from the other computer\n# (other computer) git -C br-taxqa-document-fetcher push origin main # c7f4b8f\n# (other computer) tar czf referee_cache_20261008.tgz -C /tmp lexml_referee_cache\ngit -C ../br-taxqa-document-fetcher pull && git -C ../br-taxqa-document-fetcher log -1 --format=%H # must contain c7f4b8f\nmkdir -p $S/rc && tar xzf referee_cache_20261008.tgz -C $S/rc\ncp -a $S/rc/lexml_referee_cache/. /tmp/lexml_referee_cache/ # other computer's answers win on equal keys\n# Better (O7): keep the merged cache outside /tmp, e.g. ../lexml_parser_non_statutory/.cache/referee, and\n# pass that path to --referee-cache below.\n\n# P1. Non-statutory re-parse (= E2, output to a fresh folder)\ncd ../lexml_parser_non_statutory && set -a && . ./.env && set +a && \\\nLC_ALL=C.UTF-8 PYTHONPATH=src python3 -m lexml_nonstat parse --emitter=generico-aninhado \\\n --generation=proposed --referee=api --referee-cache=/tmp/lexml_referee_cache \\\n --linker=/usr/local/bin/linkertool --linker-cache=.cache/linker_51874d9 \\\n --metadata ../br-taxqa-r_v2.0/scripts/lexml/nonstat_metadata.tsv \\\n -o ../br-taxqa-r_v2.0/lexml/nao_articulados_new \\\n ../br-taxqa-r_v2.0/original/nao_articulados/*.docx ../br-taxqa-r_v2.0/lexml/nao_articulados/_text/*.txt\ncd ../br-taxqa-r_v2.0\n.venv/bin/python $S/tools/diff_lexml2.py lexml/nao_articulados lexml/nao_articulados_new\n# gate: structure changes only in SC 140/2015 (and SC 194 text); everything else link-only or identical\ncp lexml/nao_articulados/PARSER_VERSION lexml/nao_articulados_new/ && cp -a lexml/nao_articulados/_text lexml/nao_articulados_new/\nrm -r lexml/nao_articulados && mv lexml/nao_articulados_new lexml/nao_articulados\n# edit PARSER_VERSION: linker 51874d9 / sha256 6b4cf768…, --linker-cache=.cache/linker_51874d9, date, result\npython3 scripts/lexml/nonstat_lexml_map.py # must leave nonstat_lexml_map.tsv unchanged (same URNs)\ngit add -A lexml/nao_articulados scripts/dataset/nonstat_lexml_map.tsv && git commit\n\n# P2. Segmentation (frozen = the committed R7 chunk set; its LexML = 280121b)\ngit show HEAD:segmented/chunks_all.csv.gz > $S/chunks_all_r7.csv.gz\n.venv/bin/python scripts/segmentation/segment_all.py --jobs 16 --overwrite --allow-count-change \\\n --variants caput --frozen $S/chunks_all_r7.csv.gz --frozen-lexml-rev 280121b\n# gate: validation OK; diff_vs_frozen: 0 differences for documents whose LexML is unchanged since 280121b\ngit add segmented && git commit\n\n# P3. Dataset\npython3 scripts/dataset/build_v2_dataset.py --questions ../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json\n# gates: build_report.json git.fetcher_commit = c7f4b8f…; references 1,917 -> 1,916 (144-05 dropped);\n# the 8 overridden references matchable; fragment_ids_missing 25 -> 13 (142-03 and 157-01 matchable after F1);\n# cited_documents_without_chunks = []; decreto_7030/in_rfb_1505 not in documents.jsonl\npython3 -m pytest scripts/dataset/tests\ngit add dataset scripts/dataset && git commit\n\n# P4. Embeddings (only new texts; resumes the paused endpoint, pauses it at the end)\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --extend --dry-run\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --extend --resume\n\n# P5. Retrieval and evaluation (new eval id; the v2c evaluation stays readable)\nR=scripts/rag/rag.py\n.venv/bin/python $R check --embedding jua-4b-mixed\n.venv/bin/python $R retrieve --embedding jua-4b-mixed --force\n.venv/bin/python $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf \\\n --eval-id v2d_either_containment_skip --comparisons S1:S2,S2:S3,S2:S2c,S3:S4,S1:S2c\ngit add embeddings runs && git commit\n```\n\n---\n\n## 7. Other points found\n\n| # | Point | Suggestion |\n|---|---|---|\n| X1 | `lexml/articulados/PARSER_VERSION` names an uncommitted tree | §5.2 confirmed byte-identical output: replace it with `4c85e81` |\n| X2 | `../lexml-parser-projeto-lei/target/…-onejar.jar` is now the `4c85e81` build (sha256 `a018af01…`); the `a94c2bf` jar (`4f1b97af…`) is in `$S/backup/onejar_4f1b97.jar` | Record the new sha256 in `PARSER_VERSION` together with X1 |\n| X3 | SC 140/2015 layout table and SC 194/2015 \"ouexigir\" (§3.3) | Fix the `.docx` before P1 if wanted; P1 then covers it |\n| X4 | Referee cache volatility (results note O7): the cache in `/tmp` is now known to differ between computers | Keep one merged cache in a versioned or backed-up location; record its path in `PARSER_VERSION` |\n| X5 | `.cache/linker` of the non-statutory parser is stale (pre-`51874d9`) | Delete it once P1 is installed, so it cannot be used by mistake |\n| X6 | `segmented/chunks_all.csv` (uncompressed, gitignored) dates from 2026-09-25 | Stale; `segment_all.py` rewrites it in P2 |\n\n---\n\n## 8. Execution after the user's decisions (2026-10-09, afternoon)\n\nDecisions taken by the user after §0–§7 were written:\n\n- **D1.** The fetcher commit `c7f4b8f` was brought to this computer. The other computer's referee cache\n was **not**: the user asked whether it was really needed. The answer was no, at the cost of the 21\n referee-driven heading changes of §4, so the parse proceeds with the local cache.\n- **D2.** The user fixed the SC Cosit 140/2015 and 194/2015 `.docx` again (X3). Both now have no table\n and no glued words (sha256 `65aa4fd9…89e5`, `6452628c…5403`; working tree, not committed).\n- The referee is the OpenAI API (`LEXML_REFEREE_BASE_URL=https://api.openai.com/…`, model\n `gpt-5.6-luna`), with the key in `../lexml_parser_non_statutory/.env`. No new key was needed.\n\n### 8.1 P0/P1: referee cache made persistent, final non-statutory parse, install\n\n```bash\ncd /work/unicamp/articles/RAG_evaluation/br-taxqa-r_v2.0\ngit -C ../br-taxqa-document-fetcher log --oneline -1 # c7f4b8f Correct 27 canonical records …\ngit -C ../br-taxqa-document-fetcher status --short # \" M br_legal_parser\" (dirty submodule; recorded as fetcher_dirty)\n\n# referee cache out of /tmp (X4); .cache is gitignored in that repo\nmkdir -p ../lexml_parser_non_statutory/.cache/referee\ncp -a /tmp/lexml_referee_cache/. ../lexml_parser_non_statutory/.cache/referee/ # 661 entries\n\n# final parse into a fresh folder\ncd ../lexml_parser_non_statutory && set -a && . ./.env && set +a && \\\nLC_ALL=C.UTF-8 PYTHONPATH=src python3 -m lexml_nonstat parse --emitter=generico-aninhado \\\n --generation=proposed --referee=api --referee-cache=.cache/referee \\\n --linker=/usr/local/bin/linkertool --linker-cache=.cache/linker_51874d9 \\\n --metadata ../br-taxqa-r_v2.0/scripts/lexml/nonstat_metadata.tsv \\\n -o ../br-taxqa-r_v2.0/lexml/nao_articulados_new \\\n ../br-taxqa-r_v2.0/original/nao_articulados/*.docx ../br-taxqa-r_v2.0/lexml/nao_articulados/_text/*.txt \\\n > ../br-taxqa-r_v2.0/lexml/nao_articulados_new.log 2>&1\n# exit 0, 1 min 42 s, 245 XML, referee cache 661 -> 661 (0 API calls)\ncd ../br-taxqa-r_v2.0\ndiff -rq $S/nonstat_out lexml/nao_articulados_new # only SC 140/2015 and SC 194/2015 differ (the D2 fixes)\n.venv/bin/python $S/tools/diff_lexml.py lexml/nao_articulados lexml/nao_articulados_new\n# identical 83, remissao_only 131, other 31 (= 8 link-span-only + SC 140 + SC 194 + the 21 of §4)\n# SC 140: 0 <table>; SC 194: 0 glued words\n\n# install (keep _text/, write a new PARSER_VERSION)\nmv lexml/nao_articulados/_text lexml/nao_articulados_new/_text\nrm lexml/nao_articulados/*.xml lexml/nao_articulados/PARSER_VERSION && rmdir lexml/nao_articulados\nmv lexml/nao_articulados_new lexml/nao_articulados\nmv lexml/nao_articulados_new.log $S/nonstat_parse_final.log\n# lexml/nao_articulados/PARSER_VERSION rewritten by hand (parser e8c3d1e, command, linker 51874d9 +\n# .cache/linker_51874d9, referee cache .cache/referee with 661 answers, result)\npython3 scripts/lexml/nonstat_lexml_map.py # \"244 stems\"; nonstat_lexml_map.tsv unchanged\n```\n\n`git status`: 162 non-statutory XML files modified (= 245 − 83 identical), plus `PARSER_VERSION`.\n\n### 8.2 P2: segmentation\n\n```bash\ngit show HEAD:segmented/chunks_all.csv.gz > $S/chunks_all_r7.csv.gz # the R7 chunk set (280121b)\n.venv/bin/python scripts/segmentation/segment_all.py --jobs 16 --overwrite --allow-count-change \\\n --variants caput --frozen $S/chunks_all_r7.csv.gz --frozen-lexml-rev 280121b > $S/segment_all.log 2>&1\n# exit 0, 91 s of pipeline (2 min 51 s wall with validation)\n```\n\n| | R7 (2026-10-08) | Now |\n|---|---:|---:|\n| Router A / B / C | 12 / 50 / 179 | 12 / 35 / 130 |\n| XSL files / rows | 276 / 83,569 | 256 / 72,415 |\n| ART/DSP rows split → parts | 655 → 1,746 | 606 → 1,626 |\n| Loose rows | 697 | 388 (61 files) |\n| Non-statutory files / rows | 424 / 3,486 | 375 / 3,450 |\n| `chunks_all.csv` rows (base + caput) | 118,766 (88,600 + 30,166) | **104,574 (77,080 + 27,494)** |\n| S1 / S2 / S3 / S2c / S4 rows | 26,364 / 83,496 / 88,600 / 83,496 / 88,600 | 21,497 / 73,118 / 77,080 / 73,118 / 77,080 |\n| Grouping rows over 8,192 tokens (left out) | 243 | 193 |\n| Unique texts | 115,582 | 101,943 |\n\nMost of the drop comes from the five removed documents: Lei 3.071/1916 (Civil Code of 1916), Lei\n5.869/1973 (CPC of 1973), IN RFB 1.911/2019 with 60 annexes, Decreto 7.030/2009 and IN RFB\n1.505/2014. The rest comes from the statutory re-parse: the D2/D3 fixes, and loose chunks of the\ntreaty files absorbed into their articles.\n\n**Validation:** all 14 checks `ok`. **`diff_vs_frozen` needs care.** It reports `rows_text_differs: 8555`\nof 31,605 rows for the 364 files whose LexML is byte-identical to `280121b`. This is not a regression.\nThe check compares each new row's **caput variant** with the frozen text (`expected = cap_by_base…`,\n`validate_segments.py:433`). That was right for R7, whose frozen set predated the caput plan, so its\nparagraph rows carried the caput sentence. It is wrong now that the frozen set is R7, which has\ncaput-free base rows. A variant-matched comparison (`$S/tools/diff_chunks_same_variant.py`, key =\n`arquivo, variante, Tipo, urn, Num_Inicio, Num_Final, parte`) gives:\n\n```bash\n.venv/bin/python $S/tools/diff_chunks_same_variant.py $S/chunks_all_r7.csv.gz 280121b\n# files_unchanged_lexml 364, rows_compared 31605 (base 23050, caput 8555), rows_text_differs 0,\n# rows_only_new 0, rows_only_frozen 0\n```\n\nThe 8,555 are exactly the caput rows. Base and caput texts are unchanged wherever the LexML is unchanged.\n(X7: make `diff_vs_frozen` compare variant by variant when the frozen set already has a `variante`\ncolumn.)\n\n### 8.3 P3: dataset\n\n```bash\nmkdir -p $S/dataset_prev && cp -a dataset/. $S/dataset_prev/\npython3 scripts/dataset/build_v2_dataset.py --questions ../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json \\\n > $S/build_dataset.log 2>&1 # exit 0\npython3 -m pytest -q scripts/dataset/tests # 36 passed\n```\n\n- `questions 715 references 1916 {'auto_exact': 1815, 'auto_undated': 30, 'override': 71} documents 453\n (cited 446) dropped 10 articles found 1464+575 (annex)/2052 provisions {'found_in_main': 1654,\n 'found_in_annex': 616, 'without_id': 36, 'missing': 13}`.\n- `build_report.json → git`: `fetcher_commit c7f4b8f…`, `fetcher_dirty: true` (the submodule), `commit\n a94c2bf`, `dirty: true` (this uncommitted run).\n- Reference diff against the previous `dataset/`: **removed 144-05**; provisions changed for **018-01,\n 093-02, 093-06, 209-01, 460-03, 683-02, 708-01, 708-11** (the overrides, with `provisions_note`) and\n for **142-03 → `art34_cpt_ali4` and 157-01 → `art21_cpt_ali4`, now `matchable: true`** (the F1–F3\n statutory fix). Nothing else changed. In particular 150-03 and 280-08 keep their documents, so the\n stale-list artifacts of the investigation note are gone.\n- `validation.fragment_ids_missing`: **13**, all treaty articles of O1 (25 before).\n `article_ids_missing_unexplained = []`, `documents_without_chunks = []`, `cited_documents_without_chunks = []`.\n- `documents_not_cited` (7): the 5 service pages, `par_cosit_26_20000629`, `sc_cosit_153_20140611`\n (review note N2: they should get references, not be removed).\n\n### 8.4 P4: embeddings (full, not `--extend`)\n\nThe `--extend` dry run failed: `FileNotFoundError: embeddings/jua-4b-mixed/corpus/texts.csv`. The\nfinalized corpus store (texts and vectors, gitignored) is also on the other computer. Only its\n`manifest.json` is versioned. The query vectors are here (`embeddings/jua-4b-mixed/queries/irpf/`). The\ncorpus is therefore embedded in full:\n\n```bash\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --extend --dry-run # FileNotFoundError (above)\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --dry-run # \"already finalized; --overwrite …\"\ncp embeddings/jua-4b-mixed/corpus/manifest.json $S/backup/corpus_manifest_20261008.json\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --overwrite --dry-run\n# 101943 texts, 27,981,664 tokens (max 8104), 1593 requests of <= 64 inputs / 32768 tokens, concurrency 8\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --overwrite --resume --no-progress \\\n > $S/embed_corpus.log 2>&1\n```\n\nResult: exit 0 in 92 min 48 s. `session complete: 101943 texts, 27981664 tokens in 5425s (5157.7 tok/s),\nrequests=1612 retries=19`. The 19 retries were HTTP 503 at 13:33 and 14:17, all recovered. **91.2\nreplica-minutes, $1.23** (`embeddings/costs.csv`, run `20261009T130234-1437c3`). The endpoint was paused\nat the end (`endpoint_meter.jsonl`: `paused`). The vectors are `[101,943 × 2,560]` float32, norms in\n[0.99999994, 1.0000001], with no NaN:\n\n```bash\n.venv/bin/python -c \"import numpy as np; v=np.load('embeddings/jua-4b-mixed/corpus/vectors.npy', mmap_mode='r'); \\\n n=np.linalg.norm(v, axis=1); print(v.shape, v.dtype, n.min(), n.max(), np.isnan(v).any())\"\n```\n\nThe 715 query vectors (`embeddings/jua-4b-mixed/queries/irpf/`, 2026-09-25) were reused: the\nquestions did not change, and `rag.py check` verifies them.\n\n### 8.5 P5: retrieval and evaluation\n\n```bash\nR=scripts/rag/rag.py\n.venv/bin/python $R check --embedding jua-4b-mixed > $S/rag_check.log 2>&1\n# \"Check: OK\": 104,574 chunks, 101,943 unique texts = corpus vectors, 715 query vectors, 715 questions,\n# 1,916 references, 0 not in the corpus, 453 documents, 0 without chunks\n.venv/bin/python $R retrieve --embedding jua-4b-mixed --force > $S/rag_retrieve.log 2>&1\n# exit 0, but warnings \"strategy S1: 21497 chunk rows, strategies.yaml expects 26364 (other chunk file?)\" (all 5)\n# -> scripts/rag/strategies.yaml: expected_rows updated to 21,497 / 73,118 / 77,080 / 73,118 / 77,080 and its\n# header comment to the new chunk file (SHA-256 a6087b7f…326a); then again:\n.venv/bin/python $R retrieve --embedding jua-4b-mixed --force > $S/rag_retrieve.log 2>&1 # exit 0, 0 warnings, 38 s\n# texts per strategy: S1 21,458; S2 72,960; S3 76,922; S2c 70,500; S4 74,462\n.venv/bin/python $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf \\\n --eval-id v2d_either_containment_skip --comparisons S1:S2,S2:S3,S2:S2c,S3:S4,S1:S2c \\\n > $S/rag_evaluate.log 2>&1 # exit 0, 45 s\n```\n\nOutput: `runs/retrieval/jua-4b-mixed/irpf/eval/v2d_either_containment_skip/` (`report.md`, `metrics.csv`,\n`comparisons.csv`, `reachability.csv`, `manifest.json`; `per_item/per_question/metrics_by_chapter`\nare gitignored). The settings are the same as `v2c`: annex rule `either`, containment de-duplication,\noverflow `skip`, Qwen3-token budgets, 10,000 bootstrap resamples, seed 13. The `v2c` evaluation folder\nis untouched. Its rankings were replaced, as in R9, and can only be regenerated with the 2026-10-08\nvectors on the other computer.\n\n---\n\n## 9. Updated IR result (`v2d`) vs 2026-10-08 (`v2c`)\n\n**Gold.** 1,724 document items (1,725 before: 144-05 dropped), 1,958 article and 2,230 provision items.\nUnreachable: 13 articles (the treaty articles, unchanged) and **48 provisions (57 before)**. The 8\nre-mapped references and 142-03/157-01 became reachable. Provision oracle 0.969 (0.965 before).\n\n### 9.1 Recall at 4k tokens, all resolved gold (v2c → v2d)\n\n| Level | S1 | S2 | S3 | S2c | S4 |\n|---|---|---|---|---|---|\n| document | 0.604 → 0.605 | 0.665 → **0.667** | 0.652 → 0.655 | 0.631 → 0.636 | 0.627 → 0.632 |\n| article | 0.379 → 0.383 | 0.473 → **0.473** | 0.464 → 0.465 | 0.428 → 0.431 | 0.426 → 0.428 |\n| provision | 0.347 → 0.353 | 0.361 → **0.362** | 0.361 → **0.362** | 0.321 → 0.324 | 0.334 → 0.338 |\n| provision, sub-article gold (366 q.) | 0.313 → 0.316 | 0.424 → **0.425** | 0.409 → 0.414 | 0.370 → 0.368 | 0.367 → 0.371 |\n| provision, whole-article gold (429 → 430 q.) | 0.337 → **0.344** | 0.266 → 0.268 | 0.270 → 0.270 | 0.237 → 0.242 | 0.259 → 0.262 |\n| document, non-statutory gold (195 q.) | 0.669 → **0.666** | 0.628 → 0.626 | 0.611 → 0.614 | 0.628 → 0.633 | 0.606 → 0.611 |\n\n### 9.2 Recall by budget (v2d, all resolved gold)\n\n| Level | Strategy | 1k | 2k | 4k | 8k | 16k |\n|---|---|---:|---:|---:|---:|---:|\n| document | S1 | 0.372 | 0.479 | 0.605 | 0.718 | 0.803 |\n| | S2 | **0.489** | **0.575** | **0.667** | **0.764** | **0.832** |\n| | S3 | 0.482 | 0.564 | 0.655 | 0.745 | 0.815 |\n| | S2c | 0.445 | 0.538 | 0.636 | 0.731 | 0.808 |\n| | S4 | 0.444 | 0.533 | 0.632 | 0.717 | 0.795 |\n| article | S1 | 0.170 | 0.266 | 0.383 | 0.480 | 0.566 |\n| | S2 | **0.307** | **0.388** | **0.473** | **0.569** | 0.650 |\n| | S3 | 0.305 | 0.379 | 0.465 | 0.567 | **0.661** |\n| | S2c | 0.273 | 0.347 | 0.431 | 0.531 | 0.619 |\n| | S4 | 0.271 | 0.348 | 0.428 | 0.531 | 0.627 |\n| provision | S1 | 0.157 | 0.239 | 0.353 | 0.456 | 0.533 |\n| | S2 | 0.188 | **0.262** | **0.362** | 0.471 | 0.566 |\n| | S3 | **0.194** | 0.261 | **0.362** | **0.484** | **0.586** |\n| | S2c | 0.164 | 0.226 | 0.324 | 0.440 | 0.542 |\n| | S4 | 0.171 | 0.231 | 0.338 | 0.452 | 0.560 |\n\nContext precision (provision, 4k): S1 0.117, S2 0.145, S3 0.160, S2c 0.163, S4 0.176. S3 keeps its\nadvantage at large budgets (16k: 0.123 vs S2 0.078).\n\n### 9.3 Paired comparisons (recall, budget view; difference [95 % CI], permutation p)\n\n| Pair | Level | 1k | 4k | 16k |\n|---|---|---|---|---|\n| S2 − S1 | document | +0.117 [+0.092, +0.142] p<0.001 | +0.062 [+0.042, +0.082] p<0.001 | +0.029 [+0.015, +0.044] p<0.001 |\n| S2 − S1 | article | +0.138 [+0.112, +0.165] p<0.001 | +0.090 [+0.067, +0.113] p<0.001 | +0.084 [+0.065, +0.104] p<0.001 |\n| S2 − S1 | provision | +0.030 [+0.008, +0.053] p=0.007 | +0.009 [−0.016, +0.035] p=0.46 | +0.033 [+0.016, +0.051] p<0.001 |\n| S3 − S2 | document | −0.007 [−0.014, −0.001] p=0.03 | −0.011 [−0.021, −0.003] p=0.01 | −0.018 [−0.026, −0.010] p<0.001 |\n| S3 − S2 | article | −0.003 p=0.53 | −0.008 p=0.11 | +0.011 [−0.001, +0.024] p=0.07 |\n| S3 − S2 | provision | +0.006 p=0.12 | −0.001 p=0.90 | +0.020 [+0.007, +0.033] p=0.003 |\n| **S2c − S2** | document | −0.043 [−0.061, −0.026] p<0.001 | −0.031 [−0.045, −0.018] p<0.001 | −0.024 [−0.034, −0.015] p<0.001 |\n| **S2c − S2** | article | −0.034 [−0.054, −0.015] p<0.001 | −0.041 [−0.058, −0.025] p<0.001 | −0.031 [−0.044, −0.019] p<0.001 |\n| **S2c − S2** | provision | −0.023 [−0.038, −0.009] p<0.001 | −0.038 [−0.054, −0.023] p<0.001 | −0.024 [−0.035, −0.014] p<0.001 |\n| **S4 − S3** | document | −0.038 [−0.056, −0.021] p<0.001 | −0.023 [−0.037, −0.009] p<0.001 | −0.020 [−0.029, −0.011] p<0.001 |\n| **S4 − S3** | article | −0.033 [−0.053, −0.014] p=0.001 | −0.037 [−0.053, −0.021] p<0.001 | −0.034 [−0.048, −0.021] p<0.001 |\n| **S4 − S3** | provision | −0.023 [−0.037, −0.009] p=0.002 | −0.024 [−0.038, −0.010] p<0.001 | −0.026 [−0.039, −0.014] p<0.001 |\n| S2c − S1 | provision | +0.007 p=0.54 | −0.029 [−0.053, −0.005] p=0.02 | +0.009 p=0.30 |\n\n(The p-values are rounded; the permutation test floor is 0.0001. All rows are in `comparisons.csv`.)\n\n### 9.4 Reading\n\n- **Conclusions unchanged.** Sub-article units help (S2 − S1: +9 article points and +11 sub-article\n provision points at 4k). The caput sentence hurts (S2c − S2 and S4 − S3: −2 to −4 points at every\n level and budget, all significant). Groupings are about neutral for recall and better for context\n precision at 8k/16k. The size and significance of every v2c difference is reproduced, to within 0.01.\n- **Why the averages barely move.** The fixes touch few gold items: 10 reference pairs, 1 dropped\n reference, and the treaty documents of the N3 questions (142–160). The removed documents were\n distractors that were rarely retrieved. The corpus shrank by 12 % in chunks, and S1 gains the most\n (+0.006 provision, +0.007 whole-article), which suggests that some old distractors were long\n articles of the two removed codes. Four things changed at once: corpus, chunks, gold and vectors\n (a fresh full embedding). A per-question attribution would need the v2c per-item tables, which are\n on the other computer.\n- **The N3 treaty items now have content** (`per_item.csv.gz`, `rank_full`, S1/S2/S3):\n 142-03 `decreto_56435 art34_cpt_ali4` 17/34/36; 157-01 `decreto_5128 annex art21_cpt_ali4` 86/6/6;\n 151-02 `decreto_57784 art15` 10/13/13; 151-01 `decreto_50656 art47` 134/271/190; 153-02 `decreto_67542\n art141` 259/507/418. Before the statutory fix their `ART` chunks held only \"Artigo N\", so the\n article chunk could not match the question at all.\n- **Non-statutory document recall** is stable (S1 0.666, S2 0.626). S1 > S2 there is expected:\n non-statutory units are the same `TXT` chunks in every strategy, and S2's larger pool of statutory\n sub-article chunks competes for the same budget.\n\n---\n\n## 10. Full reproduction sequence (from the committed state `a94c2bf` + the user's two `.docx` fixes)\n\n```bash\n# 0. inputs\ngit -C ../br-taxqa-document-fetcher log -1 --format=%H # c7f4b8faf8b8df84520e6e957d7a0890513f4a52\ngit -C ../lexml_parser_non_statutory log -1 --format=%H # e8c3d1ee72ec6e37320bf27bbd540411d40bc405\ngit -C ../lexml-parser-projeto-lei log -1 --format=%H # 4c85e81de4bffaa7cdacb4b405f0d04d66e87bd5\nsha256sum \"$(readlink -f /usr/local/bin/linkertool)\" # 6b4cf768…b28f (lexml-linker 51874d9)\n# referee cache: ../lexml_parser_non_statutory/.cache/referee (661 answers); without it, ~31 new\n# answers are bought and borderline headings may differ (§4)\n\n# 1. statutory LexML (only to verify; byte-identical to lexml/articulados, §5.2; 28 min)\n(cd ../lexml-parser-projeto-lei && LC_ALL=C.UTF-8 mvn -q -Ponejar package -DskipTests)\npython3 ../lexml-parser-projeto-lei/scripts/batch_parse.py --no-justificativa \\\n --linker /usr/local/bin/linkertool original/articulados <out>\n\n# 2. non-statutory LexML (§8.1)\n(cd ../lexml_parser_non_statutory && set -a && . ./.env && set +a && \\\n LC_ALL=C.UTF-8 PYTHONPATH=src python3 -m lexml_nonstat parse --emitter=generico-aninhado \\\n --generation=proposed --referee=api --referee-cache=.cache/referee \\\n --linker=/usr/local/bin/linkertool --linker-cache=.cache/linker_51874d9 \\\n --metadata ../br-taxqa-r_v2.0/scripts/lexml/nonstat_metadata.tsv \\\n -o ../br-taxqa-r_v2.0/lexml/nao_articulados_new \\\n ../br-taxqa-r_v2.0/original/nao_articulados/*.docx ../br-taxqa-r_v2.0/lexml/nao_articulados/_text/*.txt)\n# then swap folders keeping _text/ and PARSER_VERSION (§8.1)\npython3 scripts/lexml/nonstat_lexml_map.py\n\n# 3. segmentation (§8.2)\n.venv/bin/python scripts/segmentation/segment_all.py --jobs 16 --overwrite --allow-count-change \\\n --variants caput --frozen <R7 chunks_all.csv.gz> --frozen-lexml-rev 280121b\n\n# 4. dataset (§8.3)\npython3 scripts/dataset/build_v2_dataset.py --questions ../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json\npython3 -m pytest -q scripts/dataset/tests\n\n# 5. embeddings (§8.4; ~93 min, ~$1.2)\n.venv/bin/python scripts/embedding/embed.py corpus --model jua-4b-mixed --overwrite --resume --no-progress\n\n# 6. retrieval and evaluation (§8.5)\n.venv/bin/python scripts/rag/rag.py check --embedding jua-4b-mixed\n.venv/bin/python scripts/rag/rag.py retrieve --embedding jua-4b-mixed --force\n.venv/bin/python scripts/rag/rag.py evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf \\\n --eval-id v2d_either_containment_skip --comparisons S1:S2,S2:S3,S2:S2c,S3:S4,S1:S2c\n```\n\n### 10.1 Checksums of this run\n\n| File | SHA-256 |\n|---|---|\n| `segmented/chunks_all.csv.gz` | `a6087b7f19ff5b02cc0863523b6dd423f6feddf291fe9f11e7f08d45146c326a` |\n| `original/nao_articulados/sc_cosit_140_20150605.docx` | `65aa4fd94549bb96bc4041c52e5e8858abc2948e78a1ea315bc3ba98ba3889e5` |\n| `original/nao_articulados/sc_cosit_194_20150805.docx` | `6452628c187a0d6ece83569886d4ae5383ccae071f2f09e0a4cb6a9a89875403` |\n| parser jar (`4c85e81` build) | `a018af018ffd88ccd96316418df78788a443201aa4217a6545fecac59f6c6c57` |\n\n### 10.2 Still open\n\n- ~~Commit~~ **done**: (1) `a80a5cf` the two `.docx` fixes + `lexml/nao_articulados`; (2) `f13bcf3`\n `segmented/`; (3) `31293c5` `dataset/`; (4) `ffbc7a3` `scripts/rag/strategies.yaml` + `embeddings/`\n manifests and costs + `runs/` + this note. Then, on the clean tree at `ffbc7a3`:\n `python3 scripts/dataset/build_v2_dataset.py --questions ../br-taxqa-document-fetcher/questions_QA_2024_v1.1.json`\n (exit 0, same summary line as §8.3). Only `build_report.json` changed (`commit ffbc7a3…`, `dirty: false`,\n timestamp); the three `.jsonl` files were byte-identical. Committed with this status update.\n- ~~X1/X2~~ **done**: `lexml/articulados/PARSER_VERSION` now names `4c85e81` and jar sha256 `a018af01…6c57`\n (old jar hash kept for the record) and adds a `verification` line pointing at §5.2.\n- ~~X5~~ **done**: `rm -rf ../lexml_parser_non_statutory/.cache/linker` (16,315 pre-`51874d9` entries, 20 MB;\n gitignored there). `.cache/linker_51874d9` and `.cache/referee` remain.\n- ~~X7~~ **done**: `diff_vs_frozen` compares variant by variant (key + `variante`) when the frozen set has a\n `variante` column, and keeps the old caput-vs-frozen comparison for older sets; it reports `by_variant`.\n New `scripts/segmentation/tests/test_diff_vs_frozen.py` (3 tests). On the real data (R7 frozen set,\n `--frozen-lexml-rev 280121b`): 364 unchanged files, 31,605 rows compared, **0 differ** (was 8,555).\n- ~~Stale test~~ **fixed**: `test_python_segmenters.py::test_loose_offset_keeps_intervals_disjoint` failed on\n the committed tree too (not from X7). It expected a loose tax table before LIVRO I in\n `decreto_9580_20181122.anexo1.xml` (RIR/2018). That table was a **parser defect of the old parse**: the\n `.docx` writes art. 677, VI as \"V I\", so `art677` had only items I–V and the item's 2015 table\n (`anexo1_tab2`, a duplicate-looking copy of art. 122, VI's) was pushed before LIVRO I as loose text\n (`DocumentoGenerico`). The re-parse `a94c2bf` puts it in `art677_cpt_inc6` (`DocumentoArticulado`), which is\n right. The test now uses the fixture `in_rfb_1500_20141029.anexo8.xml` (five loose RRA tables after the XSL\n `DSP` of item V; the XML matches the `.docx`, where items II–IV have no caption paragraphs), and a new\n `test_rir_2018_tax_table_is_in_its_article` pins the RIR/2018 fix. Segmentation suite: 49 passed.\n Leftover: RIR/2018 still has one loose paragraph, the footnote mark `*` that followed the misplaced table;\n it is a one-character `TXT` chunk (`articulacao_p1-p1`) in the corpus, harmless for retrieval.\n- The fetcher's dirty submodule (`br_legal_parser`) makes `fetcher_dirty: true`.\n- Vectors and rankings exist only on the computer that made them. Back up `embeddings/jua-4b-mixed/corpus/`\n (≈ 1 GB) or release it on the HF Hub, so a later `--extend` run can reuse it.\n- Results note O1 (treaty texts), O5 (nonstat tests), O8 (other embedding models) and review note N2\n (Q029 and Q576 references) are unchanged.\n","20261011_224049_gold_answer_nuggetization_plan_v2.md":"# Gold-Answer Nuggetization and Nugget-Based Answer Evaluation — Plan v2\n\n**Generated:** 2026-10-11 22:40:49 (local time, from `date +%Y%m%d_%H%M%S`)\n**Status:** plan only. Nothing in `scripts/nuggets/` has been implemented or run.\n**Status update (2026-10-12):** a minimal phase 0 is implemented and a 10-question preview has been\nrun. Current state, prompts and missing pieces: `scripts/nuggets/README.md`. Decisions that amend\nthis plan (judge prompt and R8, R2 granularity, pointer sentences, git layout, measured costs):\n`docs/20261012_114025_*`, `docs/20261012_154616_*` and `docs/20261012_160349_*`.\n**Revised 2026-10-11 (later):** the human audit cannot be run in the near term. It is **postponed**,\nnot dropped. §3.5 (nugget robustness without people), §5.6 (robustness of the conclusions) and §5.7\n(known-answer tests, which also replace the human judge calibration) take its place, and the release\nis labelled as automatic (D5, D10, W10).\n**Revised 2026-10-11 (latest):** a third nugget set by **Qwen3.8-Max** replaces the repeated GPT\ncreation runs; stability is measured as **agreement across model families**. The cost estimate now\ncovers **every provider**, not only OpenAI, and the OpenAI part uses the lean option (D8, D11, W11,\n§3.5.2, §6.4). **Medium reasoning effort** is fixed for every LLM call (D12), and the Gemini judge\ncandidate is **Gemini 3.8 Flash**, with 3.1 Pro only on a check subset (D2, §5.7). Qwen3.8-Max does\nnot replace Gemini: without a batch discount in the Singapore region it is not cheaper (§6.4).\n**Supersedes:** `docs/20260926_112714_gold_answer_nuggetization_plan.md` (**v1**). v1 is still the\nreference for the literature review (v1 §1), the audit check tables (v1 §3.4.1) and the rationale\nfor the audit (v1 §3.4.4). Where this note and v1 differ, this note wins.\n**Goal (unchanged):** turn the 715 gold answers of BR-TaxQA-R into **legal nuggets** (short,\nself-contained, atomic statements) and score the answers of the RAG generator LLMs against them, so\nthe segmentation strategies can be compared on answer quality, not only on retrieval.\n\n---\n\n## 0. What changed since v1 (2026-09-26 → 2026-10-11)\n\n| # | Work done after v1 | Effect on this plan |\n|---|---|---|\n| W1 | **Dataset v2.0 built** (`dataset/`, `scripts/dataset/build_v2_dataset.py`; `docs/20260927_180401_*`). `questions.jsonl` already has `answer_cleaned` as one string (lines joined with `\\n`) | `prepare` reads `dataset/questions.jsonl` instead of downloading v1.0 from the HF Hub (§2). Nuggets become a 4th HF config, `nuggets`, as already foreseen in the dataset note |\n| W2 | **Gold answers checked unchanged** after every rebuild: 715 questions, 698,724 characters of `answer_cleaned`, median 84 words, p90 316, max 3,316, 20 answers under 80 characters (re-measured 2026-10-11) | Nuggets do **not** depend on the corpus. The corpus rebuilds of 2026-10-08/09 do not invalidate them, and future corpus fixes will not either. Only the legal-provision score (§5.5) depends on the corpus and on `references.jsonl` |\n| W3 | **References resolved at provision level** (`docs/20260927_213420_*`, rebuild of 2026-10-09): 1,916 references, 0 `not_in_corpus` (v1 counted 42), nested `fragment_id`s (`art12_par1_inc2`), `matchable` flags, 13 unmatchable fragments (treaty articles) | §5.5 matches system citations against `fragment_id`s directly. `scripts/dataset/citations.py` parses both citation orders; `lexml-linker` does not parse the act-first order (\"Lei nº 11.482, de 2007, art. 1º\"), so `citations.py` is the extractor of system citations, with the linker only as a cross-check |\n| W4 | **Retrieval (RAG Phase 1) done** (`scripts/rag/`, `docs/20260927_222210_*`, `docs/20261009_121822_*` §9). Strategies are now **S1, S2, S3, S2c, S4** (caput variants, `docs/20261005_184116_*`). Result `v2d`: S2 best at 4k; the caput sentence hurts at every level (p ≤ 0.002); groupings neutral for recall | The answer grid has five strategies, not three. The paired comparisons of interest are S2 − S1 (main hypothesis), S3 − S2, S2c − S2 and S4 − S3 (§5.3). Retrieval recall is only a proxy; whether a partial hit is enough to answer is exactly what nugget scoring decides |\n| W5 | **Generation (RAG Phase 3) not implemented.** No system answers exist yet (`runs/` holds only `retrieval/`) | Nugget creation, validation and the automatic robustness checks (phases 1–3) can run **now**. Judge selection (phase 4) needs only the gold answers and their corruptions (§5.7), so most of it can run before the first answer runs too |\n| W6 | **FiscalQA Pro comparison** (`docs/20260929_111356_*` §5): adopt deterministic value checks, year-aware `contradicts`, a temporal slice, a reference date in the generation prompt and cluster-aware statistics | Folded into creation (rule R8, the year stays attached to every value, §3.2), validation (§3.3) and scoring (§5.3, §5.4). The reference date belongs to the RAG generation prompt |\n| W7 | **OpenAI reasoning models reject `temperature`.** Measured in the sibling parser: `gpt-5.6-luna` returns `400 unsupported_value` for `temperature=0`; only the default is accepted (`../lexml_parser_non_statutory/docs/20260916_173138_openai_referee_temperature_400.md`). The Sol models are reasoning models too | v1's \"temperature 0 where the API allows it\" becomes: **no `temperature` for OpenAI reasoning models**; pin model id + `reasoning.effort` + prompt hash, and make reruns exact through the **raw-response cache**, not through decoding settings (§6.3) |\n| W8 | **Newer OpenAI models released.** `gpt-6.1-sol` came out on 2026-09-29 (DevDay), three days after v1 | Creator choice settled on **`gpt-6.1-sol`** (§6.1). The user asked for an OpenAI frontier model as creator |\n| W9 | **The shared LLM client** (RAG plan §7.5, recommended) does not exist yet | Whichever of nuggets / RAG Phase 3 is built first creates `scripts/llm_client/`. With W5, that is likely the nugget code (§7) |\n| W11 | **Cost review** (2026-10-11): the earlier ≈ $95–135 covered OpenAI only, and half of it was repeated GPT runs and a prompt-iteration buffer at high effort. The Gemini roles had not been costed | Repeated GPT runs replaced by a Qwen3.8-Max set (§3.5.2); prompt iteration on the 30 pilot questions only; all providers in one cost table (§6.4); multi-set **scoring** flagged as the real cost driver |\n| W10 | **No human audit in the near term** (user, 2026-10-11) | Without people, nugget **accuracy** cannot be measured, only reduced and estimated by models. The plan therefore (1) strengthens automatic error reduction (§3.5), (2) shows that the paper's **comparisons** do not depend on nugget errors (§5.6), and (3) tests nuggets + judge on answers whose correct score is known by construction (§5.7). The judge calibration of v1 §4.4 also relied on human labels; §5.7 replaces it |\n\n---\n\n## 1. Decisions (revised)\n\n| # | Topic | Decision |\n|---|---|---|\n| D1 | Generator LLMs | Unchanged: **OpenAI**, **Maritaca Sabiá and Sabiazinho**, **DeepSeek** |\n| D2 | Judge | **Revised (2026-10-11):** candidates **Gemini** and an open-weight **Qwen**, **selected with the known-answer tests (§5.7)** while human labels are not available. The Gemini candidate is **`gemini-3.8-flash`**; `gemini-3.1-pro-preview` runs on a 10 % subset of the tests and replaces Flash only if it is clearly better there (balanced accuracy > 0.05 higher). Qwen is primary if its balanced accuracy there is within ≈ 0.05 of Gemini's. An **OpenAI judge on a subset** measures self-preference. Human calibration (v1 §4.4) is added when the audit happens |\n| D3 | Nugget creator | **Revised (2026-10-11): `gpt-6.1-sol`**, OpenAI Responses API, `reasoning.effort = medium` (D12), Structured Outputs (strict JSON schema), Batch API for the full run. `gpt-5.6-sol` is not used (§6.1). The [LN] baseline (prompt of v1 §1.1 + a small model) is optional; if run, use `gpt-5.6-luna`, since `gpt-5.4-nano` is two generations old |\n| D4 | GPU endpoints | Unchanged: only if Qwen is served ourselves |\n| D5 | Human audit | **Revised (2026-10-11): postponed.** Replaced for now by the automatic robustness program (§3.5, §5.6, §5.7). When it happens, it follows v1 §3.4 (annotators: the user and another team member), or a minimal version (§3.4) |\n| D6 | Legal-provision score | Unchanged (secondary metric), now on `fragment_id`s and `citations.py` (W3, §5.5) |\n| D7 | `contradicts` label | Kept, plus a deterministic **value-conflict** and **temporal-substitution** check (W6, §5.4) |\n| D8 | Nugget-set robustness | **Revised (2026-10-11): three full nugget sets from three families**: `gpt-6.1-sol` (primary), **Gemini** (`gemini-3.1-pro-preview`) and **Qwen3.8-Max** (Alibaba Model Studio API). Neither Gemini nor Qwen is a generator family (D1). With no human audit, agreement across the sets is the **main** robustness argument (§3.5.2, §5.6). The main comparisons are scored with all three sets; the rest of the grid with the primary set only (§6.4) |\n| D9 | **New:** question scope | All 715 questions are nuggetized. Slices (procedure-only, temporal, short answers) are flags, not exclusions |\n| D11 | **New:** model per role | Creation: `gpt-6.1-sol`, Batch, medium effort (D12). Second and third sets: `gemini-3.1-pro-preview` (Batch) and `qwen3.8-max`. Auditors: Gemini 3.1 Pro and Qwen3.8-Max. Mechanical roles (alignment, round-trip reconstruction, corruption rewrites): `gemini-3.8-flash` (Batch). Judge candidates: `gemini-3.8-flash` (3.1 Pro on a check subset) and an open-weight Qwen on our endpoint (D2). Qwen3.8-Max is **not** a judge candidate: it is not cheaper than Gemini (§6.4), it would make both candidates Qwen-family, and it created the third nugget set. Run the Gemini Flash roles **before 2027-01-01**, when its prices double |\n| D12 | **New:** reasoning effort | **Medium for every LLM call** (user, 2026-10-11, to limit cost): `reasoning.effort: medium` for `gpt-6.1-sol`; the equivalent setting for Gemini (a medium thinking level where the model offers one, otherwise a thinking budget of ≈ 2k tokens) and for Qwen3.8-Max (thinking on, thinking budget ≈ 2k tokens). The exact Gemini and Qwen parameters are checked in phase 0 and recorded in `models.yaml`. The pilot no longer compares effort levels; it reports quality at medium, and any change of effort is a new decision by the user |\n| D10 | **New:** release label | The nuggets are frozen and released as **`nuggets/gold/v0-auto/`** (\"automatic, not human-audited\"), with every raw response, flag and robustness report. A later audit produces `v1` as a patch on it. The paper describes the error estimates as **model-based**, never as measured accuracy |\n\n---\n\n## 2. Input\n\n- **Source:** `dataset/questions.jsonl` (v2.0, built by `scripts/dataset/build_v2_dataset.py`), fields\n `question_number`, `question_summary`, `question_text`, `answer_cleaned`. `prepare` records the\n SHA-256 of the file and of each prepared text, and the dataset build commit\n (`dataset/build_report.json`). When v2.0 is on the HF Hub, the manifest also records the Hub\n revision. The text is identical to v1.0/v1.1 (checked in v1 §2 and again on 2026-10-11, W2).\n- **Prompt input:** `question_summary` + `question_text` + `answer_cleaned`. The summary (\"OBRIGATORIEDADE\")\n is new relative to v1. It costs a few tokens and helps the model name the subject in each nugget.\n- **Size** (o200k tokenizer, question + answer): **195k tokens in total**, median 156, p90 523,\n max 6,306 (the 3,316-word answer). One call per question is enough; no chunking.\n- **Cases the prompt and validator must handle** (unchanged from v1 §2): 20 answers under 80\n characters; long enumerations (one nugget per item); 50 answers still pointing to other questions;\n program/PGD instructions; embedded citations (to `legal_basis`, not to the text); `linked_questions`\n are not expanded.\n- **New: temporal values.** 77 answers contain R$ amounts and 86 contain percentages\n (`docs/20260929_111356_*` §4.3). The corpus holds **other years' values of the same provisions**\n (Lei 9.250 art. 8º II b items 1–10; Lei 11.482 art. 1º tables up to May 2025). A nugget that states\n \"o limite é R$ 3.561,50\" without its year cannot tell a correct AC-2023 answer from a wrong-year\n one, so the year must be part of the nugget (rule R8).\n\n---\n\n## 3. Nugget creation\n\n### 3.1 Schema\n\nAs in v1 §3.1 (`nugget_id`, `question_number`, `text`, `importance` vital/okay, `category`,\n`legal_basis`, `source_span`, `ordinal`), plus:\n\n- `values`: list of `{raw, kind (brl|pct|date|count|deadline), normalized, reference_period}`, filled\n by the **validator** from `text`, not by the LLM. It drives the value checks of §3.3 and §5.4.\n- `flags`: `procedimento_pgd`, `temporal` (has a value, or cites a provision amended after\n 2024-05-03), `short_answer`. Question-level flags are copied to every nugget so slices are one\n filter.\n\nThe pydantic model is the single source: the JSON schema sent to the API (Structured Outputs,\n`strict: true`) is exported from it, without the validator-filled fields.\n\n### 3.2 Prompt rules (pt-BR, `scripts/nuggets/prompts/create_v1.pt.md`)\n\nRules R1–R7 are v1 §3.2 rules 1–7: self-contained nuggets; atomic, but a condition stays with its\nrule; exact values and technical terms verbatim; always a verdict nugget; nothing outside the answer;\ncitations in `legal_basis`; schema output. Added:\n\n- **R8 (temporal anchor).** Every nugget that states an amount, rate, limit or deadline names the\n period it applies to (exercício 2024 / ano-calendário 2023, or the period the answer gives). If the\n answer gives no period, the nugget uses the question's period, never a year the model knows from\n elsewhere.\n- **R9 (no updating).** The model must not \"correct\" a value to the law it knows. `gpt-6.1-sol` has a\n knowledge cutoff of 2026-04-30, so it knows the 2025 tables (e.g. Lei 15.191/2025, Lei 15.270/2025).\n The gold answer is the truth even when the law changed later. The numeric grounding check (§3.3)\n enforces this mechanically.\n- **R10 (worked examples).** Numbers that appear only in a worked example (e.g. Q617, Q620) give no\n nugget unless the example states a rule. This also keeps computed figures out of the value checks.\n\nThe prompt has a fixed prefix (instructions, schema, two worked examples: one short Sim/Não answer\nand one enumeration like Q001) and a variable suffix (the question). The fixed prefix is\n≈ 3k tokens and identical across calls, so OpenAI prompt caching bills it at the cached rate.\n\n**One call or two (importance separately)?** Unchanged: the pilot decides (§4, phase 1).\n\n### 3.3 Automatic validation (`validate`, no LLM)\n\nv1 §3.3 (schema, unique ids, numeric grounding as a hard error, `source_span` found in the answer,\ndedupe, coverage of answer lines, ≥ 1 vital per question, `validation.json`), plus:\n\n- **Value extraction** with pt-BR normalization (`R$ 30.639,90` ≡ `30639.90`; `7,5%` ≡ `0.075`;\n `30 de abril de 2024` ≡ `2024-04-30`; amounts written in words in parentheses are ignored). The\n same module is reused at scoring time (§5.4), so creation and scoring normalize values the same\n way.\n- **Period check (R8):** a `valor_prazo` nugget without a year or period expression is a warning, sent\n to the review queue.\n- **Out-of-answer year:** a year in the nugget that is not in the question or answer is a hard error\n (catches R9 violations that change only the year).\n\n### 3.4 Human audit (postponed, D5)\n\nWhen it happens, it follows v1 §3.4: checks C1–C6, guideline v1 → calibration on 10 answers → guideline v2,\nstratified sample of 60 questions + every validator flag, annotator A on all 60, B on 12, adjudication,\nspecialist session for escalations, report with 95 % CIs and κ, **freeze gate** (C1 ≥ 95 %, ≥ 90 % of\nanswers with no missing vital fact). Two changes:\n\n- The stratification adds the **temporal** flag, so value-bearing answers are in the sample in\n proportion (≥ 10 of the 60).\n- The LLM cross-check over all 715 answers (v1 §3.4.4) is run by **Gemini**, the family not chosen as\n creator. Its flags go to the review queue; they are not labels.\n\nThe audited set is `nuggets/gold/v1/` (SHA-256), released as a patch on `v0-auto` (D10).\n\n**Minimal version**, if only a little time becomes available: one annotator, 20 answers drawn at\nrandom from the same strata (with ≥ 4 temporal answers), checks C1, C4 and C5 only, about 1–2 h. It\nturns the model-based error estimates of §3.5 into a measured (if wide) interval, and checks whether\nthe LLM auditors' flags agree with a person.\n\n### 3.5 Nugget robustness without the human audit (W10)\n\nFive layers, from cheapest to most expensive. None of them measures accuracy the way the audit\nwould: models share blind spots with the creator. Together they remove most mechanical and\nsingle-model errors, and they produce **model-based** error estimates for the paper.\n\n#### 3.5.1 Mechanical checks (no LLM)\n\n§3.3 becomes the main safety net. Added for the no-audit setting:\n\n- **Enumeration count:** for answers with numbered or lettered items (\"1 -\", \"a)\"), the number of\n items whose line is covered by some `source_span` must equal the number of items, unless R10 or a\n guideline rule (pointers to other questions) excludes the item. A missing item is a hard error.\n- **Self-containment regex (C2 proxy):** nuggets that start with or contain unresolved back-references\n (\"esse\", \"essa\", \"tal\", \"o referido\", \"o mesmo\", \"a mesma\", \"neste caso\", \"nessa hipótese\") or that\n mention \"o contribuinte\" when the question limits who is meant are warnings, sent to the repair\n queue (§3.5.3).\n- **Verdict check:** if the answer starts with \"Sim\" or \"Não\", exactly one `resposta_direta` nugget\n must exist and carry the same polarity.\n- All warnings that survive repair are listed per nugget in the release (`flags`).\n\n#### 3.5.2 Cross-family agreement (replaces repeated GPT runs)\n\nRepeated runs of the same model measure only its sampling noise: a mistake GPT makes every time\n(e.g. always dropping a given condition) is \"stable\" across three GPT runs. Three model families have\ndifferent blind spots, so their agreement is the stronger signal, and it costs less (W11).\n\n- The three sets of D8 (GPT, Gemini, Qwen3.8-Max) are made with the **same prompt** (R1–R10, the same\n schema) and validated with §3.3.\n- Align them per question: first by `source_span` overlap, then by an LLM aligner\n (`gemini-3.8-flash`) for the rest.\n- Each primary nugget gets `stability` ∈ {3/3, 2/3, 1/3} (how many families produced a matching\n nugget) and `importance_agreement` (how many gave the same vital/okay label).\n- A fact present in **both** other sets but missing from the primary set, with a `source_span` in the\n gold answer, is an **omission candidate** for the repair step (§3.5.3).\n- Reported: share of 3/3 nuggets, share of vital labels with 3/3 agreement, per category. Unstable\n vital labels are the expected weak point (v1 §3.4.2); §5.6 tests whether they matter.\n- **Same-model noise** is still measured, on the 30 pilot questions only: two more `gpt-6.1-sol`\n runs, reported as a side number (how much of the cross-family disagreement is just sampling).\n\n#### 3.5.3 Two-auditor LLM review with a repair loop\n\n- Two auditors from families other than the creator apply checks **C1–C6** (v1 §3.4.1) to every\n question, comparing the nuggets with the **gold answer** (never with the law). Auditor 1 is\n **Gemini 3.1 Pro**; auditor 2 is **Qwen3.8-Max** (D11). Each audits the primary set, not its own\n family's set.\n- Inputs to the auditors: the question, the gold answer, the nuggets, and the omission candidates of\n §3.5.2 and §3.5.4.\n- **Repair:** items flagged by **both** auditors, plus hard validator warnings, go back to the creator\n with the auditors' reasons, in one repair call per question. The repaired nuggets go through §3.3\n and the auditors again. At most two repair rounds; what is still flagged by both auditors is\n dropped (C1 failures) or kept with a flag (other checks), and listed.\n- Items flagged by **one** auditor are kept and listed with the flag.\n- **Model-based error estimate:** before repair, the share of nuggets flagged by both auditors per\n check, with a 95 % CI over questions. Reported as \"flagged by two independent LLM auditors\", not as\n an error rate.\n\n#### 3.5.4 Round trip and cross-set alignment (omissions)\n\n- **Round trip:** `gemini-3.8-flash` writes an answer from the nuggets alone (no access to the gold\n answer). Qwen3.8-Max lists gold-answer statements missing from that reconstruction. These are omission\n candidates (C5 proxy), sent to §3.5.3.\n- **Cross-set alignment:** the alignment of §3.5.2 also gives the nugget-level agreement for each\n pair of sets (share of one set's nuggets matched in the other, both directions), which is reported.\n\n#### 3.5.5 Gold self-score (faithfulness through the judge)\n\nEvery candidate judge (§5.7) scores the **gold answer itself** against its own nuggets. A nugget that\nboth judges label `not_support` or `contradicts` against the text it was extracted from is either\nunfaithful or not self-contained, and goes to the repair queue. This is part of §5.7, run early.\n\n#### 3.5.6 Automatic freeze gate (replaces the human gate of v1 §3.4.3)\n\nProposed thresholds, to be confirmed after the pilot:\n\n| Gate | Threshold |\n|---|---|\n| Validation | 0 hard errors (numbers, years, spans, enumeration count, verdict polarity) |\n| Gold self-score | ≥ 98 % of nuggets `support` by both judges against the gold answer, after repair |\n| Two-auditor review | ≤ 2 % of nuggets still flagged by both auditors after repair |\n| Known-answer tests (§5.7) | sensitivity ≥ 0.90 on value, year and verdict corruptions for the selected judge |\n\nCross-family stability (§3.5.2) and set agreement (§3.5.4) are **reported, not gated**: there is no reference\nvalue for them. The set that passes is frozen as `nuggets/gold/v0-auto/` (D10).\n\n---\n\n## 4. Phases and gates\n\n| # | Phase | Output | Gate | Can start |\n|---|---|---|---|---|\n| 0 | Scaffold: `scripts/llm_client/` (providers `openai`, `gemini`, `openai_compat`, `fake`; cache; cost ledger), `scripts/nuggets/` package, `prepare` | `nuggets/gold/input/questions.jsonl` + manifest | Tests pass with `fake` | now |\n| 1 | **Pilot creation:** 30 stratified questions (the RAG plan's `stratified_30`, seed 13, so pilot answers can be scored later) × `gpt-6.1-sol` {1 call, 2 calls} at medium effort (D12); prompt iterations on these 30 only; two more GPT runs for same-model noise (§3.5.2); Gemini 3.1 Pro and Qwen3.8-Max on the same 30 with the winning prompt; the known-answer tests (§5.7) on the 30, with Flash and Pro, as a first look at the judge; optional [LN] baseline. The robustness checks of §3.5 run on the pilot too | `nuggets/pilot/…`, comparison report (nugget counts, reasoning tokens and cost per call **per provider**, validator errors, auditor flags, cross-family stability, gold self-score); a revised cost estimate | The user picks prompt and call mode from the report, with an informal read of a few questions (minutes, not an audit) | after 0 |\n| 2 | **Full creation** with `gpt-6.1-sol` (Batch API) + `validate`; **second and third sets** with Gemini 3.1 Pro (Batch) and Qwen3.8-Max (D8) | `nuggets/gold/v0/`, `nuggets/alt_gemini/v0/`, `nuggets/alt_qwen/v0/` | 0 hard validation errors | after 1 |\n| 3 | **Automatic robustness** (§3.5): alignment, two-auditor review, round trip, repair loop; gold self-score with both candidate judges (§3.5.5) | `nuggets/gold/v0-auto/` (frozen), `nuggets/robustness/` reports | Automatic freeze gate (§3.5.6) | after 2 |\n| 4 | **Judge selection** with the known-answer tests (§5.7) on gold, corrupted and wrong answers; value-hit and inter-judge agreement added once real runs exist | `nuggets/known_answer/` + report | Primary judge chosen; sensitivity / specificity per corruption type reported, incl. `contradicts` | after 3 (real-run part after the RAG Phase 3 pilot) |\n| 5 | **Scoring** of the answer grid with both nugget sets; robustness of conclusions (§5.6) | `nuggets/assignments/<run_id>/<judge>/`, `nuggets/scores.csv`, `nuggets/robustness/conclusions.md` | — | after 4 |\n| 6 | **Release:** code, `v0-auto` nuggets (HF config `nuggets`), robustness and known-answer reports, raw responses | HF dataset v2.0 + repo | README quick start works in a clean venv | after 5 |\n| 7 | *Later, optional:* human audit (§3.4, full or minimal) and human judge calibration (v1 §4.4) | `nuggets/gold/v1/` patch, `nuggets/calibration/` | Audit gate of v1 | when people are available |\n\nA dated `docs/` note records the decisions and results at the end of each phase.\n\n---\n\n## 5. Scoring system answers\n\n### 5.1 Input contract\n\nUnchanged: one JSONL per run, `{\"run_id\", \"question_number\", \"answer\"}`, plus a sidecar `run.json`.\nThe RAG plan (§7.4) already writes `runs/answers/<run_id>/answers.jsonl` in this form, with\n`context_id` and token usage per line. `run.json` carries the strategy (S1/S2/S3/S2c/S4), embedding,\nbudget or `k=0` / oracle, generator and prompt hash.\n\n### 5.2 Assignment call\n\nUnchanged (v1 §4.2): one judge call per (question, answer) with all nuggets of the question, labels\n`support` / `partial_support` / `not_support` / `contradicts`, short justification, Structured Outputs.\n\n### 5.3 Scores and statistics\n\n- V_strict (main), V, A_strict, A, W, contradiction rate (v1 §4.3).\n- **Slices:** with/without `procedimento_pgd`; **temporal** vs rest (W6); chapter; answer length.\n- **Paired comparisons** for the same generator, embedding and budget: **S2 − S1** (main), S3 − S2,\n S2c − S2, S4 − S3, and each strategy vs the oracle and `k=0`. Paired bootstrap or permutation over\n questions, **plus a cluster bootstrap** by P&R chapter (W6 item 5).\n- Answer **length** is reported per run, since recall rewards long answers.\n\n### 5.4 Deterministic checks next to the judge (new, from W6)\n\nFor every nugget with `values`:\n\n- **Value hit:** the normalized value appears in the system answer (with a per-kind tolerance;\n exact for R$ and dates). Reported as a separate score.\n- **Judge audit for free:** agreement between the judge's `support` and the value hit on these\n nuggets, per judge (§5.7). Disagreements are kept for the later human calibration.\n- **Value conflict:** the answer states a different value of the same kind in the same slot →\n deterministic `contradicts` candidate.\n- **Temporal substitution:** the conflicting value appears in the corpus as another period's value of\n the same provision (e.g. the 2025 band of Lei 11.482) → tagged `temporal_substitution`. This tests\n the hypothesis that S2 inciso chunks, which isolate one period with its year label, give fewer\n wrong-year answers than S1 article chunks.\n\n### 5.5 Legal-provision score (secondary, D6)\n\nAs v1 §4.5, updated by W3: gold = `references.jsonl` (`document_id`, `article_ids`,\n`provisions[].fragment_id`, `matchable`); system citations extracted with `scripts/dataset/citations.py`\n(both citation orders), resolved to `document_id` + `fragment_id`; `lexml-linker` as a cross-check.\nPrecision / recall / F1 at document, article and provision level, with the same \"unmatchable\" rules\nas the retrieval evaluation (`docs/20261008_133726_*` §3.1), so retrieval and answer citation scores\nare comparable.\n\n### 5.6 Robustness of the conclusions (W10)\n\nThe paper's claims are **comparisons** (S2 − S1, etc.), so the question to answer is not \"how good\nare the nuggets?\" but \"could nugget errors change the comparison?\".\n\n- **Three nugget sets (D8):** score every main comparison with the primary, Gemini and Qwen sets. Report Kendall τ between the strategy rankings and whether every\n paired difference keeps its sign and significance under each set. Agreement means the conclusion\n does not depend on the choice of creator.\n- **Perturbation test (no LLM, free):** re-score existing assignments after damaging the nugget set\n with a simulated error model, 1,000 replicates per setting:\n - random nugget **deletion** at 5, 10, 15, 20 % (omissions);\n - **vital ↔ okay flips** at 10, 20, 30 % (the least reliable label), and flips restricted to\n unstable labels (§3.5.2);\n - **targeted deletion** of `condicao` nuggets: conditions and exceptions are where sub-article\n chunks (S2) are expected to help, so losing them is the error most likely to *bias* S2 − S1, not\n just add noise;\n - deletion of nuggets flagged by one auditor (§3.5.3), as a \"pessimistic\" set.\n\n Report, per comparison, the share of replicates in which the difference keeps its sign and stays\n significant, and the **break-even error rate** at which it would flip. If S2 − S1 survives 15–20 %\n damage, the missing audit cannot plausibly overturn it.\n- **Score variants:** report V_strict, V, A_strict, A and W side by side. A conclusion that holds under\n A (which ignores importance) does not depend on the vital/okay labels.\n- **Stable-only scores:** recompute the main comparison on nuggets that all three families produced\n (stability 3/3, §3.5.2).\n\n### 5.7 Known-answer tests (nuggets + judge; replaces human judge calibration for now)\n\nAnswers whose correct labels are known **by construction**, built by script from the gold answers and\nnuggets. They test the nuggets and the judge together, and they are the basis for choosing the judge\n(D2) while human labels are missing.\n\n| Test answer | How it is built | Expected labels |\n|---|---|---|\n| **Gold** | the gold answer itself | every nugget `support` (also §3.5.5) |\n| **Value corruption** (V) | one value of a nugget with `values` changed in the gold text: ± a plausible step, or **another period's value of the same provision found in the corpus** (doubles as a temporal-substitution test) | target nugget `contradicts` (`not_support` counted as a partial detection); others `support` |\n| **Year corruption** (Y) | the year of a `valor_prazo` statement changed | target `contradicts` / `not_support`; others `support` |\n| **Verdict flip** (N) | leading \"Sim\" ↔ \"Não\" (and the verb negated where needed) | `resposta_direta` nugget `contradicts` |\n| **Omission** (D) | the `source_span` of one nugget deleted | target `not_support`; others `support` |\n| **Dropped condition** (C) | a condition clause (\"desde que\", \"exceto\", \"salvo\", \"caso\", \"se\") removed from the target span, rule-based where the clause is delimited, otherwise rewritten by `gemini-3.8-flash` and checked by diff that only the target span changed | target `partial_support` or `not_support`; others `support` |\n| **Wrong question** (W) | the gold answer of another question of the same chapter | almost all nuggets `not_support` |\n| **Empty** (E) | \"Não há informação suficiente nos dispositivos fornecidos.\" | all `not_support` |\n\n- **Size:** 715 gold + ≈ 1,500 corruptions (V and Y only where values exist; one D and one C per\n question where possible; N for the Sim/Não answers) + 715 wrong-question answers ≈ 3,000 judge calls\n per candidate judge. Gemini 3.1 Pro runs on a 10 % stratified subset (≈ 300 calls) only, to check\n that Flash is not clearly worse (D2).\n- **Metrics per judge and corruption type:** sensitivity (target nugget detected), specificity\n (non-target nuggets still `support`), `contradicts` precision, and the score drop of V_strict\n against the gold answer. Balanced accuracy over all types selects the primary judge (D2).\n- **On real runs** (after the RAG Phase 3 pilot): agreement between the two candidate judges (κ per\n label, Kendall τ of run rankings) and the judge–value-hit agreement of §5.4.\n- **Limit, stated in the paper:** synthetic corruptions are cleaner than real generator errors\n (paraphrase, partial coverage, hedging). The tests bound the judge's behaviour on clear cases; the\n human calibration of v1 §4.4 remains the reference for the subtle ones and is added when possible.\n\n---\n\n## 6. LLM choice, settings and cost\n\n### 6.1 Creator: `gpt-6.1-sol` rather than `gpt-5.6-sol`\n\nChecked on 2026-10-11 on the OpenAI model pages and pricing page (prices per 1M tokens):\n\n| | `gpt-6.1-sol` | `gpt-5.6-sol` |\n|---|---|---|\n| Released | 2026-09-29 | earlier (2026) |\n| Input / cached input / output (standard) | **$2.00 / $0.10 / $10.00** | $4.00 / $0.40 / $20.00 (promotional, \"at least through 2026-11-21\") |\n| Batch (−50 %) | $1.00 / $0.05 / $5.00 | $2.00 / $0.20 / $10.00 |\n| Context / max output | 1.05M / 128k | 1.05M / 128k |\n| Reasoning effort | low, medium (default), high, xhigh, max | none, low, medium (default), high, xhigh, max |\n| Structured Outputs, Batch API | yes | yes |\n| Knowledge cutoff | 2026-04-30 | 2026-02-16 |\n\n**Recommendation: `gpt-6.1-sol`.**\n1. **Half the price** at every tier, and the 5.6 price is promotional with no stated end rate, so a\n rerun after November could cost more.\n2. **Newer generation.** OpenAI reports fewer factual errors than GPT-6 Sol at low effort, and\n better adherence to reasoning instructions than both GPT-6 Sol and GPT-5.6 Sol (a weak proxy). Nuggetization is\n mostly careful instruction following (R1–R10), so this is the property that matters. There is no\n pt-BR or legal benchmark that separates the two; the pilot measures it on our data.\n3. Same context, output limit, Structured Outputs and Batch support, so nothing is lost. The missing\n `none` effort level does not matter here.\n4. Its later knowledge cutoff is a mild **risk**, not a benefit: it knows more post-2024 law (R9). The\n numeric and year checks of §3.3 catch this mechanically, and the audit measures what is left.\n\nIf the pilot shows a clear quality problem with `gpt-6.1-sol`, running `gpt-5.6-sol` on the same 30\nquestions costs about $5 and settles it.\n\n### 6.2 Creator–generator family overlap\n\nOpenAI is both the nugget creator and a generator (D1). Nuggets phrased by an OpenAI model might match\nthe phrasing of the OpenAI generator a little better. The paper's comparisons are **between\nstrategies with the same generator**, so this cancels in the paired tests. It could still favour the\nOpenAI generator in a cross-generator table. Controls: R3 (technical terms and values verbatim from the\ngold answer), the judge from another family (D2), and the Gemini and Qwen nugget sets (D8): report the\ngenerator ranking under all three sets.\n\nThe same reasoning applies to the **judge**: if an open-weight Qwen is the primary judge, it scores\none of the three nugget sets made by its own family (Qwen3.8-Max). This is a creator–judge overlap,\nnot a creator–generator one, and it is the same for every strategy, so it cancels in the paired\ncomparisons. The GPT and Gemini sets act as controls, and the paper states it in one sentence.\n\n### 6.3 Settings and reproducibility\n\n- Responses API, `model: gpt-6.1-sol` (the only snapshot listed; record the `model` field returned\n in each response), `reasoning: {effort: \"medium\"}` (D12), Structured Outputs\n with `strict: true`, **no `temperature`/`top_p`** (W7), `max_output_tokens` ≈ 32k (reasoning +\n nuggets; a truncated response is an error, never parsed).\n- **Cache** every raw response keyed by hash(provider, model, params, rendered messages) and release\n it. Reasoning models are not deterministic, so the cache, not the API, is what makes a rerun exact.\n- Batch API for phase 2 (≤ 24 h turnaround, 50 % off); synchronous calls with bounded concurrency\n for the pilot and the review loop.\n- Cost and token usage (input, cached, output, **reasoning**) per call go to the manifest and to a\n ledger `nuggets/costs.csv`, like `embeddings/costs.csv`.\n\n### 6.4 Cost estimate (all providers, medium effort)\n\nPrices checked on 2026-10-11 on the providers' official pages (per 1M tokens):\n\n| Model | Input | Cached input | Output (incl. reasoning) | Batch |\n|---|---|---|---|---|\n| `gpt-6.1-sol` | $2.00 | $0.10 | $10.00 | −50 % |\n| `gemini-3.1-pro-preview` (≤ 200k prompt) | $2.00 | $0.20 | $12.00 | −50 % |\n| `gemini-3.8-flash` (until 2026-12-31; doubles on 2027-01-01) | $0.75 | $0.075 | $3.75 | −50 % |\n| `qwen3.8-max` (Model Studio, Singapore) | $2.00 | ≈ 10 % of input (context cache; exact rate on the cache page) | $6.00, thinking and non-thinking alike | none in Singapore |\n\n**Why Qwen3.8-Max does not replace Gemini.** With Batch, Gemini 3.1 Pro costs $1.00 input /\n$6.00 output, the same output price as Qwen3.8-Max, which has no batch discount in Singapore, and\nhalf its input price. Moving a Gemini Pro role to Qwen3.8-Max saves nothing; for the known-answer\ntests it costs slightly more (table below). It would also leave the robustness checks with two\nfamilies instead of three. The saving comes from **Gemini 3.8 Flash** for the judge role and from\n**medium effort** (D12).\n\n**Assumptions** (to be replaced by the pilot's measurements; medium effort everywhere):\n- **Creation call:** ≈ 3k-token fixed prompt prefix (cached) + 273 tokens of question and answer on\n average → 2.34M input per full set (≈ 2.14M cacheable). Output ≈ 0.8k visible + ≈ 1.5k reasoning\n per question → ≈ 1.6M per set.\n- **Audit call:** ≈ 3.5k input (instructions, gold answer, nuggets, omission candidates), ≈ 2k\n output with reasoning; +40 % calls for the repair rounds.\n- **Judge call** (known-answer tests and scoring): ≈ 3.5k input (2k cached), ≈ 2.1k output with\n reasoning.\n\n**Creation of one full set (715 questions):** `gpt-6.1-sol` Batch ≈ $9; `gemini-3.1-pro-preview`\nBatch ≈ $12; `qwen3.8-max` ≈ $11–14. For reference, high effort (≈ 4k reasoning tokens) would roughly\ndouble each of these.\n\n**Known-answer tests, ≈ 3,000 judge calls per candidate (§5.7):**\n\n| Judge | Estimate |\n|---|---|\n| `gemini-3.8-flash`, Batch | **≈ $14** |\n| `gemini-3.1-pro-preview`, Batch, full | ≈ $43 (only ≈ $4 on the 10 % check subset) |\n| `qwen3.8-max` (no batch) | ≈ $48 |\n| open-weight Qwen on the HF endpoint | ≈ $10–25 of GPU time |\n\n**Nugget side: creation, robustness and judge selection (phases 1–4):**\n\n| Provider | Item | Estimate |\n|---|---|---|\n| OpenAI | Pilot: 30 q × {1, 2 calls}, prompt iterations on the same 30, two runs for same-model noise | ≈ $5–7 |\n| OpenAI | Full creation, Batch | ≈ $9 |\n| OpenAI | Repair calls (≈ 20 % of questions, up to two rounds) | ≈ $3 |\n| | **OpenAI subtotal** | **≈ $17–20** |\n| Gemini | Pilot set and pilot known-answer tests on 30 q | ≈ $2 |\n| Gemini | Second set, 3.1 Pro, Batch | ≈ $12 |\n| Gemini | Auditor 1, 3.1 Pro, Batch | ≈ $16 |\n| Gemini | Alignment of three sets, round-trip reconstruction, corruption rewrites (3.8 Flash, Batch) | ≈ $5 |\n| Gemini | Known-answer tests: 3.8 Flash in full + 3.1 Pro on the 10 % subset, Batch | ≈ $18 |\n| | **Gemini subtotal** | **≈ $50–55** |\n| Alibaba | Pilot set on 30 q | < $1 |\n| Alibaba | Third set, Qwen3.8-Max | ≈ $11–14 |\n| Alibaba | Auditor 2 | ≈ $15 |\n| Alibaba | Round-trip comparison | ≈ $8–11 |\n| | **Alibaba subtotal** | **≈ $35–40** |\n| HF endpoint | Known-answer tests with the open-weight Qwen judge (model size still open, §9) | ≈ $10–25 |\n| | **Total, phases 1–4** | **≈ $115–140** |\n\nIf the 10 % subset shows that 3.1 Pro is clearly the better Gemini judge (D2), running it in full adds\n≈ $39.\n\n**Scoring the answer grid (phase 5) is the real cost driver** and is not in the total. One answer run\n(715 questions) costs, per judge and per nugget set, at medium effort:\n\n| Judge | Per run and set |\n|---|---|\n| `gemini-3.8-flash`, Batch | ≈ $3.5 |\n| `gemini-3.1-pro-preview`, Batch | ≈ $10 |\n| `qwen3.8-max` (no batch) | ≈ $11 |\n| `gpt-6.1-sol`, Batch (self-preference subset only) | ≈ $9 |\n| open-weight Qwen on the HF endpoint | ≈ $3–8 of GPU time |\n\nA grid of 40 runs scored with three sets is ≈ $420 with Gemini 3.8 Flash and ≈ $1,200 with 3.1 Pro.\nThe plan therefore scores **every run with the primary set and the primary judge**, and uses the two\nother sets and the second judge only for the **main comparisons** (S2 − S1 and the caput variants at\nthe headline budget, per generator). The phase 5 budget is estimated with `--dry-run` once the grid\nis fixed. The OpenAI self-preference subset (e.g. 8 runs × 200 questions, ≈ $18) belongs to this\nphase too.\n\n---\n\n## 7. Code design\n\nAs v1 §7, with these changes:\n\n```\nscripts/llm_client/ shared with scripts/rag/ Phase 3 (RAG plan §7.5)\n providers/ base.py (complete_json(messages, schema) -> result + usage), openai.py (Responses API,\n Structured Outputs, Batch submit/poll), gemini.py, openai_compat.py, fake.py\n cache.py, cost.py (prices from the registry, ledger rows), retry.py\nscripts/nuggets/\n nuggets.py, models.yaml, prompts/, nuggetizer/{data,schema,create,validate,values,review,assign,\n metrics,export}.py, tests/\n nuggetizer/robustness/ align.py (cross-run and cross-set alignment), audit.py (two-auditor review\n + repair loop), roundtrip.py, perturb.py (§5.6 error models),\n known_answer.py (§5.7 corruption builders and metrics)\n```\n\n- `models.yaml` entry for the creator:\n\n ```yaml\n gpt-6.1-sol:\n provider: openai\n model_id: gpt-6.1-sol\n api_key_env: OPENAI_API_KEY\n params: {reasoning_effort: medium, max_output_tokens: 32000} # D12; no temperature (W7)\n price: {usd_per_million_input: 2.00, usd_per_million_cached_input: 0.10,\n usd_per_million_output: 10.00, batch_discount: 0.5, checked: 2026-10-11}\n ```\n- Registry entries for the other families (the Qwen one goes through `openai_compat`):\n\n ```yaml\n gemini-3.1-pro:\n provider: gemini\n model_id: gemini-3.1-pro-preview # preview: record the served version; outputs are cached\n api_key_env: GEMINI_API_KEY\n price: {usd_per_million_input: 2.00, usd_per_million_cached_input: 0.20,\n usd_per_million_output: 12.00, batch_discount: 0.5, checked: 2026-10-11}\n gemini-3.8-flash:\n provider: gemini\n model_id: gemini-3.8-flash\n api_key_env: GEMINI_API_KEY\n price: {usd_per_million_input: 0.75, usd_per_million_cached_input: 0.075,\n usd_per_million_output: 3.75, batch_discount: 0.5, checked: 2026-10-11,\n note: \"doubles on 2027-01-01\"}\n qwen3.8-max:\n provider: openai_compat\n base_url: https://dashscope-intl.aliyuncs.com/compatible-mode/v1\n model_id: qwen3.8-max # pin a dated snapshot (e.g. qwen3.8-max-0902) if listed\n api_key_env: DASHSCOPE_API_KEY\n params: {response_format: json_object} # schema enforced by pydantic validation + retry\n price: {usd_per_million_input: 2.00, usd_per_million_output: 6.00, checked: 2026-10-11}\n ```\n- `create --batch` writes the Batch input file, submits it, and `create --collect` fetches the\n results into the cache; the rest of the pipeline reads only the cache.\n- `create --dry-run` prints calls, tokens and the estimated cost from `models.yaml`, and sends\n nothing (same idea as `rag.py run --dry-run`).\n- `values.py` holds the pt-BR value normalizer used by `validate` (§3.3), by `metrics` (§5.4) and by\n the value and year corruptions (§5.7).\n- The corruption builders are deterministic (seeded), and every test answer records which nugget it\n targets and the expected label, so the known-answer set is itself releasable as a test suite for\n other judges.\n- `.env` is loaded with `python-dotenv` from the repo root, as in `scripts/embedding/embed.py`.\n\n---\n\n## 8. Setting up the API keys\n\n`.env` (repo root) is gitignored (`.gitignore` line 8). It holds `HF_TOKEN`, `GEMINI_API_KEY`,\n`ENDPOINT_URL_JUA_4B_MIXED` and, since 2026-10-11, `OPENAI_API_KEY`. This plan needs one more key,\n`DASHSCOPE_API_KEY` (§8.2).\n\n### 8.1 OpenAI (done)\n\nThe line added was:\n\n```\nOPENAI_API_KEY=sk-proj-…\n```\n\n1. On platform.openai.com, create (or pick) a **project** for this research, set a monthly budget\n limit on it (e.g. $75, comfortably above the OpenAI part of §6.4 plus the self-preference\n subset), and create a **project API key** under\n *API keys*. Keys created this way start with `sk-proj-`.\n2. Append it without echoing it to the terminal or the shell history:\n\n ```bash\n read -rs -p \"OpenAI API key: \" K && printf 'OPENAI_API_KEY=%s\\n' \"$K\" >> .env && unset K; echo\n ```\n\n (`.env` ends with a newline, so the line is appended cleanly. Editing `.env` with a text editor\n works too.)\n3. Check that the key works and the model is visible to the project, without printing the key:\n\n ```bash\n set -a; . ./.env; set +a\n curl -s https://api.openai.com/v1/models/gpt-6.1-sol \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" | python3 -m json.tool\n ```\n\n A JSON object with `\"id\": \"gpt-6.1-sol\"` means it works; an `error` object names the problem\n (invalid key, or the model not enabled for the project / usage tier).\n4. Batch API queue limits depend on the account's usage tier. 715 requests of ≈ 3k input tokens\n (≈ 2.3M enqueued tokens) fit the lower tiers, but check *Limits* in the project settings before\n phase 2.\n\nOptional, only if the account has several organizations: `OPENAI_ORG_ID=org-…` and\n`OPENAI_PROJECT_ID=proj_…` on further lines; the `openai` SDK reads both from the environment.\n\n### 8.2 Alibaba Model Studio (Qwen3.8-Max)\n\n1. In the Alibaba Cloud console, open **Model Studio** in the **Singapore (international)** region and\n create an API key. Keys are tied to a region: a Singapore key works only with the international\n endpoint below, not with the China (Beijing) one. Set a spending alert of about $75 in Billing.\n2. Append it the same way:\n\n ```bash\n read -rs -p \"DashScope API key: \" K && printf 'DASHSCOPE_API_KEY=%s\\n' \"$K\" >> .env && unset K; echo\n ```\n3. Check it with a tiny request (a fraction of a cent):\n\n ```bash\n set -a; . ./.env; set +a\n curl -s https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" -H \"Content-Type: application/json\" \\\n -d '{\"model\": \"qwen3.8-max\", \"messages\": [{\"role\": \"user\", \"content\": \"Responda apenas: ok\"}],\n \"max_tokens\": 5}' | python3 -m json.tool\n ```\n\n A `choices` array means it works. An `error` with `InvalidApiKey` usually means the key belongs\n to another region.\n\n### 8.3 Gemini\n\n`GEMINI_API_KEY` is already in `.env`. Before phase 2, check that the project has Batch API access\nand that `gemini-3.1-pro-preview` and `gemini-3.8-flash` are listed for the key.\n\n---\n\n## 9. Open questions\n\n1. **How Qwen is run for the judge** (D4): own HF endpoint (vLLM, pinned revision) or a hosted API,\n and which size. Still open from v1.\n2. **Second annotator** (name, background) and the **tax/legal specialist** for escalations. Still\n open from v1.\n3. **Gemini models** (D11): `gemini-3.1-pro-preview` is a preview and may be replaced. Confirm it at\n phase 1 and record the served version.\n4. **Medium-effort equivalents** (D12): the exact Gemini thinking setting and the Qwen3.8-Max thinking\n budget that correspond to OpenAI's medium, checked in phase 0 against the reasoning tokens\n each provider reports.\n5. **Effort escalation:** if the pilot shows a clear quality problem at medium (e.g. dropped\n conditions in long enumerations), whether to allow high effort for the long answers only.\n6. **Automatic gate thresholds** (§3.5.6): confirm or adjust after the pilot.\n7. **Scoring budget** (phase 5): which runs count as \"main comparisons\" scored with all three sets\n and both judges (§6.4).\n8. **Order with RAG Phase 3:** nuggets phases 0–3 do not need answers and can start now. Building\n `scripts/llm_client/` here first means RAG Phase 3 reuses it. Confirm this order.\n","20261012_114025_nuggetization_preview_10_questions.md":"# Nuggetization preview — 10 questions, three creators, four judges\n\n**Generated:** 2026-10-12 11:40:25 (local time, from `date +%Y%m%d_%H%M%S`)\n**Plan:** `docs/20261011_224049_gold_answer_nuggetization_plan_v2.md` (plan v2). This is a smoke test\nbefore phase 1, run to check the process end to end and to replace the assumptions of plan v2 §6.4\nwith measured token counts. It is **not** the phase 1 pilot: no prompt iteration, no 2-call mode, no\nsame-model noise runs, no auditors and no known-answer tests.\n**Full results:** `nuggets/preview/report.md` (generated). It shows all nuggets side by side per\nquestion, with validator issues and judge labels.\n**Total spent:** **$1.01** in 90 API calls (ledger `nuggets/preview/costs.csv`), plus a few\nprobe calls of a fraction of a cent.\n\n---\n\n## 1. Is 10 questions enough?\n\n**For this purpose, yes. For the phase 1 decisions, no.**\n\n- **Process check:** 10 is enough. All three providers, structured output, validation, caching, the\n ledger and the report ran end to end. All 90 calls were accepted on the first attempt.\n- **Cost estimate:** 10 is enough *if the questions are stratified by length*, because length\n drives cost. `preview_10` takes one question per answer-length decile, so the sample mean is close\n to the population mean. Tokens are fitted against length and summed over the 715 real lengths. The\n bootstrap 90 % intervals on the full-run costs are about ±10–25 % (report §5). Two things matter\n more than sample size:\n - the roles not run here (auditors, aligner, round trip) are priced from the judge-call shape;\n - the tail of long answers lies outside the sample. The longest preview answer has 1,372 tokens;\n 14 answers are longer (up to 6,306) and hold 18 % of all question + answer tokens. The linear\n fit extrapolates into them.\n- **Quality decisions** (prompt, 1 vs 2 calls, judge choice): 10 is too few. That is the job of the\n 30-question pilot.\n\n**Reuse:** `preview_10` is the first pick per decile of `stratified_30` (3 per decile, seed 13,\nprompt-example questions 001 and 003 excluded). The pilot will therefore reuse these 10 questions,\nand their cached responses.\n\nSample: Q503, 023, 039, 710, 259, 498, 564, 244, 703, 624. It has two Sim/Não verdicts, four\nenumerations and two answers with percentages, but **no R$ amount**. The R$ cases of R8/R9 are\nuntested until the pilot.\n\n## 2. What was built (phase 0, minimal)\n\n| Path | Content |\n|---|---|\n| `scripts/llm_client/` | `LLM.complete_json()` for `openai` (Responses API, strict JSON schema), `gemini` (REST `generateContent`, `responseJsonSchema`) and `openai_compat` (Qwen on Model Studio). Raw-response cache keyed by the request hash, retry on invalid or truncated replies, cost ledger |\n| `scripts/nuggets/models.yaml` | Registry with the medium-effort settings (D12) and the plan v2 prices |\n| `scripts/nuggets/prompts/create_v1.pt.md` | Creation prompt: rules R1–R10, recurring cases, fields, two worked examples (Q003, abridged Q001); ≈ 3.1k tokens |\n| `scripts/nuggets/prompts/assign_v1.pt.md` | Assignment prompt with the four labels (§5.2) |\n| `scripts/nuggets/nuggetizer/` | `schema` (pydantic → strict schema), `data` (sampling), `values` (pt-BR values), `validate` (§3.3, §3.5.1), `report` |\n| `scripts/nuggets/nuggets.py` | `sample`, `create`, `validate`, `selfscore`, `report` |\n| `nuggets/preview/` | Inputs, sample, cache, nuggets, validation, assignments, ledger, report |\n\n`openai` (3.29.0) and `pydantic` (2.14.1) were installed in `.venv`.\n\n**Not built:** Batch submit/collect, `--dry-run`, the `fake` provider and tests, `review`/`assign`\non system answers, alignment, auditors, round trip, known-answer builders.\n\n## 3. API findings (phase 0 checks of plan v2 §9 item 4)\n\n| Provider | Finding |\n|---|---|\n| OpenAI `gpt-6.1-sol` | `reasoning.effort: medium` + strict JSON schema work. Medium effort used **little reasoning**: 147 tokens per creation call on average (plan assumed 1.5k), 21 per judge call |\n| Gemini | `thinkingConfig.thinkingLevel: \"medium\"` is accepted by `gemini-3.1-pro-preview` and `gemini-3.8-flash`, so D12 maps directly. Thinking: 1,151 tokens per Pro creation call, 469 per Flash judge call. **No implicit caching** was reported for the 3.1k-token prefix (cached = 0), so Gemini estimates assume none |\n| Alibaba `qwen3.8-max` | The API lists the snapshot `qwen3.8-max-0902`, which is pinned in `models.yaml`. `enable_thinking` + `thinking_budget: 2048` work. **`response_format: json_schema` returned malformed JSON** in the probe; `json_object` + pydantic validation works (0 retries in 20 calls). Context cache hit automatically (2.8k of 3.7k input tokens) |\n| `.env` | `GEMINI_API_KEY` is **read differently by `python-dotenv` and by the shell**. The dotenv value is rejected (\"API key not valid\"); the shell-sourced value works. The commands therefore run after `set -a; . ./.env; set +a`. The line probably has quoting or a trailing character that the two parsers treat differently. Worth fixing in `.env` before anything relies on `load_dotenv` alone |\n\n## 4. Nugget results\n\n| Creator | Nuggets | Per question (min–max) | Vital | Validator errors | Warnings | Char coverage |\n|---|---:|---|---:|---:|---:|---:|\n| `gpt-6.1-sol` | 72 | 7.2 (2–29) | 58 % | 0 | 3 | 90 % |\n| `gemini-3.1-pro` | 50 | 5.0 (2–21) | 64 % | 0 | 8 | 89 % |\n| `qwen3.8-max` | 52 | 5.2 (2–21) | 63 % | 0 | 4 | 93 % |\n\n- **Granularity differs by family.** GPT splits more (Q703: 13 vs 6 and 6; Q244: 9 vs 5 and 5;\n Q624: 29 vs 21 and 21). Each GPT nugget is one tax treatment per instrument, which follows R2.\n Gemini and Qwen group instruments that share a rate. The two are about equally good for scoring,\n but the difference will lower the cross-family alignment rates (§3.5.2). The alignment must be\n many-to-one, not one-to-one.\n- **Gemini omissions.** Gemini left one statement uncovered in Q498 (the reasoning about the\n estate) and one in Q624 (missing CPF/CNPJ fields create pending items but do not block filing).\n Both are `okay`-level facts, and GPT and Qwen covered them.\n- **R8 warnings.** Gemini (3) and Qwen (2) wrote percentage nuggets in Q703/Q624 without a period.\n GPT anchored every value.\n- The validator's first version over-reported uncovered enumeration items: lead-in lines such as\n \"…às seguintes alíquotas:\" and roman-numeral sub-items. This is fixed, and no hard errors remain.\n\n## 5. Main finding: R8 makes the judges penalize the gold answer itself\n\nIn the gold self-score (§3.5.5), every judge should label every nugget `support`. On the GPT set:\n\n| Judge | support | partial_support |\n|---|---:|---:|\n| `gemini-3.8-flash` | 94.4 % | 4 |\n| `gemini-3.1-pro` | 94.4 % | 4 |\n| `qwen3.8-max` | 90.3 % | 7 |\n| `gpt-6.1-sol` | 86.1 % | 10 |\n\n**All but one** of the non-`support` labels have the same cause. GPT followed R8's fallback and\nwrote \"no ano-calendário de 2023\" / \"exercício de 2024\" into deadline and rate nuggets (Q023,\nQ039, Q564, Q703) whose question and answer state no year. The judges then mark `partial_support`\nwith \"não menciona o ano-calendário de 2023\". The Gemini and Qwen sets added fewer years and scored\n98–100 % with Flash.\n\nThis would lower V_strict for **every** system answer that does not state the year, and the\n§3.5.6 gate (≥ 98 % self-support) would fail on it. It is a prompt/judge interaction, not a nugget\nerror. Options for the pilot, to be chosen by the user:\n\n1. **Judge side (recommended):** state in `assign_v1` that the P&R period (exercício 2024,\n ano-calendário 2023) is implicit context. A missing year is then not a defect, while a\n *different* year or value stays `contradicts`. The temporal-substitution test (§5.4) is kept,\n and the nuggets need no change.\n2. **Creation side:** limit R8's document-period fallback to `valor_prazo` nuggets with amounts\n or rates, and mark the added period as `[período do documento]` so the judge can ignore it.\n3. Both.\n\nOther judge observations:\n- Flash was the most lenient judge, GPT the strictest; Qwen3.8-Max was in between and also flagged\n Q703.\n- The only non-R8 label was Flash on Qwen's Q710 nugget, which only says \"the treatment of pergunta\n 674 applies\". That is a pointer the prompt says should give no nugget, so Flash was right to flag it.\n- These differences are the reason the known-answer tests (§5.7) choose the judge.\n\n## 6. Updated cost estimate\n\nMeasured tokens per call, extrapolated to 715 questions (method in report §5), with the plan v2\ncall counts:\n\n| | Preview-based | Plan v2 §6.4 |\n|---|---:|---:|\n| Creation, `gpt-6.1-sol`, Batch | $4.6 (90 % CI $4.2–5.6) | ≈ $9 |\n| Creation, `gemini-3.1-pro`, Batch | $10.6 ($9.9–11.0) | ≈ $12 |\n| Creation, `qwen3.8-max` | $8.9 ($7.9–10.1) | ≈ $11–14 |\n| OpenAI subtotal, phases 1–4 | $10.7 | ≈ $17–20 |\n| Gemini subtotal, phases 1–4 | $35.7 | ≈ $50–55 |\n| Alibaba subtotal, phases 1–4 | $27.4 | ≈ $35–40 |\n| HF endpoint (not measured) | $10–25 | ≈ $10–25 |\n| **Total, phases 1–4** | **≈ $85–100** | **≈ $115–140** |\n| Scoring per run and nugget set: Flash, Batch | $1.3 | ≈ $3.5 |\n| Scoring per run and nugget set: 3.1 Pro, Batch | $5.7 | ≈ $10 |\n| Scoring per run and nugget set: Qwen3.8-Max | $6.4 | ≈ $11 |\n| Scoring per run and nugget set: `gpt-6.1-sol`, Batch | $2.0 | ≈ $9 |\n| Grid of 40 runs × 3 sets, Flash / 3.1 Pro | ≈ $160 / ≈ $690 | ≈ $420 / ≈ $1,200 |\n\nReasons and caveats:\n- **OpenAI is about half the plan** because medium effort reasons very little on this task (147\n tokens, not 1.5k). Its prefix was cached at $0.10/M even in synchronous calls. If the pilot raises\n effort for quality reasons (plan v2 §9 item 5), the OpenAI lines move back toward the plan.\n- **Judge calls are smaller than assumed:** ≈ 1.1–1.2k input, not 3.5k, because the assignment\n prompt is short. Output is 0.3–1.2k, not 2.1k. Real scoring judges **system** answers, not gold\n ones. If the generators write longer answers than the P&R (median 84 words), input grows; output\n grows mostly with the number of nuggets. A safety factor of 1.5× on the scoring rows is\n reasonable until the RAG Phase 3 pilot gives real answer lengths.\n- Auditor, aligner and round-trip roles are **priced from the judge-call shape** (×1.3 for the\n auditors' longer instructions). They are the least certain lines, about 40 % of the total.\n- The phase 5 scoring budget is now dominated by the choice between Flash and 3.1 Pro as primary\n judge, by a factor of ≈ 4.\n\n## 7. How to rerun or extend\n\n```bash\nset -a; . ./.env; set +a\nP=.venv/bin/python; N=scripts/nuggets/nuggets.py\n$P $N sample # writes nuggets/preview/sample.json (preview_10, stratified_30)\n$P $N create --models gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max\n$P $N validate\n$P $N selfscore --judge gemini-3.8-flash --sets gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max\n$P $N report # nuggets/preview/report.md\n```\n\nReruns read the cache and cost nothing. `--sample stratified_30 --out nuggets/pilot` runs the same\nsteps on the pilot sample, reusing nothing from the preview cache unless `--out` points to the same\nfolder. Copy `nuggets/preview/cache/` to keep the 10 calls.\n\n## 8. Decisions for the user before phase 1\n\n1. R8 vs the judge (§5): option 1, 2 or both.\n2. Whether GPT's finer granularity is wanted (R2 as written), or R2 should allow grouping\n instruments that share a rule and value.\n3. Whether to commit `nuggets/preview/` (3.2 MB, raw responses included) or keep only the report\n and manifests, as for `runs/`.\n4. Fixing the `GEMINI_API_KEY` line in `.env` so that `python-dotenv` reads it (§3).\n","20261012_154616_nuggetization_preview_open_items_resolution.md":"# Nuggetization preview — resolution of the open items\n\n**Generated:** 2026-10-12 15:46:16 (local time, from `date +%Y%m%d_%H%M%S`)\n**Context:** `docs/20261012_114025_nuggetization_preview_10_questions.md` (the preview note) §8 listed\nfour decisions for the user before phase 1. This note records the discussion of each one and the\nresolution. Plan: `docs/20261011_224049_gold_answer_nuggetization_plan_v2.md` (plan v2).\n**Status:** decided by the user (2026-10-12): **all recommendations accepted**. Implementation and the\npreview rerun are pending (§5).\n\n| # | Item | Resolution |\n|---|---|---|\n| 1 | R8 period anchor vs the judge | **Option A:** judge prompt treats the P&R period as implicit context. Nuggets unchanged |\n| 2 | Nugget granularity across families | **Keep the fine grain**, and make it explicit in R2 so all three families split alike |\n| 3 | What to commit from `nuggets/` | **Same pattern as `runs/`:** small outputs in git, `cache/` and `input/` ignored, raw cache released on the HF Hub |\n| 4 | `GEMINI_API_KEY` line in `.env` | **Fixed by the user.** Checked: `python-dotenv` alone now loads a key Gemini accepts (HTTP 200) |\n\n---\n\n## 1. Rule R8 and the judge\n\n### 1.1 Problem\n\nR8 (plan v2 §3.2) makes every nugget that states an amount, rate or deadline name its period. If\nneither the answer nor the question gives one, the nugget uses the P&R's own period (exercício 2024,\nano-calendário 2023). `gpt-6.1-sol` applied this strictly. In Q564, for example, the deadline rules\n(\"2º mês subsequente\", \"210 dias\", \"180 dias\") became \"Na venda de imóveis residenciais **no\nano-calendário de 2023**, …\".\n\nThe gold answer never mentions 2023. All four judges labelled these nuggets `partial_support`\n(\"não menciona o ano-calendário de 2023\"), against the very text they were extracted from. The gold\nself-score of the GPT set fell to 86–94 %, below the 98 % automatic gate (plan v2 §3.5.6). All but\none of the non-`support` labels of the preview had this cause.\n\nThe nugget is correct; the scoring of it is the problem. Left as is, every system answer that does\nnot repeat the year would lose credit on these nuggets. Most good answers would, because the gold\nanswers do not repeat it either. That is noise unrelated to retrieval, and it pushes V_strict down for\nall strategies.\n\n### 1.2 Why R8 stays\n\nR8 is what lets a wrong-year answer be detected. An answer that gives the 2025 rate or limit should be\n`contradicts`, and that requires the nugget to say which year its value belongs to (temporal\nsubstitution, plan v2 §5.4). This is also how the S2 hypothesis is tested: inciso chunks, which\nisolate one period with its year label, should give fewer wrong-year answers than S1 article chunks.\n\n### 1.3 Options considered\n\n| Option | Change | Pros | Cons |\n|---|---|---|---|\n| **A (chosen)** | One paragraph in the judge prompt: the P&R period is the implicit context of every answer. A *missing* year is not a defect; a *different* year, or another year's value, is `contradicts` | Nuggets unchanged; the temporal check is kept; one prompt edit | The judge might also become lenient on real wrong-year answers. The year- and value-corruption tests (plan v2 §5.7) measure exactly this |\n| B | The creator records where each period came from (`period_source: answer \\| question \\| document`); the judge ignores `document` periods | More explicit | Schema change, a new judge input, and three nugget sets that must fill the field consistently |\n| C | A + B | Covers both sides | Only needed if A alone does not bring the gold self-score to ≥ 98 % |\n\n### 1.4 Resolution\n\n**Option A.** `assign_v1.pt.md` becomes `assign_v2.pt.md` with the implicit-period paragraph. The\ncreation prompt is unchanged on this point.\n\n**Acceptance check:** rerun the four judges on the preview nuggets with `assign_v2` (≈ 40 calls,\n≈ $0.30). The GPT-set gold self-score should reach ≈ 99 % with every judge. If it stays below 98 %,\noption B is reconsidered (option C). The check that the judge still catches real year changes is the\nyear-corruption test of plan v2 §5.7. It runs in the pilot, and its sensitivity must stay ≥ 0.90\n(plan v2 §3.5.6).\n\n---\n\n## 2. Granularity: GPT splits more than Gemini and Qwen\n\n### 2.1 Observation\n\nIn Q703, item 1 of the answer lists five kinds of operation (renda fixa, fundos, bolsa, ouro and\nliquidação futura, swap) that all receive \"the same rules as residents\":\n\n| Creator | Nuggets for item 1 | Nuggets for Q703 |\n|---|---|---:|\n| `qwen3.8-max` | 1, with the five kinds | 6 |\n| `gemini-3.1-pro` | 1, with the five kinds (reworded) | 6 |\n| `gpt-6.1-sol` | 6, one per kind, each repeating the rule | 13 |\n\nThe same pattern explains Q244 (9 vs 5 and 5) and Q624 (29 vs 21 and 21). In total, GPT made 72\nnuggets on the 10 questions, Gemini 50 and Qwen 52.\n\n### 2.2 Why it matters\n\n- **All-or-nothing on composite nuggets.** A system answer that covers renda fixa, fundos and swap\n but omits ouro gets `partial_support` on Qwen's single nugget, which scores 0 under V_strict. On\n GPT's set it gets 5 of 6.\n- **The research question needs the fine grain.** The S2 argument is that sub-article chunks\n retrieve the specific inciso. An answer that got inciso I but not inciso II is exactly the case\n composite nuggets hide.\n- **Weights within a question.** Scores are averaged per question, so splitting changes weights only\n inside a question. Item 1 of Q703 weighs 6/13 of the question under the GPT set and 1/6 under the\n Gemini set. Neither is \"correct\", but giving each fact equal weight is easier to defend.\n- **Cost is negligible.** Judge output grows with the number of nuggets (≈ 72/50 here), which is cents\n per run.\n- **Cross-family agreement is the real risk.** If GPT splits and the other families do not, the\n stability measure of plan v2 §3.5.2 reports low agreement that reflects style, not disagreement\n about facts. With the human audit postponed, that agreement is the main robustness argument (D8).\n\nGPT over-splits slightly at the edge. \"Renda fixa\" and \"fundos de investimento\" come from the same\nphrase and still became two nuggets. This is defensible, because a system answer can mention one\nwithout the other.\n\n### 2.3 Resolution\n\n**Keep the fine grain**, which is what R2 already intends, and **make it explicit** so all three\nfamilies apply it the same way. Sentence added to R2 in the creation prompt (`create_v1.pt.md` →\n`create_v2.pt.md`):\n\n> Quando a resposta aplica uma mesma regra a vários objetos ou casos listados (instrumentos, espécies\n> de rendimento, hipóteses), gere um nugget por objeto ou caso, repetindo a regra em cada um.\n\n**Acceptance check:** rerun the three creators on the preview (≈ $0.60) and compare the nuggets per\nquestion. Gemini and Qwen should approach GPT's counts on Q244, Q703 and Q624. The cross-family\nalignment (plan v2 §3.5.2) must still be **many-to-one**, since some residual difference in\nsplitting will remain. Finer tuning of the prompt belongs to the phase 1 prompt iterations.\n\n---\n\n## 3. What to commit from `nuggets/`\n\n### 3.1 Sizes\n\n| `nuggets/preview/` | Size | Content |\n|---|---:|---|\n| `cache/` | 1.9 MB | raw API responses, ≈ 21 KB per call |\n| `input/` | 920 KB | copy of `dataset/questions.jsonl`, reproducible |\n| `create/` + `selfscore/` | 340 KB | nuggets, validation, labels, per-call logs, manifests |\n| `report.md` | 92 KB | |\n| `costs.csv`, `sample.json` | 16 KB | |\n\nThe cache does not scale in git. Phases 1–4 are ≈ 10–12k calls (≈ 250 MB of raw responses), and\nscoring the answer grid adds tens of thousands more. `embeddings/` and `runs/` already follow a rule\nfor this: provenance and small results in git, bulk on the HF Hub. Plan v2 D10 already releases the\nraw responses with the frozen nuggets.\n\n### 3.2 Resolution\n\nThe same pattern as `runs/`:\n\n- **Ignored** (`.gitignore`): `nuggets/**/cache/` and `nuggets/**/input/`. The input copy is\n regenerated from `dataset/questions.jsonl`, whose SHA-256 is recorded in `sample.json`.\n- **Versioned:** `nuggets.jsonl`, `validation.json`, `assignments.jsonl`, `calls.jsonl`,\n `manifest.json`, `costs.csv`, `sample.json`, `report.md`, plus the code (`scripts/llm_client/`,\n `scripts/nuggets/`) and the docs notes. These are small, they are what gets reviewed, and they show\n prompt changes as diffs.\n- **The raw cache is backed up outside git.** It is the only exact record of non-deterministic\n outputs. From the pilot on, it is pushed to a **private HF dataset repo** at the end of each phase,\n and released publicly with `v0-auto` (D10). The preview cache matters less, because its 10\n questions are regenerated in the pilot.\n- **The preview is committed** under these rules. The preview note cites it, and it is the \"before\"\n state for the changes of §1 and §2.\n\n---\n\n## 4. Effect on plan v2\n\n| Plan v2 | Change |\n|---|---|\n| §3.2 R2 | Explicit one-nugget-per-listed-object sentence (§2.3); prompt `create_v2.pt.md` |\n| §3.2 R8 | Unchanged. The document-period fallback stays |\n| §5.2 assignment call | Implicit P&R period: a missing year is not penalized, a different year is `contradicts` (§1.4); prompt `assign_v2.pt.md` |\n| §3.5.2 alignment | Must be many-to-one (§2.3) |\n| §5.7 known-answer tests | The year-corruption sensitivity of the selected judge now also validates the §1.4 judge change |\n| §6.3 reproducibility | Raw cache pushed to a private HF dataset repo at each phase end (§3.2) |\n| §8.3 Gemini key | `GEMINI_API_KEY` now loads through `python-dotenv`; the `set -a; . ./.env` step is optional |\n\nThe cost estimate of the preview note (§6) is unaffected. The finer split raises judge output by\n≈ 10–40 % for Gemini and Qwen sets, which is cents per run.\n\n## 5. Next steps\n\n1. Write `assign_v2.pt.md` (§1.4) and `create_v2.pt.md` (§2.3), keeping the v1 files for the record.\n2. Add the `.gitignore` rules (§3.2).\n3. Rerun the preview: the three creators with `create_v2`, then validation, then the four judges\n with `assign_v2` (≈ $1). Check the two acceptance criteria (§1.4, §2.3), regenerate\n `nuggets/preview/report.md`, and record the outcome in a dated note.\n4. Commit the code, the docs and the small preview outputs.\n5. Phase 1 pilot on `stratified_30`.\n","20261012_160349_nuggetization_preview_v2_execution.md":"# Nuggetization preview v2/v3 — execution log\n\n**Generated:** 2026-10-12 16:03:49 (local time, from `date +%Y%m%d_%H%M%S`). **Updated** the same day\nwith the v3 run (§7–§11), and on 2026-10-12 16:38:48 with the pointer-rule discussion and\nresolution (§13).\n**Implements:** `docs/20261012_154616_nuggetization_preview_open_items_resolution.md` (the resolution\nnote) §5, steps 1–4.\n**Status:** **done.** The v2 creation prompt had an unexpected side effect (§3). The run was paused and\nreported, and the user chose the \"follow the answer's structure\" fix (§5, option 1). With it\n(`create_v3`) and the judge fix (`assign_v2`), **both acceptance criteria of the resolution note pass**\n(§8, §9). After the pointer-rule decision (§13), the prompts for the phase 1 pilot are\n**`create_v4`** and **`assign_v2`**.\n**Outputs:** `nuggets/preview_v2/` (creation only, the rejected R2 variant) and `nuggets/preview_v3/`\n(final; report `nuggets/preview_v3/report.md`). The v1 preview in `nuggets/preview/` is unchanged\nand kept as the \"before\" state.\n**Total cost of the whole preview (v1 + v2 + v3): $2.6258** at standard prices, 210 ledgered calls\n(§10).\n\n---\n\n## 1. Changes made\n\n| File | Change |\n|---|---|\n| `scripts/nuggets/prompts/create_v2.pt.md` | Copy of `create_v1` + the R2 sentence of the resolution note §2.3 |\n| `scripts/nuggets/prompts/assign_v2.pt.md` | Copy of `assign_v1`. The old period sentence in `support` is removed, and an **implicit-period** paragraph is added: a missing exercício 2024 / ano-calendário 2023 does not lower the label; another period, or another year's value, is `contradicts` (resolution note §1.4) |\n| `scripts/nuggets/nuggets.py` | `--prompt` on `create` (default `create_v2`) and `selfscore` (default `assign_v2`); `selfscore` writes a `manifest.json` per judge and set; global `--budget USD`; loads `.env` with `python-dotenv` (the `GEMINI_API_KEY` line now parses, so `set -a; . ./.env` is no longer needed) |\n| `scripts/llm_client/client.py` | **Budget cap:** `LLM(..., budget_usd=)`. Before every API call, retries included, it sums the `--out` ledger (`costs.csv`) and raises `BudgetExceeded` once the total reaches the cap. Concurrent workers can overshoot by at most one call each (≈ $0.10 at worst for these call sizes) |\n| `scripts/nuggets/nuggetizer/report.py` | Header lists the prompt of every creator and judge. The phase 1–4 total is marked incomplete when some roles were not run |\n| `.gitignore` | `nuggets/**/cache/` and `nuggets/**/input/` (resolution note §3.2) |\n\n**Budget cap test (no API call):** a scratch `--out` with a fake ledger of $5.00 and `--budget 1.0`.\n`create` raised `BudgetExceeded` before the first call; no cache file was written and the ledger was\nunchanged.\n\nThe v1 report (`nuggets/preview/report.md`) was regenerated only to add the prompt header (no API\ncalls; the v1 ledger still has 90 rows). The v1 self-score runs have no manifest. The report shows\nthem as `assign_v1 (no manifest)`, which is correct: the prompt text is inside each cached request.\n\n## 2. Creation v2 run\n\n```bash\nP=.venv/bin/python; N=scripts/nuggets/nuggets.py\n$P $N --out nuggets/preview_v2 sample # same preview_10 and dataset SHA-256 as v1 (checked)\n$P $N --out nuggets/preview_v2 --budget 0.90 create --models gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max\n$P $N --out nuggets/preview_v2 validate\n$P $N --out nuggets/preview_v2 report\n```\n\n30 calls, 0 retries, 0 validator errors.\n\n### 2.1 Nuggets per question, v1 → v2\n\n| Creator | Total | 503 | 023 | 039 | 710 | 259 | 498 | 564 | 244 | 703 | 624 |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| `gpt-6.1-sol` | 72 → **93** | 2 → 4 | 3 | 2 | 2 | 3 → **7** | 5 → 6 | 4 | 9 | 13 → 15 | 29 → **41** |\n| `gemini-3.1-pro` | 50 → 55 | 2 | 3 → 2 | 2 | 2 → 1 | 3 | 2 → 3 | 4 | 5 → 4 | 6 → **11** | 21 → 23 |\n| `qwen3.8-max` | 52 → 52 | 3 → 2 | 3 | 2 | 2 | 3 | 3 | 4 | 5 → 6 | 6 | 21 |\n\nValidation v2: GPT 2 warnings (Q710's pointer to pergunta 674, uncovered as intended; Q624 above\n40 nuggets). Gemini 13 warnings: 10 `span_fuzzy`, 8 of them on Q703 where it split item 1;\n1 backreference; 1 period; 1 uncovered (the Q710 pointer). Qwen 4 warnings, the same as v1.\n\n## 3. Unexpected result: the R2 sentence makes GPT over-split illustrative lists\n\nThe resolution note expected Gemini and Qwen to move toward GPT's granularity (§2.3 acceptance check).\nInstead:\n\n- **Qwen did not change** (52 → 52), and **Gemini changed only on Q703** (6 → 11).\n- **GPT split further, into illustrative lists.** In Q259 (\"criação e venda de cães, passarinhos,\n gatos etc.\"), the animals are **examples** of one activity. GPT v2 made 3 animals × 2 cases =\n 6 nuggets instead of 2 (\"Se a criação e venda de cães for exercida de forma eventual…\", \"… de\n passarinhos…\", \"… de gatos…\"). A system answer that says \"animais\" would no longer be fully\n supported. In Q624, inciso III (\"veículos, aeronaves, embarcações e demais bens móveis sujeitos a\n registro\") became four nuggets. Each rule that refers to inciso III was then repeated four times,\n giving 41 nuggets.\n- The gap between families **grew**: GPT/Qwen went from 72/52 (1.38) to 93/52 (1.79).\n\nThe R2 sentence (\"vários objetos ou casos listados … um nugget por objeto\") does not separate\n**enumerated cases** of the answer (items 1, 2, a), b), incisos I, II), which may have different\ntreatment, from **objects listed inside one phrase**, which usually share it. GPT read it literally.\n\n## 4. Costs\n\nAll costs at standard (synchronous) prices, from the ledgers.\n\n| Run | Calls | Cost | Ledger |\n|---|---:|---:|---|\n| Preview v1: creation (30) + self-score (60) | 90 | $1.0100 | `nuggets/preview/costs.csv` |\n| Probe calls of 2026-10-12 (parameter checks, not in a ledger) | 7 billed (+ 2 rejected for the key) | < $0.01 (prompts of ≈ 20–70 tokens) | — |\n| Budget cap test | 0 | $0 | scratch |\n| **Preview v2: creation** | 30 | **$0.6639** | `nuggets/preview_v2/costs.csv` |\n| **Total so far** | 120 + 7 probes | **≈ $1.68** | |\n\nPer creator, v1 → v2 (10 calls each): `gpt-6.1-sol` $0.1387 → $0.1578 (+14 %), `gemini-3.1-pro`\n$0.3080 → $0.3733 (+21 %), `qwen3.8-max` $0.1287 → $0.1327 (+3 %).\n\n**Note for the cost estimate.** Gemini 3.1 Pro reasoned more under v2: 1,151 → 1,561 tokens per call\non average, with latency 47 → 95 s. Its extrapolated full-set cost moved from $10.60 to **$12.80**\n(Batch). That is **outside** the 90 % interval of the v1 run ($9.94–11.03). The bootstrap interval\nonly captures which 10 questions were sampled. It does not cover prompt changes or run-to-run\nvariation in reasoning length, which here were larger. Cost estimates for the report should\ntherefore carry a margin of at least ±25 % per creator, not the bootstrap interval alone. The other\ntwo creators moved within their v1 intervals.\n\n## 5. Decision needed before continuing (as reported at the pause)\n\n**R2 (creation prompt).** Options:\n\n1. **(Recommended) \"Follow the answer's structure\" (`create_v3`).** Replace the R2 sentence with:\n - one nugget per **enumerated item or sub-item** of the answer (1, 2…, a), b)…, I, II…);\n - objects listed **inside one sentence or item** stay in one nugget, unless the answer gives them\n different treatment;\n - illustrative lists (\"etc.\", \"tais como\", \"por exemplo\") are never split;\n - a short negative example based on the Q259 pattern.\n\n The rule is objective and tied to the answer's own layout, so the enumeration-count check of the\n validator can enforce it. It matches what Gemini and Qwen already do. It still gives inciso-level\n granularity, because the P&R lays incisos out as items (Q624 I–IV, Q703 I/II). It **partly\n reverses** the resolution note §2.3: Q703 item 1 (five operations with one treatment in one\n sentence) becomes one nugget again. The all-or-nothing effect there is left to `partial_support`\n and the non-strict scores (V, A). Cost: one creation rerun, ≈ $0.70 (cap $0.90).\n2. **Revert to `create_v1`.** Accept the style differences between families and rely on many-to-one\n alignment (plan v2 §3.5.2). No cost.\n\n**Judge criterion (resolution note §1.4).** This is independent of R2. The clean test is to rerun\nthe four judges with `assign_v2` on the **v1 nuggets**: same nuggets, only the judge prompt changes,\nso any difference is due to the prompt. 60 calls; v1 self-score cost $0.4332, so expect ≈ $0.45,\nwith a cap of $0.60. It can run before or after the R2 decision.\n\n## 6. Next steps (as planned at the pause; see §7 for what was done)\n\n1. Judge test on the v1 nuggets with `assign_v2` (§5).\n2. R2: `create_v3` + rerun creation + validation, or revert (§5).\n3. Self-score of the final v2/v3 nugget sets with `assign_v2`; the report; an update of this note\n with the outcome and costs.\n4. Commit the code, the docs and the small outputs (`cache/` and `input/` are ignored).\n\n---\n\n## 7. Decision and order of work (after the pause)\n\n- **R2:** option 1, \"follow the answer's structure\" (user, 2026-10-12).\n- **Order:** the user asked to fix R2 before running any judge. The clean A/B test of the judge prompt\n (four judges with `assign_v2` on the **v1** nuggets, §5) was **dropped**. The acceptance criterion\n of the judge fix is absolute (gold self-score ≥ 98 %), so one judge run on the v3 nuggets checks\n it. That saves ≈ $0.45. The A/B would have been run only if v3 had failed the criterion, to find\n the cause.\n\n## 8. Creation v3\n\n`scripts/nuggets/prompts/create_v3.pt.md` = `create_v1` with the last sentence of R2 (one nugget per\nenumerated item) replaced by:\n\n> **Siga a estrutura da resposta:** gere **um nugget por item ou subitem enumerado** da resposta\n> (1, 2…; a), b)…; I, II…), repetindo em cada um o contexto necessário. Objetos ou casos listados\n> **dentro de uma mesma frase ou de um mesmo item** ficam em **um único nugget**, salvo se a resposta\n> lhes der tratamentos diferentes. Listas ilustrativas (\"etc.\", \"tais como\", \"por exemplo\", \"como\")\n> nunca são divididas: \"os rendimentos de aluguel de imóveis, como casas, apartamentos e salas\n> comerciais, são tributáveis\" gera um nugget, e não um por tipo de imóvel.\n\nThe example is invented on purpose: Q259, the case that exposed the problem, is in `preview_10`\nand `stratified_30`, so using it would leak its answer into the prompt. The `create_v2` sentence is\nnot in v3. Worked example 2 (abridged Q001) already follows the rule.\n\n```bash\nP=.venv/bin/python; N=scripts/nuggets/nuggets.py\n$P $N --out nuggets/preview_v3 sample\n$P $N --out nuggets/preview_v3 --budget 0.90 create --prompt create_v3 --models gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max\n$P $N --out nuggets/preview_v3 validate\n```\n\n30 calls, 0 retries, **$0.5839**, 0 validator errors.\n\n| Creator | v1 | v2 | **v3** | Per question, v3 (503 023 039 710 259 498 564 244 703 624) | Vital, v1 → v3 |\n|---|---:|---:|---:|---|---|\n| `gpt-6.1-sol` | 72 | 93 | **53** | 2 2 2 2 3 5 4 4 6 23 | 58 % → 64 % |\n| `gemini-3.1-pro` | 50 | 55 | **47** | 2 2 2 2 2 2 3 3 6 23 | 64 % → 49 % |\n| `qwen3.8-max` | 52 | 52 | **48** | 2 2 2 2 3 2 4 4 6 21 | 63 % → 60 % |\n\n**Criterion of the resolution note §2.3: passed.** The three families now agree question by question\nwithin ±2 nuggets: GPT/Qwen is 53/48 (1.10), against 1.38 in v1 and 1.79 in v2.\n\n**Checks on the merge** (no API cost):\n- **No facts lost.** In Q244, GPT went from 9 nuggets to 4. The four \"SCP is a taxpayer of IRPJ /\n CSLL / PIS / Cofins\" nuggets became one sentence-level nugget, as the rule says, and every\n statement of the answer is still covered. No `unit_uncovered` warning for GPT.\n- **Side effect: merging changes importance.** The four tax nuggets of Q244 were `okay` in v1; the\n merged one is `vital`. Gemini's vital share fell from 64 % to 49 %. Importance labels are the least\n stable part of the nuggets (plan v2 §3.5.2), and the score variants that ignore importance\n (A, A_strict; plan v2 §5.6) are the control for it.\n- **Remaining warnings (v3):** GPT 1 (a backreference resolved inside the nugget). Gemini 4: the\n Q498 omission seen in v1 (the reasoning about the estate), two percentage nuggets without a\n period, one backreference. Qwen 6: four fuzzy spans and the same two percentage nuggets without a\n period.\n\n## 9. Gold self-score v3 with `assign_v2`\n\nSame layout as v1: Flash on the three sets; 3.1 Pro, Qwen3.8-Max and GPT on the GPT set. The cap\nwas `--budget 1.20` for the whole `preview_v3` ledger.\n\n```bash\n$P $N --out nuggets/preview_v3 --budget 1.20 selfscore --prompt assign_v2 --judge gemini-3.8-flash \\\n --sets gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max\nfor j in gemini-3.1-pro qwen3.8-max gpt-6.1-sol; do\n $P $N --out nuggets/preview_v3 --budget 1.20 selfscore --prompt assign_v2 --judge $j --sets gpt-6.1-sol\ndone\n$P $N --out nuggets/preview_v3 report\n```\n\n60 calls, 0 retries, **$0.3694**.\n\n| Judge | Nugget set | v1 (`create_v1`, `assign_v1`) | **v3 (`create_v3`, `assign_v2`)** |\n|---|---|---:|---:|\n| `gemini-3.8-flash` | GPT | 94.4 % | **98.1 %** |\n| `gemini-3.8-flash` | Gemini | 100.0 % | **100.0 %** |\n| `gemini-3.8-flash` | Qwen | 98.1 % | **97.9 %** |\n| `gemini-3.1-pro` | GPT | 94.4 % | **98.1 %** |\n| `qwen3.8-max` | GPT | 90.3 % | **100.0 %** |\n| `gpt-6.1-sol` | GPT | 86.1 % | **100.0 %** |\n\n**Criterion of the resolution note §1.4: passed.** There is no longer any `partial_support` caused\nby the implicit period. GPT's v3 nuggets still carry \"exercício de 2024\" / \"ano-calendário de 2023\"\nwhere the answer has none (R8 is unchanged), and the judges now accept them. The year-corruption\ntest of plan v2 §5.7 remains the check that the judges still catch a *different* year.\n\n**All three remaining non-`support` labels are the same case: Q710_N01**, the nugget made from the\npointer sentence \"Quando as operações forem realizadas em bolsa, aplica-se o tratamento tributário\nprevisto na pergunta 674\". In v3, all three families made a near-empty `vital` nugget from it\n(\"operações de ouro em bolsa seguem o tratamento das operações em bolsa\"). In v1, GPT made none. The\njudges hesitate because the content is in another question. Flash's 97.9 % on the Qwen set is\n1 nugget of 48, and that nugget is this one.\n\nThis is the **pointer** edge case of plan v2 §2 (50 answers still point to other questions). The\nprompt's rule (\"a pointer gives no nugget unless the sentence also states something\") is ambiguous\nwhen the sentence states only \"the treatment of another question applies\". **Open for the pilot**,\nfor the user to decide:\n- (a) such a sentence gives **no nugget**, which matches what the validator already accepts as\n uncovered;\n- (b) it gives an `okay` nugget, so a system answer that explains the actual bolsa rules is not\n required to say it.\n\n(a) is simpler and consistent with the v1 guideline (\"pointers to other questions: no nugget\").\n\n## 10. Costs (for the report)\n\nAll at standard (synchronous) prices, from the ledgers. No call exceeded a budget cap. There were no\nretries in any run.\n\n| Run | Prompts | Calls | Creation | Judges | Total | Ledger |\n|---|---|---:|---:|---:|---:|---|\n| Preview v1 | `create_v1`, `assign_v1` | 90 | $0.5754 | $0.4332 | **$1.0086** | `nuggets/preview/costs.csv` |\n| Preview v2 | `create_v2` | 30 | $0.6639 | — | **$0.6639** | `nuggets/preview_v2/costs.csv` |\n| Preview v3 | `create_v3`, `assign_v2` | 90 | $0.5839 | $0.3694 | **$0.9533** | `nuggets/preview_v3/costs.csv` |\n| Probe calls (parameter checks, 2026-10-12, not ledgered) | — | 7 | | | < $0.01 | — |\n| Budget-cap test (scratch ledger) | — | 0 | | | $0 | — |\n| **Total** | | **210 + 7** | **$1.8232** | **$0.8026** | **$2.6258 + < $0.01** | |\n\n(The preview note gave v1 as $1.01; the exact ledger sum is $1.0086.)\n\nPer creator and run (10 calls each):\n\n| Creator | v1 | v2 | v3 |\n|---|---:|---:|---:|\n| `gpt-6.1-sol` | $0.1387 | $0.1578 | $0.1110 |\n| `gemini-3.1-pro` | $0.3080 | $0.3733 | $0.3273 |\n| `qwen3.8-max` | $0.1287 | $0.1327 | $0.1455 |\n\n## 11. Updated cost estimate (final prompts, `nuggets/preview_v3/report.md` §5–§6)\n\n| | v3-based | v1-based (preview note) | Plan v2 §6.4 |\n|---|---:|---:|---:|\n| Creation `gpt-6.1-sol`, Batch | $3.75 | $4.64 | ≈ $9 |\n| Creation `gemini-3.1-pro`, Batch | $11.23 | $10.60 | ≈ $12 |\n| Creation `qwen3.8-max` | $10.03 | $8.90 | ≈ $11–14 |\n| OpenAI subtotal, phases 1–4 | $8.63 | $10.69 | ≈ $17–20 |\n| Gemini subtotal, phases 1–4 | $33.64 | $35.70 | ≈ $50–55 |\n| Alibaba subtotal, phases 1–4 | $24.65 | $27.37 | ≈ $35–40 |\n| HF endpoint (not measured) | $10–25 | $10–25 | ≈ $10–25 |\n| **Total, phases 1–4** | **≈ $77–92** | ≈ $84–99 | ≈ $115–140 |\n| Scoring per run and set: Flash, Batch | $1.26 | $1.32 | ≈ $3.5 |\n| Scoring per run and set: 3.1 Pro, Batch | $4.73 | $5.72 | ≈ $10 |\n| Scoring per run and set: Qwen3.8-Max | $5.04 | $6.42 | ≈ $11 |\n| Scoring per run and set: `gpt-6.1-sol`, Batch | $1.62 | $1.95 | ≈ $9 |\n\n**Margins to use in the report.** Across the three runs, the same creator's extrapolated full-set\ncost moved by up to 21 % (Gemini 3.1 Pro: $10.60 → $12.80 → $11.23, Batch). That is more than the\nbootstrap intervals, which only reflect which 10 questions were sampled (§4). Recommended\npresentation:\n- **phases 1–4: ≈ $77–92, with ±25 % on the measured part** (≈ $67 of it), i.e. **≈ $60–110**;\n- **scoring:** the per-run figures above × 1.5 until real system-answer lengths are known (RAG\n Phase 3 pilot).\n\nWith Flash as primary judge, a 40-run grid scored with three sets is ≈ 40 × 3 × $1.26 × 1.5 ≈\n**$230**. With 3.1 Pro it is ≈ **$850**.\n\n## 12. Next steps (status updated 2026-10-12 16:38)\n\n1. ~~Commit the code, the docs and the small outputs of `nuggets/preview*/`.~~ **Done:** commit\n `381be3c`, pushed by the user.\n2. ~~Back up the three `cache/` folders outside git.~~ **Done by the user:** the whole `nuggets/`\n folder was copied to `../nuggets_backup_20261012_132700/` (outside the repo). The private HF\n dataset repo of the resolution note §3.2 is still the target from the pilot on.\n3. ~~Decide the pointer rule (§9) and fold it into `create_v4`.~~ **Decided and implemented:** §13.\n4. Phase 1 pilot on `stratified_30` with the remaining pilot items of plan v2 §4 (1 vs 2 calls,\n same-model noise, known-answer tests, auditors), with `create_v4`, `assign_v2` and a `--budget`\n cap on every run. `create_v4` has not been run yet (§13.5).\n\n---\n\n## 13. Pointer sentences: discussion and resolution (2026-10-12)\n\n### 13.1 The question\n\n§9 recommended that a sentence that only delegates to another question give **no nugget**. The user\nasked: if a system answer also includes, correctly, what the pointed answer says, is it penalized?\nCompared with an answer that leaves it out, shouldn't the more complete answer be graded better?\n\n### 13.2 How the scores treat extra correct content\n\nThe nugget scores (V_strict, V, A_strict, A; plan v2 §5.3) are **recall** scores: the share of the\ngold nuggets that the system answer supports. There is no precision term. Content that matches no\nnugget counts neither for nor against the answer.\n\nTake two answers to Q710 (gold: \"Quando as operações forem realizadas em bolsa, aplica-se o\ntratamento tributário previsto na pergunta 674. Já operações de mútuo e de compra vinculada à\nrevenda … são equiparadas às operações de renda fixa …\"):\n\n- **A:** the gold content, plus a correct explanation of how gold operations in bolsa are taxed (the\n content of Q674);\n- **B:** only the gold content.\n\nWith no pointer nugget, A and B get the **same score**. A is **not penalized**, and its extra correct\ncontent is **not rewarded**. Extra content can lower a score only when it conflicts with a nugget\n(`contradicts`); correct content does not.\n\n### 13.3 Why the v3 pointer nugget is worse than no nugget\n\nIn v3 all three families made a `vital` nugget from the pointer sentence (\"as operações de compra e\nvenda de ouro realizadas em bolsa seguem o tratamento aplicável às operações em bolsa\"). That\nnugget rewards *mentioning the delegation*, not its substance:\n- B gets credit only if it repeats the pointer sentence;\n- A may or may not get credit, depending on whether the judge accepts the concrete bolsa rules as\n support for an almost empty statement. The judges already hesitated on the gold answer itself\n (§9).\n\nThat is noise on a `vital` nugget. Without it, A and B are scored on what the Receita actually wrote.\n\n### 13.4 Should the more complete answer score higher? Options considered\n\n| Option | Effect | Assessment |\n|---|---|---|\n| **(a) No nugget for a pure delegation sentence** | A = B on the gold content | The gold answer is the reference by definition (v1 §3.4.1), and the Receita chose to delegate |\n| (b) Keep an `okay` pointer nugget | Credit for repeating the delegation | Noisy (§13.3), even at `okay` |\n| (c) **Expand** the pointer: import the pointed question's nuggets into this question | A > B | It **changes the reference**: Q710's gold becomes Q710 + Q674. If Q674 has ≈ 10 nuggets, they swamp Q710's 2 in the per-question average, unless they are kept out of the denominator as \"bonus\", which breaks the 0–1 scale and comparability with TREC-style scores. It **disagrees with the retrieval evaluation**: `references.jsonl` for Q710 does not include Q674's provisions, so retrieval and answer scoring would use different notions of what is relevant. **Chains:** the pointed answer may point further. Plan v2 §2 already decided \"`linked_questions` are not expanded\" |\n\n**Effect on the paper's comparisons.** The same rule applies to every strategy, so it cancels in the\npaired tests (S2 − S1, etc.). It biases a comparison only if one strategy systematically brings in\nthe pointed content and its answers then go uncredited. That would make a difference look\n**smaller**, never flip its sign.\n\n**Scale** (all 715 gold answers, counted on 2026-10-12): **57 answers (8 %)** contain a pointer\n(\"pergunta NNN\"), in **69 sentences**. Most of those sentences carry content around the pointer\n(e.g. \"… desde que se enquadre como … (ver pergunta X)\"), and that content still gets nuggets.\nOnly pure delegation sentences like Q710's lose their nugget, so the affected set is a subset of\nthe 69. 237 questions have non-empty `linked_questions`, which is a broader field than in-text\npointers.\n\n### 13.5 Resolution (user, 2026-10-12)\n\n1. **Main nugget set: option (a)**, implemented in `scripts/nuggets/prompts/create_v4.pt.md`\n (= `create_v3` + a rewritten \"Remissões\" bullet):\n - a sentence that **only delegates** the treatment to another question gives **no nugget**, even\n when it says to which situation the delegation applies; empty nuggets such as \"aplica-se um\n tratamento específico\" are named as forbidden;\n - a remission that **limits a verdict or a rule** of the answer itself still gives a **condition**\n nugget, without the question number. This keeps worked example 1 (Q003, \"Não, a menos que se\n enquadre nas hipóteses previstas na resposta à pergunta 001\") consistent with the rule: a flat\n \"Não\" would be wrong there, so the exception is real content. In Q710 the remission adds\n nothing to judge;\n - a sentence that also states other content gives the nugget for that content.\n\n The examples in the new bullet are neutral (\"pergunta 300\", \"essas operações\"). The first draft\n quoted Q710's own wording (\"pergunta 674\", \"operações em bolsa\"); it was rewritten because Q710 is\n in `preview_10` and `stratified_30` (the same leak avoided for Q259 in §8).\n2. **A question-level `has_pointer` flag**, filled by the validator (plan v2 §3.1: flags are not\n produced by the LLM). It is copied to every nugget's `flags` and to the question's entry in\n `validation.json`, so the pointer slice is one filter.\n3. **Validator changes** (`scripts/nuggets/nuggetizer/validate.py`):\n - an uncovered answer unit that contains a pointer is reported as **`pointer_uncovered`**\n (expected under `create_v4`). It used to be `unit_uncovered`, or `enum_item_uncovered` (a hard\n error) when the unit was an enumerated item. It stays a warning under its own code, because a\n *mixed* sentence whose content part was missed would also land there and is worth a look;\n - a nugget whose text contains a pointer (\"pergunta NNN\") gets a **`pointer_in_text`** warning.\n4. **Optional, later: an \"expanded\" secondary score on the pointer slice.** Since all 715 questions\n are nuggetized, the pointed question's nuggets are a lookup, not new creation calls. They can be\n added as `okay` nuggets for a secondary score on the `has_pointer` questions only, leaving the\n main metric unchanged. The extra judge cost is cents per run. It answers the user's question\n empirically: does crediting the pointed content change any conclusion? To be decided when the\n scoring plan (phase 5) is fixed.\n\n**Validator test (no API cost)**, on scratch copies of the committed outputs:\n- v3 nuggets: Q710 is the only `has_pointer` question of `preview_10`, flagged in all three sets. No\n `pointer_uncovered`, because the v3 pointer nuggets cover the sentence; that is the behaviour\n `create_v4` removes.\n- v1 GPT nuggets (made no pointer nugget): Q710 now gives `pointer_uncovered` (\"Quando as operações\n forem realizadas em bolsa, aplica-se o tratamento …\") instead of `unit_uncovered`.\n\nThe committed `nuggets/preview*/` outputs were **not** revalidated, so they still show the old\ncodes. Reproducing them requires the validator of commit `381be3c`.\n\n`nuggets.py create` now defaults to `--prompt create_v4`; `selfscore` already defaulted to `assign_v2`.\nBefore this change, the `create` default was still `create_v2`, the rejected variant.\n\n**Not run yet:** `create_v4` itself (no API call was made for this change). Options: check it on\n`preview_10` (≈ $0.60, cap $0.90), or let the first pilot run be its check. The expected outcome on\nQ710 is no pointer nugget in any family, one `pointer_uncovered` warning per set, and a gold\nself-score of 100 % on Q710.\n","20261012_192640_nuggetization_phase1_pilot.md":"# Nuggetization phase 1 pilot — `stratified_30`\n\n**Generated:** 2026-10-12 19:26:40 (local time, from `date +%Y%m%d_%H%M%S`).\n**Implements:** plan v2 §4 phase 1 (`docs/20261011_224049_gold_answer_nuggetization_plan_v2.md`), after the\npreview (`docs/20261012_160349_nuggetization_preview_v2_execution.md`, which fixed `create_v4` and `assign_v2`).\n**Outputs:** `nuggets/pilot/`: `report_pilot.md` (all pilot measurements), `report.md` (nuggets side by side\nand per-question detail), `costs.csv` (ledger), one folder per stage (§1).\n**Status:** **done.** Every phase 1 item of plan v2 §4 was run. Two items were added: the planted-error\nauditor test (§6.3) and a dataset check of `answer_cleaned` (§8). The last two 3.1 Pro items, blocked by a\ndaily quota (§9.1), were completed on 2026-10-13 through the Batch API (§11).\n**Cost: $8.62** at standard prices, **$8.29 billed** (35 calls via Batch at half price), 949 ledgered calls,\n1 retry (§10). Expected before the run: ≈ $11; cap $15. No cap was hit.\n\n**Updated 2026-10-12 20:03:05:** §13 records the follow-up work the user approved: the `answer_cleaned` fix\n(§8 → done) and Batch API support (§9.1 → done).\n\n**Updated 2026-10-13 03:30:59:** the pending 3.1 Pro items ran through Batch (§11); §6.3, §7, §9.1 and §10 now\ninclude them.\n\n**Gate of phase 1 (plan v2 §4):** \"the user picks prompt and call mode from the report\". Recommendation:\n**`create_v4`, one call** (§4, §5). Both choices and the other decisions for phase 2 are in §12.\n\n---\n\n## 1. What was run\n\nAll commands from the repository root (`P=.venv/bin/python; N=scripts/nuggets/nuggets.py;\nO=\"--out nuggets/pilot --sample stratified_30 --budget <cap>\"`). The cap is cumulative per ledger; each step\nraised it by its expected cost plus a margin (README \"Costs and the budget cap\").\n\n| # | Step (plan v2 reference) | Command | Output | Calls | Cost |\n|---|---|---|---|---:|---:|\n| 1 | Sample (same `dataset_sha256` as the preview) | `$N --out nuggets/pilot sample` | `sample.json` | 0 | $0 |\n| 2 | Creation, 3 families, `create_v4` (§3.5.2, D8) | `create --models gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max` | `create/<model>/` | 90 | $1.61 |\n| 3 | Same-model noise: two more GPT runs (§3.5.2) | `create --models gpt-6.1-sol --replicate 2` (and `3`) | `create/gpt-6.1-sol.r2`, `.r3` | 60 | $0.49 |\n| 4 | 2-call mode: importance in a second call (§3.2) | `importance --source gpt-6.1-sol` | `create/gpt-6.1-sol.2call` | 30 | $0.13 |\n| 5 | Validation (§3.3, §3.5.1) | `validate` | `create/*/validation.json` | 0 | $0 |\n| 6 | Gold self-score, `assign_v2` (§3.5.5) | `selfscore` (Flash on 3 sets; 3.1 Pro, Qwen, GPT on the GPT set) | `selfscore/` | 180 | $1.43 |\n| 7 | Cross-set alignment, `gemini-3.8-flash` (§3.5.2) | `align --pairs` P:G, P:Q, G:Q, P:r2, P:r3 | `align/<A>__<B>/` | 150 | $0.48 |\n| 8 | Round trip (§3.5.4) | `roundtrip --set gpt-6.1-sol` (check v1; then v2, §6.2) | `roundtrip/` | 90 | $0.47 |\n| 9 | Two-auditor review (§3.5.3) | `audit --set gpt-6.1-sol --auditor {gemini-3.1-pro,qwen3.8-max} --others …` | `audit/gpt-6.1-sol/` | 60 | $0.84 |\n| 10 | Repair round 1 + re-audit + self-score of the repaired set | `repair --new gpt-6.1-sol.rep1`; `audit`/`selfscore` on `.rep1` | `create/gpt-6.1-sol.rep1`, … | 5 | $0.08 |\n| 11 | Known-answer tests, Flash and 3.1 Pro (§5.7) | `known build/judge --set gpt-6.1-sol.rep1` | `known/gpt-6.1-sol.rep1/` | 218 | $2.12 |\n| 12 | **Added:** planted errors, auditor sensitivity | `plant --set gpt-6.1-sol.rep1`; `audit` on `.planted` | `create/…planted`, `audit/…planted/` | 30 | $0.32 |\n| 13 | Reports | `report`, `pilotreport` | `report.md`, `report_pilot.md` | 0 | $0 |\n\n`stratified_30` = 3 questions per answer-length decile (seed 13), a superset of `preview_10`, the same\nsample as the RAG pilot. Two questions point to other questions (`has_pointer`: Q710, Q028).\n\n### 1.1 Code added for the pilot (no API cost unless run)\n\n| File | What |\n|---|---|\n| `scripts/llm_client/client.py` | `complete_json(..., replicate=N)`: N > 0 enters only the cache key, so an identical request is sampled again (same-model noise). `QuotaExhausted`: a per-day quota (HTTP 429 `…PerDay…`) fails at once instead of backing off |\n| `scripts/nuggets/nuggets.py` | `create --replicate`; new commands `importance`, `align`, `roundtrip`, `audit`, `repair`, `plant`, `known build/judge`, `pilotreport`. One user-prompt builder (`assign_user`) for self-score and known-answer tests, so gold tests reuse the self-score cache |\n| `scripts/nuggets/nuggetizer/schema.py` | Strict schemas for importance labels, alignments, reconstruction, missing facts and audits |\n| `scripts/nuggets/nuggetizer/known_answer.py` | Deterministic builders of the test types G, V, Y, N, D, C, W, E (plan v2 §5.7) and their metrics. Not built in the pilot: V from another period's value in the corpus, and the Flash rewrite for undelimited conditions (phase 4) |\n| `scripts/nuggets/nuggetizer/planted.py` | One planted error per question (value, polarity, condition, quantifier, addition, merge, importance), each with the check it should fail |\n| `scripts/nuggets/nuggetizer/pilot_report.py` | `report_pilot.md` |\n| `scripts/nuggets/nuggetizer/validate.py` | Two false positives fixed (§3.1); the `temporal`, `short_answer` and `procedimento_pgd` flags (answer-based; over all 715: 303, 20 and 101 questions) |\n| `scripts/nuggets/nuggetizer/report.py` | Generic title; derived sets (`.rN`, `.2call`, `.repN`, `.planted`) map to their registry model |\n| `scripts/nuggets/prompts/` | `importance_v1`, `align_v1`, `roundtrip_write_v1`, `roundtrip_check_v1` → `v2` (§6.2), `audit_v1` (C1–C6 of plan v1 §3.4.1), `repair_v1` (appended to `create_v4`). None quotes a `stratified_30` question (README rule) |\n\n---\n\n## 2. Creation (`create_v4`, one call)\n\n| Set | Nuggets | Per question (min–max) | Vital | Errors | Warnings | Char coverage | $ (30 q) |\n|---|---:|---|---:|---:|---:|---:|---:|\n| `gpt-6.1-sol` (primary) | 135 | 4.5 (1–23) | 64 % | 0 | 28 | 92 % | $0.27 |\n| `gpt-6.1-sol.r2` | 137 | 4.6 (1–23) | 66 % | 0 | 25 | 93 % | $0.25 |\n| `gpt-6.1-sol.r3` | 134 | 4.5 (1–23) | 63 % | 0 | 30 | 92 % | $0.24 |\n| `gemini-3.1-pro` | 122 | 4.1 (1–23) | 67 % | 0 | 38 | 89 % | $0.95 |\n| `qwen3.8-max` | 123 | 4.1 (1–21) | 64 % | 0 | 45 | 90 % | $0.39 |\n\n- **No retries, no schema failures.** GPT/Qwen nugget ratio 1.10, the same as `create_v3` on the preview.\n- **Pointer rule (`create_v4`) works as expected** (preview note §13.5): Q710's delegation sentence gives no\n nugget in any family (one `pointer_uncovered` warning per set), no nugget contains \"pergunta NNN\"\n (`pointer_in_text`: 0), and Q710 is 100 % `support` in every self-score.\n- **Remaining warnings** (GPT set): 20 `unit_uncovered`, **all of them worked-example lines of Q330**\n (R10: no nugget for numbers that appear only in an example), 1 `pointer_uncovered` (Q710), 7\n `backreference` (resolved inside the nugget). Gemini and Qwen add `value_without_period` (8 and 15) and\n `span_fuzzy` (6 and 3), as in the preview.\n\n### 2.1 Validator false positives fixed\n\nThe first validation gave 9 `enum_item_uncovered` errors (1 GPT, 4 Gemini, 4 Qwen). None was an omission:\n\n1. **Q706** lists \"a) 22,5%, em aplicações com prazo de até seis meses;\" twice, word for word (long-term and\n short-term tables). `locate()` marked only the first occurrence as covered. It now marks every exact\n occurrence.\n2. **Q330**: Qwen's spans for the PGD items leave out a long parenthetical (\"(para os servidores que contribuem\n … Linha 03 do Quadro 3 …)\"), so they cover 42–46 % of the item, under the 50 % sentence threshold. Plan v2\n §3.5.1 asks whether an item is \"covered by some span\"; an **enumerated item** now counts as covered from\n 30 %. Sentences keep 50 %.\n\nAfter the fix: 0 errors in every set. The committed preview outputs were not revalidated.\n\n## 3. Same-model noise vs cross-family agreement (§3.5.2)\n\nAlignment by `gemini-3.8-flash` (`align_v1`): for each nugget of A, the B nuggets with the same fact and the\nrelation (`same`, `a_broader`, `b_broader`, `overlap`, `conflict`, `none`). \"Matched\" = any relation but\n`conflict`/`none`.\n\n| A | B | Matched in B | `same` | `conflict` | Importance agreement (`same`, one-to-one) |\n|---|---|---:|---:|---:|---:|\n| GPT | GPT r2 | 100 % | 99 % | 0 | 95 % (133) |\n| GPT | GPT r3 | 100 % | 94 % | 0 | 94 % (126) |\n| GPT | Gemini | 99 % | 81 % | 0 | 84 % (108) |\n| GPT | Qwen | 98 % | 75 % | 0 | 96 % (99) |\n| Gemini | Qwen | 99 % | 80 % | 0 | 83 % (92) |\n\n**Stability of the primary nuggets** (families with a matching nugget, the primary included):\n\n| | 3/3 | 2/3 | 1/3 |\n|---|---:|---:|---:|\n| Cross-family, any match | **97 %** | 2 % | 1 % |\n| Cross-family, `same` only (strict) | 70 % | 17 % | 13 % |\n| Same model (primary + r2 + r3), any match | 100 % | 0 % | 0 % |\n| Same model, `same` only | 93 % | | |\n\nBy category (any match): `resposta_direta`, `condicao` and `valor_prazo` are 100 % 3/3; every vital nugget is\n3/3; `regra` 94 %, `procedimento_pgd` 96 %, `definicao` 3 of 4. Importance is identical in all three families\nfor **80 %** of the 3/3 nuggets matched one-to-one.\n\n**Reading.** On these 30 questions the three families extract **the same facts**: no `conflict` relation in\nany pair, and no fact made by both other families is missing from the GPT set (0 omission candidates from\nthe alignment, §6). They differ in **how they split** facts (strict 3/3 is 70 %; the rest are `a_broader`,\n`b_broader` or `overlap`) and in **importance** (80 % three-way agreement). GPT's own runs differ much less\n(93 % strict, 94–95 % importance), so most cross-family disagreement is style and family, not sampling noise.\nThis supports the plan's choice of three families over repeated GPT runs (D8): replicates would have shown\nalmost perfect stability and hidden the granularity and importance differences.\n\n**Span overlap as a cheap aligner** (plan v2 §3.5.2: \"first by `source_span` overlap, then by an LLM\naligner\"). Taking the LLM alignment as reference, a span overlap ≥ 50 % of the shorter span finds 98 % of\nthe matches (recall) with 90 % precision, over the GPT–Gemini and GPT–Qwen pairs. For phase 3, span overlap\ncan settle most pairs, and the LLM is needed only for the rest and for the relation type. The aligner is\ncheap anyway: $0.0032 per call, ≈ $1.1 per pair of full sets with Batch.\n\n## 4. One call vs two calls (importance in a second call)\n\nThe 2-call set keeps the primary set's texts and asks `gpt-6.1-sol` only for vital/okay (`importance_v1`).\n\n- The second call changed **19 of 135** labels (14 %): 12 vital → okay, 7 okay → vital.\n- Against the label the **other two families agree on** (75 nuggets matched `same` one-to-one in both): 1-call\n **99 %**, 2-call **88 %**.\n- Same-model noise floor of the 1-call label (primary vs replicates): 94 % agreement.\n\nThe second call moves labels by more than the same-model noise and **away** from the cross-family\nconsensus. Caveat: the consensus comes from creation calls with the `create_v4` definition of importance, and\n`importance_v1` adds guidance of its own (\"Atenção notes are normally okay\"), so part of the gap is the\nprompt, not the call mode. Either way there is no sign that a dedicated call labels importance better, and\nplan v1 §3.2 sets two calls only \"if importance labels in the single call are clearly worse\".\n**Recommendation: one call.** Cost of the second call would have been ≈ $1.5 per full set (Batch).\n\n## 5. Prompt iterations\n\n**None needed.** `create_v4` passed every automatic check on the 30 questions (§2, §6, §7). Plan v2 allowed\niterations on the pilot; the only prompt changed during the pilot is the **round-trip checker** (§6.2), which\nis a robustness tool, not the creation prompt.\n\n## 6. Robustness checks (§3.5)\n\n### 6.1 Two-auditor review (`audit_v1`, C1–C6)\n\nAuditors `gemini-3.1-pro` and `qwen3.8-max` on the primary set, with the omission candidates of §3.5.2 and\n§3.5.4 (15 candidates in 7 questions, all from the round trip; none from the alignment).\n\n| Check | 3.1 Pro | Qwen3.8-Max | Both (same check) |\n|---|---:|---:|---:|\n| C1 faithful | 0.0 % | 3.0 % | 0 |\n| C2 self-contained | 0.0 % | 1.5 % | 0 |\n| C3 one unit | 0.7 % | 0.0 % | 0 |\n| C4 importance | 2.2 % | 1.5 % | 0 |\n| Any check | 3.0 % | 5.9 % | **2 nuggets (1.5 %), on different checks** |\n| C5 omissions / C6 redundant pairs | 0 / 0 | 1 / 0 | 0 / 0 |\n\nThe two nuggets flagged by both were Q679_N03 and N04 (3.1 Pro: \"Atenção note, should be okay\"; Qwen: \"adds\n'Para fins de apuração do imposto sobre a renda', not the answer's term 'imposto mensal sobre os ganhos\nlíquidos'\"). Plan v2 §3.5.3 sends \"items flagged by both auditors\" to repair, so **any** check counts, not\nonly the same one.\n\n**Repair round 1** (`repair_v1` appended to `create_v4`, `gpt-6.1-sol`): 1 question, 2 issues, $0.016.\nGPT replaced the terms with the answer's own (\"imposto mensal sobre os ganhos líquidos\", \"realizadas em bolsa\")\nand **kept `vital`**, which the rules allow (the Atenção note here is part of the answer to the question).\nRe-audit: both auditors pass all four Q679 nuggets; self-score 4/4. **After repair, 0 nuggets are flagged by\nboth auditors** (gate ≤ 2 %). One round was enough; the second round was not needed.\n\nSingle-auditor flags kept with their flag (plan v2 §3.5.3), e.g. Q624_N04/N07 \"abrangidas pela previsão legal\ncitada\" (Qwen, C2): a real self-containment slip caused by R6 (citations go to `legal_basis`, so the text says\n\"the cited provision\"). Worth a sentence in `create_v5` if it recurs in phase 2.\n\n### 6.2 Round trip (§3.5.4)\n\n`gemini-3.8-flash` rewrote each answer from the nugget texts alone; `qwen3.8-max` listed missing or altered\ngold statements.\n\n| Checker prompt | Findings | Real omissions |\n|---|---:|---|\n| `roundtrip_check_v1` | 15 in 7 questions | 0: 12 are **legal citations** the rewrite lacks (R6 keeps them out of the nugget text, and the writer sees only texts), 1 is the Q710 pointer, 2 are wording |\n| `roundtrip_check_v2` (= v1 + \"do not list legal references\") | **1** | 0: the Q710 pointer sentence, excluded by `create_v4` |\n\n`roundtrip_check_v2` is now the default. The auditors of §6.1 saw the v1 candidates, and they confirmed none\nof them, which is the right outcome; their cache keys keep the v1 candidates.\n\n### 6.3 Added: planted errors (auditor sensitivity)\n\nThe ≤ 2 % gate means little if the auditors flag little because they are lenient. So, as the known-answer tests\ndo for the judge, one nugget per question of the repaired set was damaged by rule, each with the check it\nshould fail (`planted.py`): scope clause added 11, verdict polarity 5, vital → okay 4, two nuggets merged 3,\nquantifier 3, condition removed 3, value 1. The type rotation falls back to \"addition\" when a type does not\napply, so additions are over-represented and value changes rare.\n\n| Auditor | Planted errors flagged | On the expected check | Other nuggets flagged |\n|---|---:|---:|---:|\n| `qwen3.8-max` | **29/30** | 29/30 | 4/102 (3.9 %) |\n| `gemini-3.1-pro` | **29/30** | 29/30 | 0/102 (0.0 %) |\n| **both** | 28/30 | | |\n\n3.1 Pro missed only Q703_N03 (\"addition\"), and that one is a **flaw of the planted test**: the nugget is\nalready about a non-resident investor, so the appended \"inclusive quando o contribuinte for não residente no\nBrasil\" changes nothing. Not flagging it is correct, so Pro caught 29 of the 29 real errors. A phase 4\nversion of `planted.py` should skip an addition clause that the nugget already implies.\n\nQwen missed only one merge (Q705). Its false-flag rate on undamaged nuggets matches its rate on the clean set\n(3.7 % after repair), so **its low flag rate on the real nuggets means few errors, not leniency**.\n\n### 6.4 Gold self-score (`assign_v2`)\n\n| Judge | Set | Support rate | Non-`support` |\n|---|---|---:|---|\n| `gemini-3.8-flash` | GPT / GPT `rep1` | 98.5 % / 98.5 % | Q054_N01, Q622_N02 |\n| `gemini-3.8-flash` | Gemini | 98.4 % | the same two facts |\n| `gemini-3.8-flash` | Qwen | 100.0 % | — |\n| `gemini-3.1-pro` | GPT / GPT `rep1` | 98.5 % / 98.5 % | Q054_N01, Q622_N02 |\n| `qwen3.8-max` | GPT | 99.3 % | Q054_N01 |\n| `gpt-6.1-sol` | GPT | 99.3 % | Q622_N02 |\n\nGate ≥ 98 % passed by every judge, by a narrow margin. Both causes are known:\n- **Q622_N02**: the gold answer itself is **truncated** in `answer_cleaned` (\"… deve ser informada na\n Declaração de\"). A dataset problem, §8.\n- **Q054_N01**: GPT carried the question's premise into the nugget (\"mesmo que não influenciem no saldo de\n imposto…\"); the answer does not repeat it. A mild R5 slip (\"nothing that is only in the question\"). Both\n Gemini and Qwen avoided it.\n\n## 7. Known-answer tests (§5.7, judges `gemini-3.8-flash` and `gemini-3.1-pro`)\n\n141 tests built from the repaired GPT set: G 30, V 6, Y 6, N 5, D 25, C 9, W 30, E 30. Detection = target not\n`support`; specificity = non-targets still `support`.\n\n| Type | Flash detection (as `contradicts`) | Flash specificity | Pro detection (as `contradicts`) | Pro specificity |\n|---|---:|---:|---:|---:|\n| G gold | — | 99 % | — | 99 % |\n| V value changed | **100 % (100 %)** [15] | 100 % | 100 % (100 %) [15] | 100 % |\n| Y year changed | **100 % (100 %)** [6] | 100 % | 100 % (100 %) [6] | 100 % |\n| N verdict flipped | **100 % (100 %)** [5] | 100 % | **60 % (40 %)** [5] | 100 % |\n| D span deleted | 88 % [26] | 96 % | 92 % [26] | 91 % |\n| C condition removed | 78 % [9] | 100 % | 89 % [9] | 100 % |\n| W wrong question | 97 % [135] | — | 96 % [135] | — |\n| E empty | 100 % [135] | — | 100 % [135] | — |\n| **Pooled** | sens. 97.3 %, spec. 98.5 %, **BA 97.9 %**; `contradicts` precision 90 % | | sens. 97.0 %, spec. 97.2 %, **BA 97.1 %** (all 141 tests); precision 96 % of 24 | |\n\n- **Gate \"sensitivity ≥ 0.90 on value, year and verdict corruptions\" (§3.5.6): Flash passes (100 % on all\n three). 3.1 Pro fails on verdicts** (3 of 5): it reconciles a leading \"Não\" with an affirmative body\n (\"a resposta afirma explicitamente que é atividade rural, apesar de iniciar com 'Não'\").\n- **D2 (Pro replaces Flash only if clearly better, > 0.05 BA): not the case.** Flash stays the Gemini judge\n candidate. The year-corruption test also confirms that `assign_v2`'s implicit-period rule did not make the\n judges lenient on a *different* year (6/6 `contradicts`, both judges).\n- **Most misses are test-construction artifacts**, checked one by one: a deleted verdict that the rest of the\n answer still implies (503_D, 679_D); a removed condition restated in other words in the same answer\n (259_C: \"se configurar prática comercial esporádica\"); a removed exception repeated in another item (330_C);\n a \"wrong question\" that is a near-duplicate of the right one (336_W ← Q335, 507_W ← Q506); content of the\n deleted span repeated in other items (330_D). Non-target \"errors\" in D are mostly nuggets that relied on\n the deleted context (073_D, 028_D, 624_D). **One real judge error**, made by both judges: 622_W, a rule\n about traveler's cheques credited from an answer about foreign cash (Q621).\n- **Fixes for phase 4:** W must not take a near-duplicate neighbour (another chapter, or a lexical-overlap\n cap); D and C must check that the removed fact is not restated elsewhere (e.g. self-score the target\n nugget against the corrupted answer with a cheap judge and drop tests it still supports, or report them\n apart); V should add the corpus \"other period\" variant.\n- **3.1 Pro output glitch:** two Pro justifications came back with garbled characters in place of accented\n letters (\"porxytytm nxytyto menciona…\"). The labels were valid. Recorded because 3.1 Pro is a preview\n model (plan v2 §9 item 3).\n\n## 8. Dataset finding: `answer_cleaned` loses content in ≈ 14 answers\n\nFound through Q622's self-score. `answer_cleaned` (inherited from v1.0/v1.1; plan v2 W2 \"gold answers checked\nunchanged\") is the nugget source. Comparing it with the raw `answer` over all 715 questions:\n\n- 613 differ, almost always because the citation block and the \"Consulte a pergunta NNN\" pointers are\n removed, as intended.\n- **≈ 14 lose real content**, because the cleaning removes the **whole line or parenthetical** around a\n pointer or citation:\n\n| Q | Lost from `answer_cleaned` |\n|---|---|\n| 622 | the end of the last sentence: \"… na Declaração de **Bens e Direitos da mesma forma prevista para a moeda estrangeira mantida em espécie.**\" |\n| 625 | \"… poderão ter seus valores **atualizados para o valor de mercado em 31 de dezembro de 2023.**\" |\n| 129 | items **IV** and **VI** (\"as despesas escrituradas em livro-caixa, quando permitidas\"), leaving \");\" |\n| 186 | \"sujeitando-se à incidência **do Imposto sobre a Renda na Fonte e na DAA.**\" |\n| 326 | \"… base de cálculo do imposto **devido na declaração**\", and two bullets cut to \");\" |\n| 122 | \"(ou, alternativamente, informar a chave PIX do titular da declaração)\" |\n| 578 | \"(falta de pagamento do preço ajustado, no caso)\" |\n| 035, 037, 040, 066 | \"… ou do “Meu Imposto de Renda”\" (an access channel) |\n| 653 | \"… líquidos em renda variável\" |\n| 442 | \"(especificado no final da pergunta)\", 8 times |\n| 666 | a \"No aspecto fiscal, …\" parenthetical |\n\nOnly Q622 is in `stratified_30`. The list comes from a diff script; it may miss a few cases or include a\nborderline one. **Decision for the user before phase 2** (§12): fix `answer_cleaned` for these answers in\nthe v2.0 build (an override file, like `reference_overrides.json`), or keep v1's text and flag them. The\ngold answers are also what the RAG answers are compared with, so the fix affects more than the nuggets.\n\n## 9. Operational findings\n\n### 9.1 Gemini 3.1 Pro: 250 requests per model per day\n\nThe known-answer run with 3.1 Pro stopped on HTTP 429 `generate_requests_per_model_per_day, limit: 250,\nmodel: gemini-3.1-pro` (200 Pro calls in this pilot plus ≈ 50 in the preview runs earlier the same day). The\nclient used to back off 2.5 min per call on any 429. It now raises `QuotaExhausted` at once on a per-day\nquota. `known judge` writes partial results; rerunning the same command completes them from the cache.\n\n**Consequence for phase 2:** at 250 requests per day, 3.1 Pro cannot run synchronously over 715 questions\n(second set: 715; auditor 1: ≈ 750; known-answer subset: ≈ 300). Phase 2 needs the **Batch API** (plan v2\n§6.3; implemented since, §13.2; batch quotas are separate) or a higher quota tier. Flash, GPT and Qwen\nraised no quota errors.\n\n**The reset is at 00:00 UTC, not midnight Pacific.** The 429 at 03:25 UTC on 2026-10-13 said \"retry in\n20h34m\", i.e. at 00:00 UTC. The probe (one request every 15 min since 19:24 UTC) was refused until 03:25,\nwhen a single request went through and the next ones were refused again. We made no other Pro calls in\nbetween, so the quota did not visibly reset at 00:00 UTC on 2026-10-13. The window is unclear; do not\nplan synchronous Pro runs around it, use Batch.\n\n### 9.2 Other\n\n- No schema failures and 1 retry in 914 calls. Mean latency per call over all roles: GPT 12 s, Flash 6 s,\n 3.1 Pro 14 s, Qwen 24 s.\n- Cache: 20 MB for the pilot (`nuggets/pilot/cache/`, gitignored). Plan: push it to the private HF dataset repo\n at the end of the phase (resolution note §3.2). **Not done**: it needs your go-ahead (outward-facing).\n\n## 10. Costs\n\nAll at standard prices, from `nuggets/pilot/costs.csv` (`report_pilot.md` §1 has every role and model).\n\n| Provider | Roles | Calls | Cost |\n|---|---|---:|---:|\n| OpenAI `gpt-6.1-sol` | creation ×3, importance, repair, self-score | 151 | $1.04 |\n| Gemini `gemini-3.1-pro` | creation, auditor (+ planted), self-score, known-answer | 235 | $4.62 standard, $4.29 billed |\n| Gemini `gemini-3.8-flash` | alignment, round-trip writer, self-score, known-answer | 382 | $1.31 |\n| Alibaba `qwen3.8-max` | creation, auditor (+ planted), round-trip checker, self-score | 181 | $1.65 |\n| **Total** | | **949** | **$8.62 standard, $8.29 billed** |\n\nThe plan's pilot items (§6.4: OpenAI ≈ $5–7, Gemini ≈ $2, Alibaba < $1) cost less on OpenAI (one call per\nquestion at ≈ $0.009, one replicate pair instead of prompt iterations) and more on Gemini, because the pilot\nalso ran the 3.1 Pro auditor and the full known-answer set with 3.1 Pro.\n\nThe 35 Pro calls that finished the pilot went through Batch: $0.65 at standard prices, **$0.32 billed**\n(estimated at submission: $0.30). The ≈ $1.2 expected for them had overestimated the output length.\n\n**Running total of the nuggetization work (billed):** preview $2.63 + pilot $8.29 = **$10.92**, plus the batch\nlive test of §13.3 ($0.035).\n\n### 10.1 Updated estimate, phases 1–4 (from the pilot's per-call costs, `report_pilot.md` §9)\n\nExtrapolated to 715 questions on question + answer length; Batch prices where the provider has them.\n\n| Item | Pilot-based | Preview-based (v3) | Plan v2 §6.4 |\n|---|---:|---:|---:|\n| Creation `gpt-6.1-sol`, Batch | $2.8 | $3.75 | ≈ $9 |\n| Creation `gemini-3.1-pro`, Batch | $10.9 | $11.23 | ≈ $12 |\n| Creation `qwen3.8-max` | $8.9 | $10.03 | ≈ $11–14 |\n| Auditor 1, 3.1 Pro, Batch (+10 % re-audit) | $6.5 | — | ≈ $16 |\n| Auditor 2, Qwen3.8-Max (+10 %) | $8.3 | — | ≈ $15 |\n| Alignment, 3 cross-family pairs, Flash Batch | $3.3 (less with spans first) | — | ⎫ |\n| Round trip: Flash writer (Batch) + Qwen checker | $1.1 + $4.3 | — | ⎬ ≈ $5 + $8–11 |\n| Repair calls, GPT (≈ 3 % of questions) | < $0.5 | — | ≈ $3 |\n| Gold self-score: Flash on 3 sets + 3.1 Pro on the primary, Batch | $3.5 + $4.3 | — | (in §5.7) |\n| Known-answer: ≈ 3,000 Flash + 300 Pro calls, Batch | $5.2 + $1.7 | — | ≈ $18 |\n| HF endpoint (open Qwen judge, not measured) | $10–25 | $10–25 | ≈ $10–25 |\n| **Total, phases 1–4** | **≈ $71–86** | ≈ $77–92 | ≈ $115–140 |\n\nWith the ±25 % margin of the preview note §11 on the measured part (≈ $61): **≈ $56–102**. Scoring\n(phase 5), per answer run and nugget set: Flash Batch ≈ $1.2–1.3 at gold-answer length, unchanged from\nthe preview estimate (× 1.5 until real answer lengths are known).\n\n## 11. Pending items of this pilot (done 2026-10-13 via Batch)\n\n`after_reset.sh` (scratchpad) waited for the Pro quota. Its probe got through at 03:25 UTC, but the real\ncalls were refused again at once (§9.1). The two items were then sent as two Batch jobs (30 + 5 requests: 30\nplanted audits and 5 known-answer tests); both succeeded within 5 minutes, 35/35 results, 0 failed:\n\n```bash\nO=\"--out nuggets/pilot --sample stratified_30 --budget 13.00\"\n$P $N $O --batch known judge --set gpt-6.1-sol.rep1 --judge gemini-3.1-pro # 5 missing tests\n$P $N $O --batch audit --set gpt-6.1-sol.rep1.planted --auditor gemini-3.1-pro # Pro half of §6.3\n$P $N --out nuggets/pilot batch wait --every 60\n# the same two commands without --batch (outputs from the cache), then:\n$P $N $O pilotreport\n```\n\nResults are in §6.3 (Pro 29/30 planted errors) and §7 (Pro BA 97.1 % on all 141 tests). None of the §7\nconclusions changes: Pro still flips only 60 % of verdicts, and Flash stays the judge candidate.\n\n## 12. Decisions for the user (phase 1 gate and before phase 2)\n\n**Status 2026-10-13:** items 1–3 closed as recommended (with (a) and (b) of item 3); 4–5 done; the open\nitems are tracked in `docs/20261013_103834_nuggetization_open_decisions.md`.\n\n1. **Prompt: `create_v4`** (recommended; §2, §5–§7). No iteration was needed.\n2. **Call mode: one call** (recommended; §4).\n3. **Gate thresholds (plan v2 §3.5.6, open question 6):** all four passed on the pilot (0 hard errors; self-score\n ≥ 98 % with Flash and 3.1 Pro; 0 % flagged by both auditors after repair; Flash sensitivity 100 % on V/Y/N).\n Suggested change: count a nugget as \"flagged by both\" when both auditors flag it **on any check** (as done\n here), and add the planted-error test as a condition on the auditors (e.g. each catches ≥ 80 %), so the\n ≤ 2 % gate is meaningful.\n4. **`answer_cleaned` content loss (§8):** fix the ≈ 14 answers in the v2.0 build before phase 2\n (recommended; it changes gold answers that are also the RAG reference), or keep them and flag them.\n **Done (§13.1).**\n5. **Gemini 3.1 Pro quota (§9.1):** implement Batch submit/collect before phase 2 (README \"still missing\"\n item 5; recommended), or raise the quota tier. **Done (§13.2, §13.3); used for §11.**\n6. **Phase 4 builder fixes (§7):** W without near-duplicate neighbours; D/C dropping tests whose fact is\n restated; the corpus \"other period\" V.\n7. **Cache backup** to the private HF dataset repo (§9.2): say when, and I will push it.\n\nNot decided here, still open from the plan: the optional \"expanded\" score on `has_pointer` questions (preview\nnote §13.5 item 4), effort escalation for long answers (no sign of need: the longest answers, Q624 and Q330,\nhad no omissions), and the open-weight Qwen judge (D4).\n\n---\n\n## 13. Follow-up (2026-10-12 20:03): gold-answer fix and Batch API\n\nThe user asked for both items of §12 (4 and 5) and for explanations of items 1–3. The gate decisions 1–3 and\n6–7 are still open.\n\n### 13.1 `answer_cleaned` fix (§8)\n\n**Cause** (found by an inventory of every deletion the v1 cleaning made, all 715 answers): the cleaning is\nline-based. It drops a line from a leading \"(\" up to the next \".\" (so \"(Lei nº 10.522, …\" leaves a lone\n\".\"), and on a line with \"consulte … pergunta N\" it drops everything from the line start to the pointer.\nA diff heuristic sorted its 879 deletions into citation blocks (596), deletions containing a pointer\n(253, mostly a citation block followed by \"Consulte …\", or a pointer-only sentence), acronyms in\nparentheses (11) and others (19). Each non-citation deletion was then read by hand. Intended removals stay\nremoved, including pointer-only sentences, consistent with `create_v4`. The rest lost text or left\nstray punctuation.\n\n**Fix** (`scripts/dataset/answer_overrides.json`, applied by `build_v2_dataset.py`):\n- 25 answers restored by **37 hand-verified find/replace edits**. Each edit is pinned to the SHA-256 of\n the v1.1 text and to an exact occurrence count, so a changed input makes the build fail.\n - Lost text: 035, 037, 040, 066 (the \"Meu Imposto de Renda\" channel / item c / item 3.2); 122 (PIX);\n 129 (items IV and VI, and an empty \"Atenção:\"); 168; 186; 326; 442 (8 × \"(especificado no final da\n pergunta)\"); 578; 622 (truncation); 625 (date); 653.\n - A half-removed pointer parenthetical, now removed whole: 171.\n - Acronyms and parentheticals at a line start: 135 \"(Holanda)\", 150 \"(UPU)\" ×2, 177 \"(Fapi)\", 201,\n 319, 327, 402, 483 \"(DAA)\", 419 \"(RFB)\", 460 \"(e-CAC)\".\n - Two items found while writing the edits, in addition to §8's list: 168 (\"reciprocidade de\n tratamento\") and 171.\n- A general rule: a line made only of punctuation (\".\", \");\", \":\") is appended to the previous line when\n that line has no final punctuation (079, 335: \"… se da união resultou filho\" + \".\"), and dropped\n otherwise. It touched 22 more answers.\n- **Result:** 47 answers differ from v1.1, and only in `answer_cleaned`. `references.jsonl` and\n `documents.jsonl` are byte-identical after the rebuild, and so is the rest of `build_report.json`,\n which now lists the edited questions (`answer_overrides`). `scripts/dataset/tests`: 36 passed.\n `dataset/README.md` (\"Changes from v1.1\") and `scripts/dataset/README.md` describe the fix.\n- **Effect on the pilot:** 2 of the 30 pilot questions changed. Q622 is now complete; Q676 lost a\n stray \".\" line. The pilot outputs were made from the old text and are not regenerated. Q622_N02's two\n `partial_support` labels (§6.4) came from the truncation. Phase 2 starts from the new text (`sample`\n copies `dataset/questions.jsonl` and records its SHA-256).\n\n### 13.2 Batch API (§9.1)\n\n`scripts/llm_client/batch.py` and a global `--batch` flag on `nuggets.py`: any command can queue its\nuncached OpenAI/Gemini requests as Batch jobs, then `batch wait` caches the results, and the same command\nrerun without `--batch` writes its outputs from the cache. Usage and rules: `scripts/nuggets/README.md`\n\"Batch mode\".\n\n- **Same requests, same cache:** request bodies and response parsing are now shared functions used by\n both paths. Checked: the new parsers reproduce the cached text of all 715 OpenAI/Gemini responses in\n `nuggets/pilot/cache/`, and a synchronous rerun of a pilot command is served entirely from the cache.\n- **Budget:** checked at submission (ledger + estimated job cost ≤ `--budget`), because a submitted job is\n billed whole. Ledger rows of batch results are tagged `batch:`; `usd_standard` keeps the synchronous\n price, and the cap and `report_pilot.md` (new \"Billed\" column) count them at half.\n- **Daily quota:** a command that hits one now finishes the other items and stops with a clear message.\n Completed calls are cached, so a rerun after the reset resumes. This is why no \"partial outputs\"\n mode was added for `create`/`audit`: the cache already makes them resumable, and partial nugget sets\n would break the later steps.\n- **Live test:** §13.3 (passed).\n\n### 13.3 Batch live test (2026-10-12 21:55)\n\nScratch output folder, sample `tiny_2` (Q023, Q503), `create` with GPT-6.1 Sol and Gemini 3.8 Flash, `--budget 0.50`.\n\n| Step | Result |\n|---|---|\n| Synchronous `create` (replicate 0) | 4 calls OK, outputs written |\n| `--batch create --replicate 1` | 2 jobs submitted at 20:02 (1 OpenAI, 1 Gemini, 2 requests each); no outputs written; resume message printed |\n| `batch wait --every 60` | Gemini collected after **≈3 min**; OpenAI `completed` in **≈1 h 53 min**; 2/2 cached each, 0 failed, 0 without a result |\n| Rerun without `--batch` | all 4 items `[cache]`; `create/<model>.r1/` written; token counts equal the batch rows |\n| Ledger | 4 `batch:create:…:r1` rows, `latency_s` 0.0; cost counted at half |\n\n- Both result paths work: the OpenAI output file and the Gemini `responsesFile`.\n- Test cost: **$0.035** ($0.023 sync + $0.023 standard / 2 for batch).\n- OpenAI's turnaround is far slower than Gemini's on this tiny job (both within the 24 h window). Phase 2\n should plan for hours, not minutes, and keep using `batch wait`.\n- Batch quotas are separate from the synchronous daily cap (§9.1), so the 3.1 Pro runs of phase 2 can go through\n `--batch` without waiting for the per-day reset.\n","20261013_103834_nuggetization_open_decisions.md":"# Nuggetization — decisions after the phase 1 pilot\n\n**Generated:** 2026-10-13 10:38:34 (local time, from `date +%Y%m%d_%H%M%S`).\n**Source:** §12 of `docs/20261012_192640_nuggetization_phase1_pilot.md` (the pilot note), plus the items still\nopen in plan v2 (`docs/20261011_224049_gold_answer_nuggetization_plan_v2.md`).\n**Purpose:** one place for what is decided and what is still open. Update the status of an item here when it\nis decided.\n\n## 1. Closed\n\n| # | Decision | Outcome | Date | Evidence |\n|---|---|---|---|---|\n| 1 | Creation prompt | **`create_v4`**, unchanged | 2026-10-13 | Pilot note §2, §5–§7: 0 rejected sets after the validator fixes; self-score 98.5–100 % |\n| 2 | Call mode | **One call** (nuggets and `vital`/`okay` labels in the same response) | 2026-10-13 | Pilot note §4: the 2-call mode changed 14 % of labels and agreed less with the other families' consensus (88 % vs 99 %), at a higher cost |\n| 3 | Acceptance thresholds | **Plan v2 §3.5.6 thresholds, plus (a) and (b) below** | 2026-10-13 | Pilot note §6, §7, §12 |\n| 4 | `answer_cleaned` content loss | Fixed in the v2.0 build (`scripts/dataset/answer_overrides.json`; 47 answers changed) | 2026-10-12 | Pilot note §8, §13.1 |\n| 5 | Gemini 3.1 Pro daily quota | Batch API mode (`--batch`, `batch wait`) | 2026-10-12 | Pilot note §9.1, §13.2–§13.3; used to finish the pilot (§11) |\n| 6 | LLM access for phase 2 | **OpenRouter for all four models**, `flex` tier for GPT and Gemini (half price, synchronous; no 250/day quota); direct route kept as fallback; no parity check before phase 2 (compared on the 30 pilot questions afterwards); $150 prepaid. **Implemented and probed 2026-10-21; default route** | 2026-10-20 | `docs/20261020_130829_openrouter_support_plan.md` §7, §8 |\n\n### 1.1 Thresholds adopted (decision 3)\n\nA nugget set passes when all of these hold:\n- **0 hard errors** (schema, span, validator).\n- **Gold self-score ≥ 98 %** of nuggets labelled `support` against their own gold answer.\n- **≤ 2 % of nuggets flagged by both auditors**, after repair.\n - **(a)** A nugget counts as \"flagged by both\" when each auditor flags it **on any check**, not necessarily the\n same one. Q679 in the pilot was flagged by both auditors, for different reasons.\n- **Judge sensitivity ≥ 0.90** on the value, year and verdict corruptions of the known-answer tests.\n- **(b)** **Each auditor catches ≥ 80 % of the planted errors** (one damaged nugget per question; pilot note\n §6.3). This makes the ≤ 2 % gate meaningful: a lenient auditor would flag little and still pass it.\n\nPilot values: 0 hard errors; self-score 98.5 % or more with every judge; 0 % flagged by both after repair;\nFlash 100 % on V/Y/N; planted errors Qwen 29/30, 3.1 Pro 29/30 (its miss is a test flaw, item 6).\n\n## 2. Open\n\n### 2.1 Before phase 4: fixes to the known-answer test builder (pilot note §12 item 6)\n\nThe known-answer tests corrupt a gold answer and check that the judge notices. Most judge \"misses\" in the\npilot (pilot note §7) were flaws in the generated tests, not judge errors:\n\n- **W (answer to the wrong question):** the substitute answer sometimes comes from a near-duplicate question,\n so the nugget really is supported. Fix: exclude near-duplicate questions as the source.\n- **D / C (a sentence or condition deleted):** the deleted fact is sometimes restated elsewhere in the\n answer, so `support` is correct. Fix: drop tests whose fact survives in the remaining text.\n- **V (value changed):** replace the synthetic bump with a real value of the same item for another period,\n taken from the corpus. This is a harder, more realistic test.\n- **Planted errors (`planted.py`, added 2026-10-13):** skip an \"addition\" clause that the nugget already implies\n (Q703_N03: the clause \"inclusive quando o contribuinte for não residente no Brasil\" was appended to a\n nugget already about non-resident investors).\n\n**To decide:** whether to do these, and when (suggested: before phase 4).\n\n### 2.2 Cache backup to the private HF dataset repo (pilot note §12 item 7)\n\nThe cache (`nuggets/<run>/cache/`, gitignored; ≈ 20 MB for the pilot) holds every raw API response. Reruns\nare free and reproducible because of it. The plan backs it up to the private HF dataset repo at the end of\neach phase.\n\n**To decide:** when to push. This is outward-facing, so it is not done without the user's go-ahead.\n\n### 2.3 \"Expanded\" score on `has_pointer` questions (plan v2; preview note §13.5 item 4)\n\nSome gold answers only point to another question (\"consulte a pergunta N\"); `create_v4` makes no nugget for\nthe pointer itself. Optionally, score such answers a second time with the target question's nuggets added.\n\n**To decide:** whether to report this score. It matters only at scoring time (phase 5).\n\n### 2.4 Open-weight Qwen judge (plan v2 D4)\n\nAn open-weight Qwen model as a judge next to Gemini Flash, for reproducibility with an open model. It would be\nserved from an HF endpoint; estimated $10–25, not measured.\n\n**To decide:** whether to include it, and when to test it (it needs its own known-answer run). If it is\nincluded, the user will probably prefer an HF endpoint, as for the embeddings, over OpenRouter (2026-10-20;\nOpenRouter plan §7).\n\n## 3. Not open (for the record)\n\n- **Effort escalation for long answers** (plan v2): no sign of need in the pilot; the longest answers\n (Q624, Q330) had no omissions. Revisit only if phase 2 shows omissions on long answers.\n- **Gemini judge: Flash, not 3.1 Pro** (plan v2 D2: Pro replaces Flash only if its balanced accuracy is\n > 0.05 higher). On all 141 tests, Flash had BA 97.9 % and Pro 97.1 %. Pro also caught only 3 of 5 flipped\n verdicts (pilot note §7).\n\n## 4. Next step\n\n**Update 2026-10-21:** phases 2–4 done (`docs/20261021_155704_nuggetization_phases_2_to_4_execution.md`). The\nbuilder fixes of §2.1 were implemented and used. New open items are in that note's §6.\n\nWith decisions 1–3 closed, **phase 2** can start on the 715 questions: creation by the three families,\nthe two auditors with repair, and Gemini 3.1 Pro and GPT through Batch, with `--budget` on every run (pilot\nnote §10.1 has the estimate).\n","20261013_105850_segmentation_token_cap_summary.md":"# Segmentation maximum length: strategy and its effect on the corpus\n\n**Generated:** 2026-10-13 10:58:50 (local time, from `date +%Y%m%d_%H%M%S`).\n**Purpose:** a quick reference that gathers what the earlier notes decided about chunk length, with the\nfigures of the current corpus. It decides nothing new.\n**Sources:**\n- `docs/20260924_123747_segmentation_implementation_plan.md` §2.6 (cap and tokenizer), §5.3 (non-statutory\n splitting), §5b (oversize article splitting);\n- `docs/20260923_193852_segmentation_strategies_for_rag_experiments.md` §6 item 5;\n- `docs/20260924_184339_segmentation_results.md` (first run) and the Gemini `countTokens` check;\n- `docs/20261005_184116_segmentation_s3_vs_lima_ementa_and_caput_strategy_plan.md` E1 (128-token ementa);\n- `docs/20261009_121822_nonstat_reparse_decision_and_pipeline_rerun_log.md` (current corpus);\n- `segmented/segmentation_report.md` (rerun of 2026-10-09 12:57, the current chunk set).\n\n## 1. Strategy\n\n### 1.1 The cap: 1,024 tokens per basic unit (decided 2026-09-24)\n\nEvery chunk that a strategy indexes as its basic unit (`ART`, `DSP`, `TXT`, `TAB`) must be ≤ 1,024 tokens.\n\n**The cap is about chunk size, not a model limit.** The embedding models accept 8,192 tokens\n(`text-embedding-3-small`, `gemini-embedding-2`) or 32 k (Qwen3-Embedding-4B, jua-4B-mixed,\ninf-retriever-v1). Non-statutory chunks and parts of long articles compete with articles in the same index\nand the same context budget, so they should be about the size of a typical article, not of a whole opinion.\n1,024 tokens ≈ the 97th percentile of article length (article p50 372, p90 1,605, p99 4,841 characters).\n\n### 1.2 How tokens are counted\n\n- **Reference tokenizer:** the per-text maximum of `tiktoken:cl100k_base` and `hf:Qwen/Qwen3-Embedding-4B`\n (`--tokenizer max:tiktoken:cl100k_base,hf:Qwen/Qwen3-Embedding-4B`). Qwen counts ≈ 4–6 % more on this\n corpus, so it sets the count almost everywhere.\n- **Gemini** cannot be counted locally at corpus scale. A sample of 600 chunks (500 random + the 100\n largest) was checked with `countTokens`: Gemini counts ≈ 12 % fewer tokens (ratio p50 0.88, max 1.10); its\n largest chunk was 7,253 tokens, so nothing is truncated.\n- One segmentation run serves **all** embedding models, so every model embeds the same chunk set.\n\n### 1.3 The cap includes the metadata prefix and the ementa\n\nThe cap applies to the **full `Texto`**:\n\n```\n[ epígrafe | ementa (≤ 128 tokens) | annex label ] <article label / ancestor path> <body>\n```\n\nThe 128-token limit (`--ementa-max-tokens 128`, caput plan E1) is applied **first**, to the ementa alone.\nThe 1,024-token cap then applies to prefix + label/path + body. The ementa is **not** added on top of the\n1,024.\n\nWhere it is enforced:\n- `scripts/segmentation/split_oversize.py:86`: a part is accepted only if\n `count(prefix + HEAD + bodies) ≤ cap`;\n- `scripts/segmentation/segment_non_statutory.py:268–270`: TXT/TAB pieces are built from\n `prefix + heading + lines`;\n- `validate_segments.py`, check `cap`: uses the stored token count of the full chunk text.\n\nThe prefix is `[ epígrafe | ementa | annex label ]`, and only the ementa is limited to 128 tokens. So the\nprefix as a whole can go slightly above 128.\n\n**Prefix size**, measured on 2026-10-13 on a sample of 4,000 base ART/DSP/TXT/TAB chunks, in `cl100k_base`\ntokens (the reference count is ≈ 5 % higher):\n\n| Tipo | Sampled | Prefix median | p90 | p99 | max |\n|---|---:|---:|---:|---:|---:|\n| ART | 3,107 | 53 | 139 | 153 | 156 |\n| DSP | 153 | 85 | 102 | 145 | 153 |\n| TXT | 645 | 64 | 153 | 157 | 161 |\n| TAB | 95 | 85 | 153 | 181 | 181 |\n\n- The room left for content is ≈ 860–970 tokens per chunk.\n- In chunks near the cap (over 900 tokens, 245 in the sample), the prefix is a median **7 %** of the text.\n- **Side effect:** a document with a long ementa has less room per chunk, so its long articles split into\n slightly more parts. The caput plan (E1) recorded this when the 128 limit was chosen: \"a longer prefix can\n create a few more article parts\".\n\n### 1.4 What happens above the cap\n\n| Unit | Rule |\n|---|---|\n| **Articles (`ART`) and orphan dispositivos (`DSP`)** | Split along the structure by `split_oversize.py` (plan §5b), details below |\n| **Non-statutory text (`TXT`)** | Cut greedily at the last line ending in `.`, `;`, `:` or a paragraph number (`12.`); then at a line, then at a word boundary. No overlap. `Rotulo` gets `, parte k/n` |\n| **Tables (`TAB`)** | Packed by groups of rows, with the caption and header repeated in every part |\n| **A single line or table row above the cap** | Kept, flagged, and reported |\n| **Sub-article units (`CPT`, `PAR`, `INC`, `ALI`, `ITE`; S2)** | Not capped: the few above 1,024 tokens are kept as they are (all below 8,192) |\n| **Groupings (`CAP`, `SEC`, `TIT`…; S3)** | A separate limit of **8,192** tokens (`--grouping-max-tokens`), the real model limit. Groupings above it are left out of `chunks_all.csv` and listed in `segmented/groupings_over_limit.csv` (decision \"option 2\", 2026-09-24) |\n\n**How an article is split** (plan §5b):\n- Caput and paragraphs are packed greedily into parts.\n- A unit that is too big by itself is replaced by its children: incisos → alíneas → itens.\n- A single leaf that is still too big (usually a table) is split inside the leaf.\n- Every part repeats a HEAD: the article label + the caput sentence, plus the ancestor path when needed. So a\n part made of §§ 3–5 still reads \"Art. 8º <caput sentence> § 3º …\" (caput plan Q2).\n- Parts keep the `Tipo`, so S1 indexes \"article or article part\".\n- `urn` gets `_p<k>`, and `<csv>.prov.jsonl` records what each part covers.\n\n## 2. Effect on the current corpus (rerun of 2026-10-09: 77,080 base rows, 625 files)\n\n### 2.1 Splitting\n\n- **597 of ≈ 15.8 k articles (≈ 3.8 %) and 9 DSP were split**, into 1,626 parts.\n - 69 needed a split inside a single leaf.\n - In 8, the repeated HEAD was itself shortened to 256 tokens + \"…\" after its first full appearance\n (deviation D3).\n- **316 non-statutory TXT/TAB units (≈ 11 %) were split.** Opinions and soluções de consulta are much longer\n than articles.\n- **1 row is above the cap and cannot be cut:** a single 1,163-token table row of `portaria_2012_1114`. It is\n flagged.\n- **193 groupings above 8,192 tokens are left out** (243 before the 2026-10-09 rerun).\n- Validation: `cap` 0 violations; text coverage after splitting ≥ 99.8 % per file.\n\nLargest split articles:\n\n| Article | Tokens | Parts | Leaf split |\n|---|---:|---:|---|\n| Lei 10.865/2004, art. 8º | 16,239 | 26 | yes |\n| IN RFB 1.343/2013, art. 9º | 14,415 | 21 | yes |\n| RIR/2018 (`decreto_9580_20181122.anexo1`), art. 35 | 10,238 | 12 | |\n| LC 123/2006, art. 18 | 9,947 | 15 | |\n| Lei 9.718/1998, art. 5º | 6,997 | 11 | |\n| Lei 9.250/1995, art. 8º | 3,822 | 5 | |\n\nFull list: `segmented/segmentation_report.json`.\n\n### 2.2 Resulting lengths (reference tokens, base rows)\n\n| Tipo | Rows | p50 | p90 | p99 | max |\n|---|---:|---:|---:|---:|---:|\n| ART | 16,784 | 217 | 727 | 1,010 | 1,024 |\n| DSP | 875 | 166 | 742 | 926 | 1,009 |\n| TXT | 3,306 | 330 | 983 | 1,020 | 1,024 |\n| TAB | 532 | 310 | 977 | 1,023 | 1,163 |\n| CPT | 7,091 | 166 | 356 | 1,027 | 8,103 |\n| PAR | 19,675 | 150 | 253 | 489 | 5,776 |\n| INC | 18,235 | 168 | 280 | 473 | 3,956 |\n| ALI | 5,045 | 170 | 291 | 431 | 1,420 |\n| ITE | 1,575 | 164 | 277 | 416 | 1,358 |\n| SEC | 1,745 | 606 | 2,267 | 5,739 | 7,827 |\n| SSC | 567 | 521 | 2,037 | 4,192 | 7,771 |\n| CAP | 1,431 | 910 | 3,870 | 7,378 | 7,941 |\n| TIT | 187 | 1,886 | 6,218 | 7,953 | 8,102 |\n| SBT / LIV / PRT | 20 / 9 / 3 | 3,290 / 1,599 / 4,172 | — | — | 8,061 / 6,055 / 7,433 |\n\nThe capped types (ART, TXT, TAB) bunch up just below 1,024 (p99 ≈ 1,010–1,023). That is the greedy packing\nfilling parts up to the cap.\n\n### 2.3 Earlier runs (for the paper)\n\n| Run | ART/DSP split → parts | Groupings left out (> 8,192) |\n|---|---:|---:|\n| First run, 2026-09-24 | 656 (647 ART + 9 DSP) → 1,752 | 243 |\n| Rebuild R7, 2026-10-08 | 655 → 1,746 | 243 |\n| Rerun, 2026-10-09 (current) | 606 (597 ART + 9 DSP) → 1,626 | 193 |\n\nThe drop on 2026-10-09 comes mostly from five removed documents: Lei 3.071/1916, Lei 5.869/1973, IN RFB\n1.911/2019 with its 60 annexes, Decreto 7.030/2009 and IN RFB 1.505/2014.\n","20261013_111626_retrieval_metrics_views_and_position_metrics.md":"# Retrieval metrics: what \"all resolved gold\", the three views and the position metrics mean\n\n**Generated:** 2026-10-13 11:16:26 (local time, from `date +%Y%m%d_%H%M%S`).\n**Purpose:** a quick reference that explains how the legal-provision retrieval test is scored, from a Q&A\nwith the user. It decides nothing new. §4 is a proposal, not implemented.\n**Sources:**\n- `docs/20260927_204356_rag_pipeline_implementation_plan.md` §2.1 (gold, reachability) and §4.3 (views);\n- `docs/20261009_121822_nonstat_reparse_decision_and_pipeline_rerun_log.md` §9 (current results, `v2d`);\n- `scripts/rag/ragpipe/evaluation.py`, `metrics.py`, `context.py`;\n- `runs/retrieval/jua-4b-mixed/irpf/eval/v2d_either_containment_skip/report.md`.\n\n## 1. \"All resolved gold\"\n\nThe phrase, in titles such as \"Recall by budget (v2d, all resolved gold)\", says which gold items count in the\ndenominator.\n\n- **Resolved:** gold items come from `dataset/references.jsonl`. A reference counts only if the dataset build\n resolved it to a corpus document, which gives its document, its `article_ids` and its `provisions[]`\n (parsed from the citation text). In the first IR test, 42 references were `not_in_corpus` and were left out.\n Since the 2026-10-08 rebuild, no question has an unresolved reference. Only references dropped on purpose\n are excluded (144-05 was the latest).\n- **All, as opposed to reachable only:** each resolved item is tagged as **reachable** (at least one chunk\n of the strategy can match it) or **unreachable** (e.g. a document without chunks, an article id missing\n from the LexML). The plan reports two views:\n - **(a) all resolved gold:** unreachable items stay in the denominator and count as misses. The result is\n shown next to the **oracle** ceiling, the best recall possible given those gaps;\n - **(b) reachable gold only.**\n- **All questions:** \"all\" also means every question with gold, not a subset. §9.1 of the rerun note adds\n rows for subsets: questions whose gold cites a sub-article provision (366), a whole article (430), or a\n non-statutory document (195).\n\nCurrent gold (`v2d`): 1,724 document items, 1,958 article items, 2,230 provision items. Unreachable: 13 articles\n(the treaty articles) and 48 provisions, so the provision oracle is 0.969.\n\n## 2. The three views\n\nThe evaluation scores one ranked list of chunks per question and strategy in three ways (plan §4.3,\n`evaluation.py:5–13`). Raw rank is not comparable across strategies: an S1 chunk is a whole article, while an\nS2 chunk may be one inciso.\n\n| View | What is counted | Cutoffs | Levels | Question it answers |\n|---|---|---|---|---|\n| **Token budget** (headline) | Chunks in score order after containment de-duplication, taken while they fit in the budget (Qwen3 tokens) | 1k, 2k, 4k, 8k, 16k | document, article, provision | \"With the same amount of context, which strategy brings more of the cited provisions?\" |\n| **Unit projection** (\"unit\") | The chunk ranking turned into a ranking of distinct **documents** or **articles**: the position where each first appears. A grouping chunk stands for the articles it contains | R@1, 3, 5, 10, 20, 50, 100; **MRR; nDCG@10** | **document, article only** | \"How high does the right article or document rank?\" It is the view comparable with other retrieval papers |\n| **Raw** | Chunks as retrieved, one rank per chunk | k = 1 … 1000 | all | Diagnostic only |\n\nPlus the **oracle**: whether any chunk of the strategy can hit the item at all (the ceiling).\n\n### 2.1 Token budget: membership, not position\n\nBudget recall is a yes/no test per gold item: was it inside the selected context or not? Its position inside\nthe window does not matter. How the window is filled (`ragpipe/context.py`):\n1. Chunks are taken in score order.\n2. A chunk already covered by a higher-ranked one is dropped (containment de-duplication, `containment`).\n3. A chunk that does not fit is skipped and the next one is tried (overflow `skip`), until the budget is full.\n\nThe same selection code will build the generator's context in Phase 2, so the numbers describe exactly what\nthe LLM will see. Rank matters only for getting into the window. The five budgets give a coarse view of how\nearly the gold appears (1k vs 16k).\n\n### 2.2 Unit projection: an example\n\nS2 returns these chunks, best first, for a question whose gold is Lei 9.250 art. 8:\n\n| Chunk rank | Chunk | Article | Distinct article rank |\n|---:|---|---|---:|\n| 1 | Lei 9.250 art. 4, inciso III | art. 4 | **1** |\n| 2 | Lei 9.250 art. 4, § 1º | art. 4 | (already counted) |\n| 3 | Lei 9.250 art. 8, § 2º | **art. 8** | **2** |\n| 4 | Lei 9.250 art. 8, caput | art. 8 | (already counted) |\n\nAt chunk level the gold article first appears at rank 3. In the unit projection it is at rank 2, so its\nreciprocal rank is 1/2. A rank then means \"the n-th distinct article (or document)\", whatever the strategy\ncuts its chunks into, which makes S1 and S2 comparable at a fixed k.\n\n## 3. Position metrics today\n\n`scripts/rag/ragpipe/metrics.py` has `reciprocal_rank` (MRR) and `ndcg_at` (binary-gain nDCG).\n`evaluation.py:280–290` computes **MRR and nDCG@10 only on the unit projection**, so only at the **document\nand article levels**. They are reported in §4 of the eval report, with paired tests (§7 of the report, e.g.\nS2 − S1 document MRR +0.045 [+0.024, +0.067], p = 0.0001).\n\n**Unit projection, `v2d`, all resolved gold:**\n\n| Level (questions) | Strategy | R@1 | R@10 | R@100 | MRR | nDCG@10 | Oracle R |\n|---|---|---:|---:|---:|---:|---:|---:|\n| Document (596) | S1 | 0.237 | 0.753 | 0.969 | 0.635 | 0.592 | 1.000 |\n| | S2 | 0.263 | 0.780 | 0.970 | 0.681 | 0.630 | 1.000 |\n| | S3 | 0.263 | 0.786 | 0.969 | 0.683 | 0.634 | 1.000 |\n| | S2c | 0.250 | 0.789 | 0.965 | 0.665 | 0.626 | 1.000 |\n| | S4 | 0.251 | 0.790 | 0.965 | 0.668 | 0.628 | 1.000 |\n| Article (553) | S1 | 0.158 | 0.510 | 0.764 | 0.473 | 0.403 | 0.989 |\n| | S2 | 0.176 | 0.552 | 0.793 | 0.503 | 0.435 | 0.989 |\n| | S3 | 0.175 | 0.538 | 0.781 | 0.497 | 0.428 | 0.989 |\n| | S2c | 0.163 | 0.547 | 0.788 | 0.496 | 0.432 | 0.989 |\n| | S4 | 0.162 | 0.522 | 0.775 | 0.491 | 0.418 | 0.989 |\n\n**No position metric exists:**\n- **At the provision level.** A provision can be only partly covered: S1 never returns an inciso on its\n own, only the whole article that contains it. So there is no clean \"first position of this provision\" to\n project onto. Provision results have only the budget view (recall, with `full` and `partial` variants) and\n the raw view.\n- **In the budget view.** A plain rank is not comparable there: ten S2 chunks (≈ 150 tokens each) and ten S1\n articles (≈ 220 tokens, up to 1,024) are very different amounts of context.\n\n## 4. Proposal (not implemented): token-based position metrics\n\nA position metric is worth adding, **measured in tokens rather than ranks**. Then it works at all three\nlevels, including provision, and stays comparable across strategies with different chunk sizes.\n\n1. **Tokens to the first gold item** (and to the last), per question, in the budget-view context: how much\n context the generator must read before the evidence appears. Report the median, and the share of questions\n whose first gold item lies within 1k/2k/4k tokens.\n2. **Token-discounted gain:** an nDCG-like score whose discount depends on the tokens placed before each hit\n instead of its rank. A simpler alternative is the **area under the recall-vs-budget curve** (1k–16k),\n which summarises the whole curve in one number.\n\n**Why it matters most in Phase 2:** where a passage sits in the prompt affects LLMs (\"lost in the middle\"),\nand the context formatting (RAG plan §6.2) is not decided yet. The chunks could be ordered by score or by\ndocument order. A token-position metric would let us check whether answer quality, measured with nuggets,\nfollows where the evidence sits, and not only whether it is there.\n\n**Cost:** no API calls. The per-item tables already store ranks (`rank_full`, `rank_any`, `unit_pos`), and\ntoken counts are known. It needs a change in `evaluation.py` and a rerun of `evaluate` (≈ 30 s). Status:\n**proposed, waiting for the user's go-ahead**; if accepted, add it to the RAG plan as a Phase 2 item.\n","20261020_130829_openrouter_support_plan.md":"# OpenRouter as the single access point for the nuggetization LLMs — plan\n\n**Generated:** 2026-10-20 13:08:29 (local time, from `date +%Y%m%d_%H%M%S`).\n**Status:** **implemented and probed on 2026-10-21 (§8)**; `--route openrouter` is the default.\nDecisions registered on 2026-10-20: §7 (all models, flex, no parity check now, $150 prepaid).\n**Context:** phase 2 of the nuggetization is next (`docs/20261013_103834_nuggetization_open_decisions.md` §4).\nThe user now has an OpenRouter account and can create an API key. This note looks at the current client and\nplans how to send all LLM calls through OpenRouter.\n\n## 1. Current implementation (what must keep working)\n\n| Piece | Where | What it does today |\n|---|---|---|\n| Provider-neutral client | `scripts/llm_client/client.py` | `LLM.complete_json()` with three providers: `openai` (Responses API, strict JSON schema, `reasoning.effort`), `gemini` (REST `generateContent`, `responseJsonSchema`, `thinkingLevel`), `openai_compat` (Chat Completions on DashScope Singapore for Qwen, `json_object` + pydantic + retry, `enable_thinking` + `thinking_budget: 2048`) |\n| Disk cache | same | key = sha256 of (provider, model id, params, system, user, schema[, replicate]); one cache per `--out` |\n| Cost ledger + cap | same | `costs.csv`: one row per call, `usd_standard` computed from the `models.yaml` prices; `--budget` checked before each call against `ledger_total()` (batch rows at `BATCH_DISCOUNT` = 0.5) |\n| Errors | same | retries on 408/429/5xx; `QuotaExhausted` on a per-day 429 (Gemini 3.1 Pro: 250 requests/day) |\n| Batch | `scripts/llm_client/batch.py` | OpenAI Batch (`/v1/responses`) and Gemini `batchGenerateContent`; jobs fill the same cache; Qwen stays synchronous |\n| Registry | `scripts/nuggets/models.yaml` | 4 models: `gpt-6.1-sol`, `gemini-3.1-pro`, `gemini-3.8-flash`, `qwen3.8-max` (snapshot `qwen3.8-max-0902`); one `api_key_env` each |\n| Caller | `scripts/nuggets/nuggets.py` | `llm(name, out, budget)` builds an `LLM` from the registry; the logical model **name** goes into folder names (`create/<model>/`), set names, the ledger and the manifests |\n\nThree keys are needed today (`OPENAI_API_KEY`, `GEMINI_API_KEY`, `DASHSCOPE_API_KEY`). The `.env` on this\nmachine only has `GEMINI_API_KEY` (and `HF_TOKEN`), so this machine cannot run the OpenAI or Qwen roles.\nWith one OpenRouter key, both machines can run every role.\n\n## 2. What OpenRouter offers (checked 2026-10-20)\n\nSources: the public catalog `GET https://openrouter.ai/api/v1/models` and `/models/<id>/endpoints` (no key\nneeded), and the docs pages API overview, reasoning tokens, provider routing, FAQ and Batch quickstart.\n\n**All four models are listed, with the same upstream providers and list prices as in `models.yaml`:**\n\n| Our name | OpenRouter id | Upstream endpoints (USD per 1M in / out / cached in) | `:batch` variant |\n|---|---|---|---|\n| `gpt-6.1-sol` | `openai/gpt-6.1-sol` | `openai` 2.00 / 10.00 / 0.10; **`openai/flex` 1.00 / 5.00 / 0.05**; Azure, Bedrock (+10 %); `fast`/`ultrafast` (×2, ×6) | yes, 1.00 / 5.00 |\n| `gemini-3.1-pro` | `google/gemini-3.1-pro-preview` | `google-ai-studio` and `google-vertex/global` 2.00 / 12.00 / 0.20; **`google-ai-studio/flex` 1.00 / 6.00 / 0.10**; `priority` (×1.8) | yes, 1.00 / 6.00 |\n| `gemini-3.8-flash` | `google/gemini-3.8-flash` | `google-ai-studio`, `google-vertex/global` 0.75 / 3.75 / 0.075; **`google-ai-studio/flex` 0.375 / 1.875**; `vertex/us` +10 %; `priority` ×1.8 | yes, 0.375 / 1.875 |\n| `qwen3.8-max` | `qwen/qwen3.8-max-0902` (the pinned snapshot) | `alibaba`, `alibaba/us-east-1` 2.00 / 6.00 / **0.25** (we assumed 0.20) | **no** |\n\n- **API:** OpenAI-compatible Chat Completions at `https://openrouter.ai/api/v1` (the `openai` SDK we already\n use works with `base_url`). A Responses endpoint exists too (`/v1/responses`, listed by the Batch API).\n- **Structured outputs:** `response_format: {type: json_schema, json_schema: {..., strict: true}}`. All four\n models list `structured_outputs`.\n- **Reasoning:** one `reasoning` object: `effort` (`minimal`…`xhigh`) **or** `max_tokens`. Gemini 3:\n `effort` maps directly to `thinkingLevel`. Qwen: \"some Qwen thinking models\" map `max_tokens` to\n `thinking_budget`. **The default effort of `qwen3.8-max-0902` is `xhigh`.** If it is not set explicitly,\n Qwen would reason far longer than in the pilot (D12 says medium).\n- **Usage:** every response has `usage` with `cost` (the billed credits), `cost_details`,\n `prompt_tokens_details.cached_tokens`, `completion_tokens_details.reasoning_tokens`. Token counts use the\n model's native tokenizer. `GET /api/v1/generation?id=` returns the stats of a past call.\n- **Provider routing:** `provider: {only, order, allow_fallbacks, require_parameters, data_collection, zdr,\n ...}`. By default OpenRouter picks the cheapest provider and **falls back** to another one on errors. For\n reproducibility we must pin it.\n- **Fees:** no markup on inference prices. Buying credits costs **5.5 %** (min $0.80) by card, or 5 % in crypto.\n- **Rate limits:** calls use OpenRouter's upstream accounts, so **our Gemini 3.1 Pro quota of 250\n requests/day does not apply**. This holds unless we attach our own Gemini key (BYOK), which we should not do.\n- **Batch API (beta, launched 2026-09):** `POST /api/v1/batches` with an inline `requests` array (no file\n upload), **one model and one endpoint per batch**, results returned inline in `GET /batches/:id`, about\n 50 % off, 24 h window (Vertex up to 96 h, AI Studio expires at 48 h). On Google models every request in a\n batch must use the same `response_format`. Usage is documented at batch level only (per-result usage is not\n documented). Inputs and results are deleted after 30 days.\n- **Flex endpoints** (`openai/flex`, `google-ai-studio/flex`): **synchronous calls at half price**, probably\n slower and with more \"capacity\" errors. They give the batch discount without job handling.\n- Also in the catalog: DeepSeek (RAG generator, D1) and several open-weight Qwen models (D2/D4 judge\n candidate). Maritaca Sabiá is **not** listed.\n\n## 3. Cost for phase 1–4 (measured part, pilot note §10.1)\n\nThe measured part of the estimate is ≈ $61. That is ≈ $39 for the roles priced with Batch (GPT and Gemini)\nplus ≈ $22 for Qwen (synchronous).\n\n| Route | Estimate | Note |\n|---|---:|---|\n| Direct APIs (current: Batch for GPT/Gemini, Qwen sync) | ≈ $61 | three keys; Gemini Pro needs Batch because of the daily quota |\n| OpenRouter, standard synchronous endpoints | ≈ $100 + 5.5 % ≈ **$106** | loses the 50 % discount on ≈ $39 of calls |\n| OpenRouter, `flex` or `:batch` for GPT and Gemini | ≈ $61 + 5.5 % ≈ **$65** | +$3–4 credit fee; same prices otherwise |\n\nThe open-weight Qwen judge ($10–25, not measured) is outside these numbers. **OpenRouter only pays off if the\nGPT and Gemini roles use `flex` or `:batch`.**\n\n## 4. Design\n\n### 4.1 Registry: one logical model, two routes\n\nKeep the logical names (`gpt-6.1-sol`, …). Folder names, set names, manifests and the analysis code use them,\nand phase 2 outputs must stay comparable with the pilot. Add an `openrouter` block per model:\n\n```yaml\n gpt-6.1-sol:\n provider: openai # direct route, unchanged\n ...\n openrouter:\n model_id: openai/gpt-6.1-sol\n params: {reasoning: {effort: medium}, max_tokens: 32000, response_format: json_schema}\n routing: {only: [openai], allow_fallbacks: false, require_parameters: true, data_collection: deny}\n tier: flex # standard | flex | batch (see §4.4)\n qwen3.8-max:\n ...\n openrouter:\n model_id: qwen/qwen3.8-max-0902\n params: {reasoning: {max_tokens: 2048}, max_tokens: 16000, response_format: json_object} # §5 probe\n routing: {only: [alibaba], allow_fallbacks: false, require_parameters: true}\n```\n\n- A global `--route direct|openrouter` in `nuggets.py`, default `direct` until the parity check (§5 step 3)\n passes. The default then moves to `openrouter`. `llm()` merges the route block over the model entry.\n- `api_key_env: OPENROUTER_API_KEY` for the whole route (one key in `.env`).\n- `require_parameters: true` + `allow_fallbacks: false`: a request is never served by a provider that would\n ignore `reasoning` or the schema, or by another vendor (Azure/Bedrock). That is what makes \"same model,\n same settings\" true for the paper.\n- Prices stay in the registry (for `usd_standard` and the batch estimate); add the OpenRouter-specific\n values (Qwen cached input 0.25) to the route block.\n\n### 4.2 Client: provider `openrouter` in `client.py`\n\n- `openrouter_body()` / `parse_openrouter()` next to the existing builders, so a future batch backend can\n share them (the same pattern as `openai_body` / `parse_openai`).\n- Call through the existing `openai` SDK: `OpenAI(base_url=\"https://openrouter.ai/api/v1\")`,\n `chat.completions.create(..., extra_body={\"reasoning\": ..., \"provider\": ...})`. Optional attribution\n headers `X-Title` / `HTTP-Referer`. No new dependency.\n- **Chat Completions for all four models.** The pilot sent GPT through the Responses API. Through\n OpenRouter, the request shape is different, but the model, effort and schema are the same; the parity check\n (§5) verifies this. Use `/v1/responses` for GPT only if parity fails.\n- **Cache key:** `provider` becomes `openrouter`, and the routed `model_id` and params are new. So OpenRouter\n calls never mix with the direct-API cache entries. This is intended, but it means **pilot caches cannot\n serve OpenRouter calls**. Record the route in the key itself, not only in the manifest.\n- **Usage → `Usage`:** `prompt_tokens`, `cached_tokens`, `completion_tokens` (reasoning included),\n `reasoning_tokens`. Also keep `usage.cost` (billed) and the served `provider` and `model` from the response.\n- **Errors:** 402 (out of credits) → a new fatal `CreditsExhausted`, never retried. 429 → backoff as today. An\n upstream error can arrive as HTTP 200 with an `error` object or `finish_reason: \"error\"` → treat it as a\n retryable failure, not as a reply. `finish_reason: \"length\"` (reasoning ate the budget) → truncated, as today.\n `QuotaExhausted` stays for the direct Gemini route.\n\n### 4.3 Ledger and budget\n\n- New columns in `costs.csv`: `route`, `provider_served`, `usd_billed`. `usd_billed` is OpenRouter's\n `usage.cost` (actual charge, flex/batch discounts included). `usd_standard` stays the registry list price,\n so reports can still compare.\n- `ledger_total()`: use `usd_billed` when the row has it, else the current rule (`usd_standard`, batch rows\n at half). The 5.5 % credit fee is not per call. Report it once in the cost notes for the paper.\n- **Header compatibility:** `_log` appends with `DictWriter` without checking the header. Adding columns to an\n existing `costs.csv` would misalign rows. Phase 2 uses a new `--out`, but the code must still compare the\n header and refuse (or rewrite the file with the new columns) instead of appending blindly.\n- `report.py` and `pilot_report.py` sum `usd_standard`; switch them to the billed value, with the same rule.\n- **Second safety net:** create the OpenRouter key with a **spending limit** (set in the OpenRouter\n dashboard), slightly above the phase budget. `--budget` stays the primary cap, and the key limit catches a\n runaway loop or a leaked key. Optionally, `GET /api/v1/key` before a run prints the remaining limit.\n\n### 4.4 Discounted tier: `flex` first, OpenRouter Batch second\n\n1. **`flex` (recommended if the probe passes):** synchronous calls with `provider.only:\n [\"openai/flex\"]` / `[\"google-ai-studio/flex\"]` (to be confirmed: whether `only` accepts the tagged slug).\n No job submission, no `batch wait`, no rerun. The existing threaded runner, retries, cache and budget\n checks work as they are. Concurrency and latency must be measured (§5 step 2). Lower `--workers` if flex\n throws capacity errors.\n2. **OpenRouter Batch (fallback):** a third backend in `batch.py`. One job per model **and per schema** (Google\n requires one `response_format` per batch). Requests inline (body size limits to check for ≈ 715 × 6k\n tokens). Results are read from `GET /batches/:id`. Because per-result usage is not documented, cost per row\n may need `/generation?id=` lookups or a split of the batch-level `usage.cost`. More code, and still beta.\n3. Qwen has no `:batch` and no `flex` variant: it stays synchronous at list price, as today.\n\nThe direct route and its `batch.py` backends stay in the code. They are the fallback if OpenRouter is down or\nchanges a model, and the pilot was produced with them.\n\n## 5. Steps\n\n| # | Step | Cost | Output |\n|---|---|---:|---|\n| 0 | User creates the key (spending limit ≈ phase budget + margin), adds `OPENROUTER_API_KEY` to `.env` on both machines, buys credits | fee 5.5 % | — |\n| 1 | **Probes** (a throwaway script, not the pipeline): one `create_v4` call per model on a `preview_10` question, standard and flex. Check: strict schema accepted (and Qwen `json_schema` vs `json_object` again); `reasoning` honoured (reasoning tokens close to the pilot's: GPT ≈ 140 per creation call, Gemini/Qwen from `costs.csv`); **Qwen `reasoning.max_tokens: 2048` maps to `thinking_budget`**, else pick the `effort` with the closest token count; served provider and model in the response; `usage.cost` = registry price × tokens; `only` with `/flex` tags | < $0.50 | probe note |\n| 2 | Implement §4.1–§4.3 (+ flex). Add the **`fake` provider and unit tests** still missing from the phase 0 gate (README \"what is still missing\" item 3): mocked OpenRouter replies, including the 200-with-error, 402 and `length` cases | 0 | code, tests |\n| 3 | **Deferred (§7, decision 3).** *Parity check:* `create` + `validate` + `selfscore` (Flash) on `preview_10` in a new `--out nuggets/parity_openrouter`, all three families via OpenRouter, `--budget 2`. Compare with `nuggets/pilot/` on the same 10 questions: hard errors, nugget counts, reasoning tokens, self-score, and Flash alignment against the pilot sets (the same-model noise of pilot note §3 is the reference) | ≈ $1–1.5 (flex) | parity note; route default switched if it passes |\n| 4 | Gemini 3.1 Pro over a full day of calls is no longer blocked by the 250/day quota: confirm on step 3's calls that no quota error comes back | 0 | — |\n| 5 | Phase 2 through OpenRouter, `--budget` on every run, as planned in the open-decisions note §4 | ≈ $65 (§3) | phase 2 |\n| 6 | Docs: `scripts/nuggets/README.md` (keys, `--route`, flex), `CLAUDE.md` pointer, open-decisions note, paper methods (route, served providers, fee) | 0 | — |\n\nStop and report to the user if step 1 shows a mismatch in prices or reasoning tokens, or if flex is not usable.\n\n## 6. Risks and how the plan handles them\n\n| Risk | Handling |\n|---|---|\n| Silent fallback to another provider (Azure, Bedrock, Vertex vs AI Studio) | `only` + `allow_fallbacks: false`; log `provider_served` per call; a mismatch is an error |\n| Parameters silently dropped | `require_parameters: true`; check reasoning tokens in the probe and in the reports |\n| Qwen default effort `xhigh` | explicit `reasoning` in the registry; probe step 1 |\n| Upstream errors returned as 200 | parsed as failures (§4.2), tested with the fake provider |\n| Pilot vs phase 2 run on different routes (paper) | parity check (step 3); every manifest records the route; both stated in the methods |\n| Flex: slow or \"no capacity\" | lower `--workers`; fall back to OpenRouter Batch or to the direct Batch API for that model |\n| OpenRouter Batch is beta, docs incomplete (per-result usage) | used only if flex fails |\n| Data handling: one more party sees the prompts | the gold answers are public (BR-TaxQA-R); `data_collection: deny` costs nothing, so set it |\n| Credit fee 5.5 % | ≈ $3–4 for phases 1–4; reported once |\n| Cache backup to HF (open decision §2.2) | unchanged: caches are local per `--out`, whatever the route |\n\n## 7. Decisions (user, 2026-10-20)\n\n| # | Question | Decision |\n|---|---|---|\n| 1 | Scope | **All four models through OpenRouter.** The direct route stays in the code as a fallback |\n| 2 | Discounted tier for GPT and Gemini | **`flex`** (§4.4 option 1), after the step 1 probe. OpenRouter Batch only if flex is not usable |\n| 3 | Parity check on `preview_10` before phase 2 | **Not now.** Step 3 is deferred (see below) |\n| 4 | Credits and key | **USD 150 already prepaid**, so no new credit purchase or fee for phases 1–4 (§3). The key is still to be created (step 0 below) |\n| 5 | Open-weight Qwen judge, RAG generators | **To discuss later.** The user will probably prefer an **HF endpoint**, as for the embeddings, over OpenRouter for the open Qwen judge |\n\n**Consequences for §5:**\n- **Step 0:** create the key in the OpenRouter dashboard (Settings → API Keys,\n `https://openrouter.ai/settings/keys`), with a credit limit. Suggested limit: ≈ **$80** (phase 1–4\n estimate ≈ $61 at flex prices, plus probes and margin), below the $150 balance, so a runaway run cannot spend\n all of it. Add it to the **`.env` at the repository root** (gitignored, read by `python-dotenv` in\n `nuggets.py`) on **both machines**, as one line: `OPENROUTER_API_KEY=sk-or-v1-...`. No shell export is needed.\n The other keys (`OPENAI_API_KEY`, `GEMINI_API_KEY`, `DASHSCOPE_API_KEY`) can stay for the direct route.\n- **Step 3 (parity check) deferred.** The step 1 probes still check the settings (schema, reasoning tokens,\n served provider, prices) before phase 2. The pilot-vs-OpenRouter comparison then comes **at no extra cost\n from phase 2 itself**: phase 2 creates nugget sets for all 715 questions, `stratified_30` included, so the\n 30 pilot questions can be compared afterwards (nugget counts, reasoning tokens, self-score, Flash alignment\n against the pilot sets). This comparison goes in the phase 2 note.\n- **Route default:** without the parity step, `--route openrouter` becomes the default once step 1 (probes)\n and step 2 (code and tests) are done.\n- §3's 5.5 % fee row: already paid on the prepaid credits; it is a cost of the work, but not an extra charge\n in phase 2.\n\n## 8. Implementation and probe results (2026-10-21)\n\n### 8.1 What was implemented\n\n| Plan item | Where | Note |\n|---|---|---|\n| §4.1 registry routes | `scripts/nuggets/models.yaml` (`openrouter:` per model), `client.route_config()` | as planned; `served_provider` added (display name checked on every reply) |\n| `--route` | `nuggets.py` (global option, default **`openrouter`**) | manifests record the route and the resolved registry entry; `batch status/collect/wait` always use the direct route; `--batch` with `--route openrouter` is refused |\n| §4.2 provider | `client.py`: `openrouter_body()`, `parse_openrouter()`, `_call_openrouter()` | `httpx`, not the `openai` SDK (the raw reply keeps `provider` and `usage.cost`); `routing` enters the cache key **only** on this route, so direct-route keys are unchanged |\n| §4.2 errors | `CreditsExhausted` (402, never retried), error in a 200 reply → retried as 502, `RouteMismatch` (logged, not cached, fatal) | |\n| §4.3 ledger | `LEDGER_FIELDS` + `route`, `provider_served`, `usd_billed`; `row_billed()` used by `ledger_total()`, `report.py`, `pilot_report.py` | an older `costs.csv` is rewritten with the new (empty) columns on its first new row |\n| key check | `nuggets.py openrouter-key` | limit, usage, expiry |\n| tests | `scripts/llm_client/tests/test_openrouter.py` (13 tests, mocked HTTP) | the fake provider of the phase 0 gate is still not done |\n| §5 step 1 probe | `scripts/nuggets/probe_openrouter.py`, output `nuggets/probe_openrouter/` | |\n| docs | `scripts/nuggets/README.md` (\"OpenRouter route\"), `CLAUDE.md` | |\n\nThis machine's `.venv` had no nugget requirements; they were installed with `uv pip install --python\n.venv/bin/python -r scripts/nuggets/requirements.txt` (pinned versions).\n\n**Key:** limit $80, **expires 2026-11-20** (renew before phase 2 ends).\n\n### 8.2 Probe: `create_v4`, first 3 questions of `preview_10` (503, 023, 039), 18 calls, **$0.125 billed**\n\nThe key's usage on OpenRouter ($0.12503) matched the ledger, after a short lag.\n\n| Variant | Valid replies | Served by | Reasoning tokens (pilot, same questions) | Billed / list |\n|---|---|---|---|---|\n| `gpt-6.1-sol` (flex) | 3/3, 2 nuggets each (pilot 2) | OpenAI | 91, 0, 0 (0, 0, 0) | 0.50 on calls 2–3; 0.60 on the first, see below |\n| `gemini-3.1-pro` (flex) | 3/3, 2 each (pilot 2) | Google AI Studio | 933, 1067, 582 (872, 664, 527) | 0.50 |\n| `gemini-3.8-flash` (flex) | 3/3, 2 each | Google AI Studio | 798, 581, 535 (no pilot creation) | 0.50 |\n| `qwen3.8-max` (`reasoning.max_tokens: 2048`) | 3/3, 2 each (pilot 2) | Alibaba | 751, 461, 454 (791, 940, 541) | 1.00 (list, cached at $0.25 ✓) |\n| `qwen3.8-max`, `effort: medium` | 3/3 | Alibaba | 930, 877, 505 | 1.00 |\n| `qwen3.8-max`, strict `json_schema` | 3/3 (one with 3 nuggets) | Alibaba | 489, 889, 608 | 1.00 |\n\nFindings:\n- **Pinning works:** `only` with the tagged slugs `openai/flex` and `google-ai-studio/flex` is accepted, with\n `data_collection: deny` and `require_parameters: true`; every reply came from the pinned provider.\n- **Flex is half price**, as listed. Latency: GPT ≈ 10 s, Gemini 7–10 s, Qwen 15–30 s, about the pilot's.\n No capacity errors at this size; watch for them at phase 2 concurrency.\n- **The first GPT call costs 1.25× input on the cached prefix**: OpenRouter reports `cache_write_tokens: 3525`,\n billed at 1.25 × the flex input price. The next calls read the cached prefix at $0.05/M. It is\n a one-time cost per prefix (≈ $0.001), and it is included in `usd_billed`. `usd_standard` (list price)\n does not model cache writes.\n- **Gemini 3.1 Pro had no cached input** (as on the direct route).\n- **Reasoning effort matches the pilot's (D12):** the Gemini and GPT tokens are within the pilot's per-call\n spread. Qwen with `reasoning.max_tokens: 2048` stays below 2,048 and in the pilot's range, so the pilot setting\n (`thinking_budget: 2048`) is kept. `effort: medium` gives similar counts. Whether OpenRouter passes\n `max_tokens` as `thinking_budget` cannot be seen in the reply; both settings stay well under the budget.\n- **Qwen strict `json_schema` worked 3/3** here (it returned malformed JSON on the direct API in the preview).\n `json_object` + pydantic + retry is kept, so phase 2 runs Qwen as the pilot did.\n- No 429 and no quota error on Gemini 3.1 Pro.\n\n**Next:** phase 2 with `--route openrouter` (the default), `--budget` on every run. The pilot comparison on the\n30 `stratified_30` questions goes in the phase 2 note (§7, decision 3).\n","20261021_113527_nuggetization_status_after_pilot_and_next_steps.md":"# Nuggetization — status after the phase 1 pilot and next steps\n\n**Generated:** 2026-10-21 11:35:27 (local time, from `date +%Y%m%d_%H%M%S`).\n**Purpose:** a record of where the nuggetization stands before phase 2, and what is left to finish it.\n**Sources:** plan v2 (`docs/20261011_224049_gold_answer_nuggetization_plan_v2.md`), the pilot note\n(`docs/20261012_192640_nuggetization_phase1_pilot.md`), the open-decisions note\n(`docs/20261013_103834_nuggetization_open_decisions.md`), the OpenRouter plan\n(`docs/20261020_130829_openrouter_support_plan.md`) and `scripts/nuggets/README.md`.\n\n## 1. Done\n\n**Preview (10 questions, $2.63 billed).**\n- Creation prompt settled: `create_v2` rejected (GPT over-split illustrative lists), `create_v3` → `create_v4`\n (pointer rule: a sentence that only says \"see question N\" gives no nugget).\n- Scoring prompt settled: `assign_v2` (a missing exercício 2024 / ano-calendário 2023 is not a defect).\n\n**Phase 1 pilot (`stratified_30`, $8.29 billed, `nuggets/pilot/`).** Every phase 1 item of plan v2 §4 was run:\n- creation by three families (`gpt-6.1-sol`, `gemini-3.1-pro`, `qwen3.8-max`), two GPT replicates\n (same-model noise), and the 2-call mode (importance in a second call);\n- cross-family alignment, round trip, two auditors (3.1 Pro, Qwen) with repair, a planted-error test of the\n auditors, gold self-score;\n- known-answer tests of the judge (Flash and 3.1 Pro).\n\n**Decisions closed** (open-decisions note §1):\n- `create_v4`, **one call** (nuggets and `vital`/`okay` labels in the same response);\n- gate thresholds: 0 hard errors; gold self-score ≥ 98 %; ≤ 2 % of nuggets flagged by both auditors (on\n any check) after repair; judge sensitivity ≥ 0.90 on value/year/verdict corruptions; each auditor catches\n ≥ 80 % of planted errors. The pilot passed all of them;\n- `answer_cleaned` content loss fixed in the v2.0 build (47 answers);\n- judge: Gemini Flash, not 3.1 Pro;\n- all LLM calls through **OpenRouter** (flex endpoints for GPT/Gemini, no 250/day quota on 3.1 Pro).\n Implemented and probed on 2026-10-21 ($0.125); default route.\n\n## 2. Next steps\n\n1. **Phase 2 — full creation:** the three families on the 715 questions, `--route openrouter`, then\n `validate`. Gate: 0 hard validation errors. The 30 pilot questions inside the full run give the\n pilot-vs-OpenRouter comparison for free. Gaps:\n - `sample` only builds `preview_10` and `stratified_30`; a full-set sample is needed;\n - questions 001 and 003 are the prompt's worked examples: nuggetize them and flag them, or exclude them.\n2. **Phase 3 — automatic robustness:** alignment, two auditors + repair, round trip, gold self-score (Flash on\n the three sets, 3.1 Pro on the primary). The freeze gate gives `v0-auto`.\n3. **Phase 4 — judge selection:** known-answer tests on the full set, after the builder fixes (W without\n near-duplicate sources; D/C dropping tests whose fact is restated; V with a real other-period value).\n Optional: the open-weight Qwen judge on an HF endpoint (≈ $10–25).\n4. **Phase 5 — scoring** of the RAG answer grid with both nugget sets, and robustness of the conclusions\n (needs RAG generation runs; Flash ≈ $1.2–1.3 per answer run and nugget set). Open: the \"expanded\" score\n on `has_pointer` questions.\n5. **Phase 6 — release:** HF `nuggets` config, reports, raw responses. The cache push to the private HF repo\n needs the user's go-ahead.\n\n## 3. Budget\n\nPilot-based estimate for phases 1–4: ≈ $71–86 (≈ $56–102 with margin), of which $10–25 is the optional HF\nendpoint. The OpenRouter part is close to the key's **$80 limit**; the key **expires 2026-11-20**. Pass\n`--budget` on every step and check the key's usage between steps.\n","20261021_155704_nuggetization_phases_2_to_4_execution.md":"# Nuggetization phases 2–4 — execution on the 715 questions\n\n**Generated:** 2026-10-21 15:57:04 (local time, from `date +%Y%m%d_%H%M%S`).\n**Implements:** plan v2 §4 phases 2, 3 and 4 (`docs/20261011_224049_gold_answer_nuggetization_plan_v2.md`),\nwith the decisions of `docs/20261013_103834_nuggetization_open_decisions.md` (`create_v4`, one call, gate\nthresholds, OpenRouter). Starting point: `docs/20261021_113527_nuggetization_status_after_pilot_and_next_steps.md`.\n**Left out, as asked:** the open-weight Qwen judge (plan v2 D4).\n**Outputs:** `nuggets/full/` (all sets, audits, alignments, round trip, self-scores, known-answer tests;\n`report_full.md` has every table; `costs.csv` is the ledger; `logs/` holds the command logs and scripts),\n`nuggets/gold/v0-auto/` (**the frozen nugget set**), `nuggets/parity_openrouter/` (pilot vs OpenRouter, §3).\n**Route:** OpenRouter for every call (flex endpoints for GPT and Gemini, Alibaba for Qwen); every reply came\nfrom the pinned provider (`provider_served`: OpenAI, Google AI Studio, Alibaba). No 429 and no quota error.\n\n## 1. Cost and time\n\n### 1.1 Totals\n\n| | Calls | Billed | List price (direct API, synchronous) | Wall-clock |\n|---|---:|---:|---:|---|\n| **Nugget generation (phase 2 creation, 3 families × 715)** | 2,148 | **$23.06** | $36.70 | **58 min** (11:38–12:36 UTC) |\n| **Phases 2–4, everything** (`nuggets/full/costs.csv`) | 12,564 | **$65.34** | $103.67 | **4 h 15 min** (11:38–15:53 UTC) |\n| Pilot vs OpenRouter comparison (`nuggets/parity_openrouter/`) | 90 | $0.15 | | 3 min |\n\n- Creation per family, 8 concurrent calls per model: `gpt-6.1-sol` 23 min ($3.20), `gemini-3.1-pro` 23 min\n ($10.54), `qwen3.8-max` 58 min ($9.32). Qwen set the wall-clock time; it is also the slowest per call (≈ 20–45 s).\n- During the 4 h 15 min of phases 2–4, some API call was in flight for 4 h 10 min: the checks between steps\n overlapped with steps already running (e.g. the round trip started while Qwen was still creating). The summed\n latency of all calls is 49.5 h (12.9 h for creation), the time a single sequential worker would have needed.\n- OpenRouter key: usage $65.61 = this run + the comparison + the 2026-10-21 probe ($0.125); **$14.39 left** of\n the $80 limit (expires 2026-11-20).\n- **Running total of the nuggetization (billed):** preview $2.63 + pilot $8.29 + batch test $0.035 + OpenRouter\n probe $0.125 + phases 2–4 $65.34 + comparison $0.15 = **$76.57**.\n- Estimate before the run (status note §3; pilot per-call costs × 715 at flex prices): ≈ $61 for the same steps\n (≈ $70 with the full 3.1 Pro self-score, not run, §6). Actual $65.34 (+7 %). The overshoot: the Qwen audit\n (+$1.2), the two re-audit rounds ($2.6, not in the estimate) and the planted test (+$0.4).\n\n### 1.2 Per step (ledger)\n\n| Phase | Step | Calls | Retries | Billed | Wall-clock |\n|---|---|---:|---:|---:|---:|\n| 2 | Creation, 3 families (`create_v4`) | 2,148 | 3 | $23.06 | 58 min |\n| 2 | Repair of hard validator errors, each family by itself (§2.2) | 21 | 0 | $0.80 | 7 min |\n| 3 | Round trip (Flash writer, Qwen checker), raw and `rep0` primary | 1,432 | 0 | $5.74 | 40 min |\n| 3 | Cross-family alignment, 3 pairs (Flash) | 2,118 | 0 | $3.66 | 14 min |\n| 3 | Gold self-score, Flash (4 sets) | 2,138 | 0 | $3.82 | 120 min (in parallel with others) |\n| 3 | Two auditors on the primary set (3.1 Pro, Qwen) | 1,446 | 14 | $15.45 | 75 min |\n| 3 | Repair round 1 + re-audit | 42 + 85 | 2 | $2.42 | 24 min |\n| 3 | Repair round 2 + re-audit | 10 + 17 | 2 | $0.73 | 19 min |\n| 3 | Planted-error auditor test (`stratified_70`) | 141 | 1 | $1.76 | 9 min |\n| 4 | Known-answer tests: Flash on all, 3.1 Pro on `stratified_70` | 2,966 | 3 | $7.89 | 50 min |\n\nRetries are reply rejections (truncated or invalid JSON) retried by the client; the 14 audit retries include\nthree truncated Qwen replies on Q442 (§2.4).\n\n## 2. What was run\n\nAll commands are in `nuggets/full/logs/*.sh` and in §2.6; global options `--out nuggets/full --sample all\n--budget <cap> --workers 8`. The cap is cumulative per ledger; it was raised step by step (32 → 75), never hit.\n\n### 2.1 Samples (`sample --keep-from nuggets/pilot/sample.json`)\n\nThe 47 answer fixes of the v2.0 build (pilot note §13.1) changed some answer lengths, so recomputing the deciles\ntoday gives other `preview_10` / `stratified_30` lists. Both are kept **verbatim from the pilot**\n(`stratified_30` is also the RAG pilot sample). New lists: `all` (715) and `stratified_70` = `stratified_30` + 4\nmore per current decile (the 10 % subset of plan v2 §5.7). Questions 001 and 003, the prompt's worked\nexamples, are in `all`: they need nuggets for scoring, and the validator flags them (`prompt_example`).\n\n### 2.2 Phase 2: creation and validation\n\n| Set | Nuggets | Per question | Vital | Hard errors: raw → after validator repair (`rep0`) |\n|---|---:|---|---:|---|\n| `gpt-6.1-sol` (primary) | 3,185 | 4.5 (1–115) | 72 % | 5 → 3 |\n| `gemini-3.1-pro` | 2,888 | 4.0 (1–33) | 77 % | 60 → 3 |\n| `qwen3.8-max` | 3,001 | 4.2 (1–80) | 72 % | 42 → 21 (18 in Q442) |\n\n**Validator fixes** (false positives found in the first full validation; with them, the raw sets' hard errors\nwent from 18 / 76 / 57 to the 5 / 60 / 42 of the table):\n- **verdict check:** a verdict is \"Sim\"/\"Não\" followed by punctuation (174 answers). \"Não havendo acordo…\" (Q131) and\n \"Não se caracterizam…\" (Q255) open a sentence and are not verdicts; all three families were flagged on them;\n- **R10:** the lettered items of the worked numerical examples Q617 and Q620 give no nugget (plan v2 R10):\n `enum_item_worked_example`, a warning;\n- **pointer answers:** Q316 only delegates to Q249 plus an Atenção note, so no vital nugget is expected:\n `no_vital_pointer`, a warning.\n\nThe remaining hard errors (omitted enumerated items, one duplicate, two unmatched spans) went back to **each\nset's own creator** in one repair call per question (`repair` without auditors, `repair_v1`): the plan's rule\nthat hard validator errors go to repair, applied before the auditors so the three sets enter phase 3 clean.\nThe `.rep0` sets are the phase 2 output.\n\n**Phase 2 gate (0 hard errors): not fully met.** Left in the primary set: three enumerated items in Q149, Q326\nand Q442 that GPT kept uncovered through all three repair calls. Two are headings (\"II – Fundos Controlados\npelos Conselhos … da Pessoa Idosa;\", whose content the next nuggets carry) or sub-items restated by another\nnugget, so they are validator false positives or borderline. Q149 item 2 (\"Funcionário residente …\") is\npartly covered by N04. They are listed here and in `create/gpt-6.1-sol.rep2/validation.json`. The alternative\nsets keep 3 (Gemini) and 21 (Qwen) errors; they are used only for agreement.\n\n### 2.3 Pilot vs OpenRouter (open-decisions note decision 6, OpenRouter plan §7 decision 3)\n\nThe 30 `stratified_30` questions of the phase 2 sets against the pilot's direct-route sets, aligned by Flash\n(`nuggets/parity_openrouter/`):\n\n| Family | Matched | `same` | Importance agreement | Conflicts | Reasoning tokens per call (direct → OpenRouter) |\n|---|---:|---:|---:|---:|---|\n| `gpt-6.1-sol` | 100 % | 94 % | 97 % | 0 | 98 → 93 |\n| `gemini-3.1-pro` | 99 % | 82 % | 90 % | 0 | 1,316 → 1,244 |\n| `qwen3.8-max` | 100 % | 86 % | 90 % | 0 | 1,052 → 1,197 |\n\nGPT is within the pilot's same-model noise (replicates: 94–99 % `same`, 94–95 % importance). Gemini and Qwen\nhave no same-model reference, but they are above the cross-family level of the pilot (75–81 % `same`). Nugget\ncounts per set: 135/133, 122/118, 123/123. **The route does not change the nuggets beyond sampling noise.**\n\n### 2.4 Phase 3: automatic robustness\n\n**Cross-family agreement** (`rep0` sets; report §3): 95 % of the primary nuggets are matched by both other\nfamilies (3/3), 4 % by one; strict (`same` only) 68 %. Vital nuggets 97 % 3/3, okay 90 %; `resposta_direta` 100 %.\nImportance identical in all three families for 81 % of the 3/3 nuggets matched one to one. One `conflict`\nrelation in each of two pairs.\n\n**Round trip** (Flash rewrites from the nugget texts, Qwen checks with `roundtrip_check_v2`): 69 findings in 49\nquestions (23 missing, 46 altered), passed to the auditors as omission candidates (71 candidates in total with\nthe alignment's).\n\n**Two auditors** (`audit_v1`, C1–C6) and **two repair rounds** (the plan's maximum):\n\n| Set | 3.1 Pro flags | Qwen flags | Flagged by both (any check) | Questions repaired next |\n|---|---:|---:|---:|---|\n| `gpt-6.1-sol.rep0` | 2.8 % | 4.1 % | **41 (1.3 %, CI 0.7–2.1 %)** | 44 (65 agreed issues) |\n| `gpt-6.1-sol.rep1` | 1.9 % | 3.0 % | 8 (0.3 %) | 13 (16 issues) |\n| `gpt-6.1-sol.rep2` | 1.7 % | 2.6 % | **1 (0.03 %)** | — |\n\nThe 1.3 % before repair is the model-based error estimate of plan v2 §3.5.3 (\"flagged by two independent LLM\nauditors\"). Round 1 also created four new uncovered items (merging redundant nuggets removed spans); round 2\nfixed them. The one nugget still flagged by both, Q356_N02, is the R6 citation slip seen in the pilot (\"a\nsolução de consulta indicada na fundamentação legal\" instead of the Solução de Consulta Cosit nº 354): 3.1 Pro\nflags C1, Qwen C2.\n\nQwen's audit of Q442 (115 nuggets) was truncated at 16k output tokens three times; `audit` now retries a\ntruncated reply once with twice the output limit (`longer()`), which enters only that call's cache key.\n\n**Planted errors** (`plant` on `stratified_70`, one damaged nugget per question; addition 20, importance 13,\npolarity 10, condition 10, merge 7, quantifier 7, value 3; the addition is no longer planted on a nugget that\nalready implies it):\n\n| Auditor | Planted errors flagged | Other nuggets flagged |\n|---|---:|---:|\n| `gemini-3.1-pro` | **67/70 (96 %)** | 3.0 % |\n| `qwen3.8-max` | **65/70 (93 %)** | 1.8 % |\n\nMissed: two removed quantifiers (\"apenas\", \"somente\") by both, three vital → okay relabels, one removed condition.\n\n**Gold self-score** (`assign_v2`): Flash 99.9 % `support` on the final primary set (4 `partial_support` of\n3,175), 99.8 % / 99.6 % on the Gemini / Qwen sets. 3.1 Pro: 100 % on the 348 nuggets of `stratified_70` (the\nG tests of §2.5 use the self-score prompt, so they are its self-score on that subset).\n\n**Freeze** (`freeze`, plan v2 §3.5.3 and D10) → `nuggets/gold/v0-auto/`: 3,175 nuggets, 2,262 vital, **0\ndropped** (none flagged on C1 by both auditors). 134 nuggets carry one auditor's flag and 1 carries both, in the\nnew `audit` field; `stability` (3/3: 2,925, 2/3: 112, 1/3: 25) is filled where the nugget is unchanged since the\naligned `rep0` set (null for 113 nuggets of repaired questions).\n\n### 2.5 Phase 4: known-answer tests (judge selection)\n\n3,354 tests built from the frozen set (G 715, V 191, VP 27, Y 142, N 189, D 458, C 202, W 715, E 715). Flash judged\nall of them; 3.1 Pro the 348 tests of `stratified_70`.\n\n**Builder fixes of the pilot's test artifacts** (pilot note §7, open-decisions note §2.1), all by content-word\nbigram containment (`restated`):\n- **W:** the nearest question whose answer restates none of the nuggets (the pilot's near-duplicates are now\n skipped: Q335 for Q336, Q506 for Q507, Q621 for Q622);\n- **D / C:** the first deletion (or condition) whose content is not restated in the rest of the answer; D no\n longer deletes the verdict nugget (N tests it);\n- **VP (new):** an R$ amount replaced by a real amount from the corpus (S1 article chunks), 0.75–1.34× of it,\n at least 2 % away, written within 300 characters of it: often the same item's value in another year's table\n (2.275,08 → 2.156,52, 3.561,50 → 3.375,83). Found for 25 of the 182 distinct amounts of the answers;\n- **N:** a verdict nugget that restates the body (\"Sim. O contribuinte deve apresentar somente uma DAA…\") is\n ambiguous, since the unchanged body still supports it (§2.5.1).\n\n| Type | Flash detection (as `contradicts`) | Flash specificity | 3.1 Pro (`stratified_70`) detection | Pro specificity |\n|---|---:|---:|---:|---:|\n| G gold | — | 100 % | — | 100 % |\n| V value ± step | **97 % (96 %)** [261] | 100 % | 100 % [27] | 99 % |\n| VP corpus value | **100 % (100 %)** [34] | 100 % | 100 % [4] | 100 % |\n| Y year | **99 % (98 %)** [145] | 98 % | 100 % [15] | 100 % |\n| N verdict flip | **96 % (94 %)** [113] | 95 % | **67 %** [9] | 100 % |\n| D span deleted | 97 % [528] | 99 % | 94 % [50] | 98 % |\n| C condition removed | 89 % [202] | 99 % | 88 % [25] | 99 % |\n| W wrong question | 99 % [3,175] | — | 99 % [348] | — |\n| E empty | 100 % [3,175] | — | 100 % [348] | — |\n| **Pooled** | sens. 98.9 %, spec. 99.1 %, **BA 99.0 %** | | sens. 98.5 %, spec. 99.4 %, **BA 99.0 %** | |\n\n`contradicts` precision: Flash 75 % of 714 labels, Pro 84 % of 62 (the metric counts `contradicts` on ambiguous\nnuggets as false; most are the N tests' restated verdicts).\n\n**Judge (D2): Gemini 3.8 Flash stays the primary judge.** Same balanced accuracy as 3.1 Pro (Pro would need\n> 0.05 more), and 3.1 Pro again fails on verdict flips (6 of 9; the pilot: 3 of 5), reconciling a flipped\n\"Não\" with an affirmative body.\n\n#### 2.5.1 The N test before the ambiguity rule\n\nWith every verdict nugget as a target, Flash detected **88.9 %** of 189 flips, below the 0.90 gate. All 21\nmisses were read: each verdict nugget restates the answer's body (e.g. 009 \"O contribuinte deve apresentar\nsomente uma Declaração…\", 044 \"O direito de retificar… extingue-se em cinco anos\"), which the flip leaves\nintact, so `support` is defensible. This is the artifact the pilot found for D (a deleted verdict implied by the\nrest of the answer). With the rule, 76 nuggets become ambiguous and 113 stay targets; no API call changed\n(the labels are the same, from the cache). Both figures belong in the paper.\n\n### 2.6 Commands\n\n```bash\nP=.venv/bin/python; N=scripts/nuggets/nuggets.py; O=\"--out nuggets/full --sample all --workers 8 --budget <cap>\"\n$P $N --out nuggets/full sample --keep-from nuggets/pilot/sample.json\n$P $N $O create --models gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max && $P $N $O validate\nfor m in gpt-6.1-sol gemini-3.1-pro qwen3.8-max; do $P $N $O repair --set $m --model $m --new $m.rep0; done\n$P $N $O validate\nnuggets/full/logs/phase3a.sh # align (3 pairs of .rep0), roundtrip on gpt-6.1-sol.rep0, Flash selfscore\nnuggets/full/logs/phase3b.sh # audit by gemini-3.1-pro and qwen3.8-max, --candidates-from gpt-6.1-sol.rep0\n$P $N $O repair --set gpt-6.1-sol.rep0 --auditors gemini-3.1-pro,qwen3.8-max --new gpt-6.1-sol.rep1\n# validate; audit .rep1 (both auditors, same --others/--candidates-from); then the same for .rep2\n$P $N $O freeze --set gpt-6.1-sol.rep2 --aligned gpt-6.1-sol.rep0 --others gemini-3.1-pro.rep0,qwen3.8-max.rep0\nnuggets/full/logs/phase34.sh # plant + audit on stratified_70; known build; known judge Flash / 3.1 Pro\n$P $N --out nuggets/full --sample all pilotreport --primary gpt-6.1-sol.rep0 \\\n --others gemini-3.1-pro.rep0,qwen3.8-max.rep0 # → report_full.md\n```\n\n## 3. Gate summary (open-decisions note §1.1)\n\n| Gate | Threshold | Result | |\n|---|---|---|---|\n| Hard validation errors | 0 | primary: 3 enumerated items in 3 questions after 2 repair rounds (§2.2) | **not met; listed** |\n| Gold self-score | ≥ 98 % | Flash 99.9 % (all); 3.1 Pro 100 % (`stratified_70` only) | met (Pro on the subset) |\n| Flagged by both auditors after repair (any check) | ≤ 2 % | 0.03 % (1 nugget); 1.3 % before repair | met |\n| Judge sensitivity, value / year / verdict | ≥ 0.90 | Flash V 97 %, VP 100 %, Y 99 %, N 96 % (89 % without the N rule) | met |\n| Each auditor catches planted errors | ≥ 80 % | 3.1 Pro 96 %, Qwen 93 % | met |\n\n## 4. Code changes (no API cost by themselves)\n\n| File | Change |\n|---|---|\n| `scripts/nuggets/nuggets.py` | `sample --keep-from`, `all` and `stratified_70` lists; `repair` without `--auditors` (validator errors only); `freeze`; `audit` retries a truncated reply with `longer()`; `known build --corpus` (VP), `known judge --name` and only the `--sample` questions' tests; `pilotreport --primary/--others` → `report_full.md`; `jl_read` splits on `\\n` only (a 3.1 Pro justification held U+2028, which `splitlines()` splits on) |\n| `nuggetizer/validate.py` | verdict = Sim/Não + punctuation; `enum_item_worked_example` (R10: Q617, Q620); `no_vital_pointer`; `prompt_example` flag |\n| `nuggetizer/known_answer.py` | `restated()`; W near-duplicate skip; D/C restatement skip, D not on the verdict; N ambiguity rule; `CorpusValues` and the VP type |\n| `nuggetizer/planted.py` | no \"addition\" on a nugget that already implies it |\n| `nuggetizer/pilot_report.py`, `report.py` | full-run variant of the report (title, no 715-row table); VP row; reader fix |\n\n## 5. Points for the paper\n\n- Methods: route (OpenRouter, pinned providers, flex), the parity result (§2.3), validator-only repair before\n the audit (§2.2), two repair rounds, the freeze rules, and the builder fixes (§2.5) with both N figures.\n- The model-based error estimate: 1.3 % of nuggets flagged by two independent LLM auditors before repair\n (CI 0.7–2.1 %), 0.03 % after.\n- Synthetic corruptions remain cleaner than real generator errors (plan v2 §5.7); the real-run part of phase 4\n (judge agreement on RAG answers) waits for the RAG Phase 3 pilot.\n\n## 6. Open items (for the user)\n\n1. **3.1 Pro self-score on all 715 questions** (≈ $8.8 at flex prices, not run): the gate asks for \"both judges\";\n it is met on `stratified_70` only. Left out to keep a margin under the key's limit ($14.39 left) and because\n it exceeded the run's estimate. Run it with\n `selfscore --judge gemini-3.1-pro --sets gpt-6.1-sol.rep2` if wanted.\n2. **The 3 residual validator errors** (Q149, Q326, Q442): accept as listed (recommended; two are heading /\n restated items), or fix by hand.\n3. **Cache backup** of `nuggets/full/cache/` (gitignored; 246 MB) to the private HF dataset repo: needs your\n go-ahead (outward-facing).\n4. Still open from before: the \"expanded\" score on `has_pointer` questions (phase 5), and the open-weight Qwen\n judge (left out here).\n5. **Key:** renew or raise the limit before phase 5 (scoring ≈ $1.2–1.3 per answer run and nugget set with Flash).\n","20261021_165327_segmented_per_document_csvs_vs_chunks_all_audit.md":"# Segmented folder: per-document CSVs vs `chunks_all.csv` — audit\n\n**Generated:** 2026-10-21 16:53:27 (local time, from `date +%Y%m%d_%H%M%S`).\n**Question:** shouldn't every `.csv` under `segmented/statutory/` and `segmented/non_statutory/` be in\n`segmented/chunks_all.csv(.gz)`? Some seemed to be missing.\n**Answer:** all the content that should be in `chunks_all` is there. 75 of the 700 per-document CSVs are not in\nit: 69 are leftovers of documents removed from the corpus on purpose, and 6 are annexes with no text.\n**Status:** investigation only; **no files changed**. The cleanup (§4) is left for later.\n\n## 1. Method\n\n`segmented/chunks_all.csv` (last built 2026-10-09 12:57, `run_info.json`; 104,574 rows) was matched to the\nper-document CSVs by its `arquivo` column (the LexML file of each chunk, e.g. `lei_9250_19951226.xml` →\n`statutory/lei_9250_19951226.csv`).\n\n| | Count |\n|---|---:|\n| Per-document CSVs (`statutory/` 276 + `non_statutory/` 424) | 700 |\n| Distinct `arquivo` values in `chunks_all` | 625 |\n| `arquivo` values without a per-document CSV | 0 |\n| **Per-document CSVs with no row in `chunks_all`** | **75** (statutory 20, non-statutory 55) |\n\n## 2. The 69 leftovers: documents removed from the corpus\n\n| Document | CSVs | Rows | File date | Why it was removed |\n|---|---:|---:|---|---|\n| `in_rfb_1911_20191011` (IN RFB 1.911/2019, PIS/Cofins; main + 60 annexes) | 61 | 4,351 in the main file | main 2026-10-08, annexes 2026-09-25 | Never cited; v1's wrong match for IN RFB 1.997/2019 (the Q025 reference was dropped). The largest distractor in the corpus (≈ 5 % of the S3 rows) |\n| `in_rfb_1505_20141031` (main + 4 annexes) | 5 | 7 in the main file | 2026-09-25 | Cited only by Q081's dropped hallucinated reference |\n| `decreto_7030_20091214` (Vienna Convention on the Law of Treaties) | 1 | 3 | 2026-09-25 | Cited only by the wrong reference 144-05 (Q144 means the diplomatic-relations convention, Decreto 56.435); its \"Artigo N\" numbering was also not parsed (3 of 85 articles) |\n| `lei_3071_19160101` (Código Civil de 1916) | 1 | 3,095 | 2026-10-08 | Cited nowhere; came from the fetcher's `fetched_documents`; 25 duplicate article ids |\n| `lei_5869_19730111` (CPC de 1973) | 1 | 3,748 | 2026-10-08 | Cited nowhere (the answers cite the CPC of 2015, Lei 13.105) |\n\n- Decision: `docs/20261008_190226_reference_fixes_and_label_only_articles_investigation.md` (§2, items O2/O3, and the\n recommendation \"remove `in_rfb_1911_20191011`, `in_rfb_1505_20141031`, `decreto_7030_20091214` and … `lei_3071_19160101`\n and `lei_5869_19730111`\"). Applied in the 2026-10-09 rebuild (`docs/20261009_121822_nonstat_reparse_decision_and_pipeline_rerun_log.md`).\n- These documents are no longer in `original/` or `lexml/`, and no question in `dataset/questions.jsonl` references them.\n- **Why their CSVs are still there:** `scripts/segmentation/segment_all.py` (run with `--overwrite`) writes the\n outputs of the documents present in `lexml/` and builds `chunks_all` from them. It never deletes the per-document\n outputs of documents that are gone. 46 matching `.prov.jsonl` provenance files are leftovers too.\n- The pipeline reads only `chunks_all.csv(.gz)` (`segmented/README.md`: \"Use this one\"), so the leftovers do not reach\n embedding or retrieval.\n\n## 3. The 6 empty annexes: documents still in the corpus\n\nAll six CSVs were written by the last run (2026-10-09) with 0 rows; `annex_manifest.csv` records them as\n`DocumentoGenerico`, category C, 0 chunks.\n\n| Annex | XML content | Source `.docx` | Content lost? |\n|---|---|---|---|\n| `in_rfb_1585_20150831.anexo1`, `anexo2`, `anexo3` | the title only (\"ANEXO I\"…) | the headings only; the annexes are 3 embedded images | **No** (no text to extract) |\n| `in_rfb_1500_20141029.anexo19` | \"ANEXO XI\" | \"[Incluído(a) pelo(a) Instrução Normativa RFB nº 2299, de 17 de dezembro de 2025]\" and nothing else | **No** (an empty 2025 insertion, after the P&R date anyway) |\n| `in_srf_208_20020927.anexo1` | \"ANEXO I\" | **repeated heading**: \"ANEXO I\", then \"Anexo I\" + the \"Tabela de Atualização do Custo de Bens e Direitos\" | **No**: the table is in `anexo2.xml` (7,648 chars), which is in `chunks_all` (TAB chunk) |\n| `in_srf_81_20011011.anexo1` | \"ANEXO I\" | same repeated heading and table | **No**: the table is in `anexo2.xml` (7,691 chars), in `chunks_all` |\n\n**Side effect in IN SRF 208/2002 and IN SRF 81/2001.** The parser opens a new annex at each heading, so the repeated\nheading creates an empty `anexo1`. Every later annex file is then shifted by one: legal Anexo I is `anexo2`, and\nlegal Anexo II is split into `anexo3` (title + header) and `anexo4` (the form). The URNs of those chunks carry the\nshifted number. **No gold reference points to an annex of these two INs** (`dataset/references.jsonl`), so the\nlegal-provision retrieval evaluation is not affected today.\n\nThe segmentation report's `non_empty` check (`segmentation_report.md`: count 0) validates `chunks_all`, not the\nper-document files. That is why it does not list these six.\n\n## 4. Possible cleanup (not done; for later)\n\n1. **Delete the 69 leftover CSVs and their 46 `.prov.jsonl` files** (§2). No effect on the pipeline; the folder\n then matches `chunks_all`. Look at the list again before deleting.\n2. **Make `segment_all.py` delete per-document outputs whose document is no longer in `lexml/`**, or warn about\n them, so later rebuilds do not leave stale files.\n3. **Optional:** make the parser ignore a repeated annex heading (IN SRF 208, IN SRF 81), so the cost-update tables get\n the `anexo1` URN. Needed only if a reference to these annexes is ever added. This is a re-parse plus\n re-segmentation of two documents, and their embeddings would change.\n4. Optionally, add a check to `validate_segments.py`: every per-document CSV is either in `chunks_all` or listed as\n empty (0 chunks) in `annex_manifest.csv`.\n","20261021_194457_first_rag_evaluation_readiness_costs_and_grounding.md":"# First RAG evaluation — what is missing, costs, scope and grounding safeguards\n\n**Generated:** 2026-10-21 19:44:57 (local time, from `date +%Y%m%d_%H%M%S`).\n**Context:** nuggetization phases 2–4 are done (`docs/20261021_155704_nuggetization_phases_2_to_4_execution.md`,\nfrozen set `nuggets/gold/v0-auto/`). This note records the discussion of 2026-10-21 on what the first RAG answer\nevaluation still needs, with the user's answers and new information (§0). Plans it builds on:\n`docs/20260927_204356_rag_pipeline_implementation_plan.md` (**RAG plan**) and\n`docs/20261011_224049_gold_answer_nuggetization_plan_v2.md` (**plan v2**).\n**Status:** discussion and decisions only; no code changed, no API call made (only free model listings and the\nOpenRouter key status).\n\n## 0. New information and decisions from the user (2026-10-21)\n\n| # | Item |\n|---|---|\n| U1 | **OpenRouter cap raised to $100.** `nuggets.py openrouter-key` (19:44): usage $65.61, **$34.39 left**, expires 2026-11-20. The account had $150 prepaid (2026-10-20), so ≈ $84 of prepaid credit is left behind the cap |\n| U2 | **Maritaca AI key** created: `MARITACA_API_KEY` in the repo-root `.env`. Checked: `GET https://chat.maritaca.ai/api/models` lists `sabia-4`, `sabiazinho-4`, `sabia-4-thinking` and their `-br-sp` variants |\n| U3 | **Generators:** Sabiá-4 and Sabiazinho-4, plus at least one pair of strong frontier models, preferably OpenAI but **not GPT \"sol\"** (the `gpt-6.1-sol` family created the primary nugget set). Suggestions in §5 |\n| U4 | **DeepSeek** models are wanted too, but they cannot be reached from this environment; they run later, from another machine (see the two-machine note in memory). Keep them in `llms.yaml` and in the experiment files so that run is only a config switch |\n| U5 | **Agreed:** add the per-question retrieval ↔ answer linkage to phase 5 (§3.1) |\n\n## 1. What is missing before the first RAG evaluation\n\nThe retrieval stage (RAG Phase 1) is done: `rag.py check --embedding jua-4b-mixed` passes (2026-10-21), the\nrankings of S1/S2/S3/S2c/S4 are in `runs/retrieval/jua-4b-mixed/irpf/`, and the legal-provision test is in\n`eval/v2d_either_containment_skip/`. The nuggets are frozen. Missing:\n\n| # | Missing | Where | Notes |\n|---|---|---|---|\n| 1 | **RAG Phase 2 — context:** `context` subcommand, provenance header per chunk (`[Documento n] Lei nº … — Art. 8º, II, b`), versioned template `context_v1.pt.md`, the **closed-book** (`k=0`) and **oracle** contexts, `runs/contexts/…` | `scripts/rag/ragpipe/context.py` (selection exists) | Gate: pilot contexts read by hand (RAG plan §9) |\n| 2 | **RAG Phase 3 — generation:** `llms.yaml` registry, `answer_v1.pt.md`, `generate` / `run --experiment`, `--dry-run` cost estimate, `answers.jsonl` + `run.json`, ledger `runs/costs.csv`, `fake` provider and tests | `scripts/rag/` on the shared `scripts/llm_client/` | Gate: 30-question pilot (`stratified_30`), answers read by hand, cost per full run estimated |\n| 3 | **Maritaca provider:** not on OpenRouter, so a direct `openai_compat` route (`https://chat.maritaca.ai/api`, `MARITACA_API_KEY`) with cache, ledger and the grounding checks of §4 | `scripts/llm_client/client.py` | Prices in BRL (§2.1); the ledger needs a BRL→USD rate column or a fixed rate recorded per run |\n| 4 | **Nugget phase 5 — scoring:** `nuggets.py` has no `score` command | `scripts/nuggets/` | Judge assignment of system answers (`assign_v2`, Flash), V_strict/V/A_strict/A/W, contradiction rate, value checks (plan v2 §5.4), legal-provision score (§5.5), paired bootstrap + chapter-cluster bootstrap, perturbation robustness (§5.6), judge agreement on real answers (the deferred real-run part of phase 4), and the linkage of §3.1 |\n| 5 | **Open decisions:** headline budget (4k was a placeholder; S2 vs S1 article recall 0.47 vs 0.38 at 4k, 0.57 vs 0.48 at 8k), the \"expanded\" score on `has_pointer` questions, reasoning effort of the generators (§5) | user | |\n| 6 | **Budget:** $34.39 on the OpenRouter key covers the pilot, not the full first evaluation (§2.3) | user | |\n\n## 2. Cost estimates (only `jua-4b-mixed`)\n\n**Retrieval costs nothing more:** query and corpus vectors are stored, rankings regenerate locally in ≈ 30 s.\nHaving one embedding model only removes a grid dimension. A BM25 baseline (RAG plan Phase 1b) would be a free\nsecond retriever.\n\n### 2.1 Prices (checked 2026-10-21)\n\nOpenRouter public model list (`/api/v1/models`, per 1M tokens, list price; OpenAI and Gemini have half-price flex\nendpoints on OpenRouter, to be confirmed per model with a probe as in `probe_openrouter.py`). Maritaca official\npricing page (`docs.maritaca.ai/pt/precos`, BRL); USD figures below assume **R$ 5.5 / US$** (to be replaced by\nthe rate on the billing date).\n\n| Model | Released | Input | Output | Notes |\n|---|---|---:|---:|---|\n| `sabia-4` (pin `sabia-4-2026-01-06`) | 2026-01-06 | R$ 5,00 (≈ $0.91) | R$ 20,00 (≈ $3.64) | cache R$ 1,25; **flex / batch / night (22–06 BRT) −50 % / −30 %**; 128k context |\n| `sabiazinho-4` (pin `sabiazinho-4-2026-01-06`) | 2026-01-06 | R$ 1,00 (≈ $0.18) | R$ 4,00 (≈ $0.73) | same discounts; 128k context |\n| `sabia-4-thinking` | 2026 | R$ 5,00 | R$ 40,00 | 1M context; not proposed (reasoning cost, no non-thinking twin of Sabiazinho) |\n| `openai/gpt-6-astra` | 2026-09-04 | $10.00 | $50.00 | OpenAI's top tier |\n| `openai/gpt-5.6-terra` | 2026-07-09 | $2.00 | $12.00 | |\n| `openai/gpt-5.6-luna` | 2026-07-09 | $0.20 | $1.20 | |\n| `openai/gpt-6-luna` | 2026-09-22 | $0.10 | $0.50 | |\n| `anthropic/claude-sonnet-5.5` | 2026-09-28 | $2.00 | $10.00 | |\n| `anthropic/claude-haiku-5.5` | 2026-10-07 | $0.10 | $0.50 | |\n| `deepseek/deepseek-v4-pro` | 2026 | $0.41 | $0.83 | later, from the other machine (U4) |\n| `deepseek/deepseek-v4-flash` | 2026 | $0.09 | $0.18 | later (U4) |\n\nMaritaca also sells **built-in tools** (web search R$ 0,0165 per search, page reads R$ 0,066 per page), reported in\n`usage.tool_execution_details`: see §4.1.\n\n### 2.2 Per-call and per-run assumptions\n\nInput ≈ context budget + ≈ 0.9k tokens (instructions, question, chunk headers); output ≈ 0.7k visible tokens, plus\n≈ 0.3k reasoning at low effort where a model reasons. Budgets are counted in Qwen3 tokens, so each generator's own\ncount differs by ≈ ±20 %. One full run = 715 questions; at 4k ≈ 3.5M input and 0.5M output.\n\n| Generator, one full run | closed-book | 4k | 8k | 16k |\n|---|---:|---:|---:|---:|\n| Sabiá-4 (list / flex) | R$ 13 / 6 | **R$ 28 / 14** (≈ $5 / 2.5) | R$ 44 / 22 | R$ 76 / 38 |\n| Sabiazinho-4 (list / flex) | R$ 3 / 1.3 | **R$ 5.5 / 2.8** (≈ $1 / 0.5) | R$ 9 / 4.5 | R$ 15 / 7.5 |\n| `gpt-6-astra`, low effort (list / flex) | $41 / 20 | **$70 / 35** | $100 / 50 | $165 / 82 |\n| `gpt-5.6-terra`, minimal effort (list / flex) | $7 / 3.5 | **$13 / 6.5** | $19 / 10 | $33 / 17 |\n| `gpt-5.6-luna` / `gpt-6-luna` | $0.7 / 0.4 | $1.3 / 0.7 | $2 / 1 | $3.5 / 1.8 |\n| `claude-sonnet-5.5` / `claude-haiku-5.5` | $6 / 0.3 | $12 / 0.6 | $18 / 0.9 | $31 / 1.5 |\n\n**Scoring** (Flash flex, primary nugget set): the Flash self-score of a 715-question set cost $0.95 on the gold\nanswers (phases 2–4 ledger); system answers are longer, so **≈ $1.0–1.5 per answer run and nugget set**. The\njudge reads nuggets + answer, not the context, so this does not grow with the budget. The context-support check\nof §4.3 costs ≈ $2 per context set (it reads the context), and is shared by all generators.\n\n### 2.3 Sizing\n\n**Pilot** (`stratified_30`, the RAG Phase 3 gate): 11 contexts per generator (S1, S2, S3, S2c, S4 at 4k; S1, S2 at\n2k and 8k; closed-book; oracle at 4k) = 330 calls per generator.\n\n| Item | Cost |\n|---|---:|\n| Sabiá-4 + Sabiazinho-4 (Maritaca account, list) | ≈ R$ 15 |\n| `gpt-5.6-terra` + `gpt-5.6-luna` (OpenRouter, list / flex) | ≈ $6.5 / 3.5 |\n| `gpt-6-astra` on 4 contexts only (S1, S2 at 4k, closed-book, oracle), list / flex | ≈ $11 / 5.5 |\n| Scoring ≈ 1,450 judge calls + context support (10 contexts × 30) | ≈ $4.5 |\n| **OpenRouter total** | **≈ $10–22** (fits the $34.39 left) |\n\n**First full evaluation** (715 questions), the reduced \"headline\" grid: 5 strategies at 4k + closed-book + oracle\n= 7 runs per generator, 4 generators (Sabiá-4, Sabiazinho-4, an OpenAI pair, §5):\n\n| Item | Cost |\n|---|---:|\n| Maritaca generation (Sabiá-4 7 runs + Sabiazinho-4 7 runs), list / flex | ≈ R$ 230 / 115 |\n| `gpt-5.6-terra` + `gpt-5.6-luna`, 7 runs each, flex | ≈ $45 |\n| Scoring: 28 runs × primary set | ≈ $28–42 |\n| Scoring: Gemini and Qwen sets on S1 vs S2 at 4k, 4 generators (16 runs) | ≈ $16–24 |\n| Context support (6 context sets) | ≈ $12 |\n| **OpenRouter total** | **≈ $100–125** |\n\nThe full 11-run grid adds ≈ 60 % to this. `gpt-6-astra` on the headline grid alone would add ≈ $125 at flex\n($250 at list), so it is a candidate for the headline comparison on a subset only (§5). **The key and the\nprepaid credit need a top-up before the full first evaluation**; the pilot's ledger replaces these estimates.\n\n## 3. Scope of the next phases: retrieval and answers\n\n- **Retrieval (the legal-provision test):** done in RAG Phase 1 (document / article / provision recall, MRR,\n nDCG@10, context precision, paired S1/S2/S3 comparisons). Not rerun; reported next to the answer scores.\n- **Answers vs gold nuggets:** nugget phase 5, the main metric, with the value checks (plan v2 §5.4), the\n legal-provision score of the citations in the answers (§5.5, comparable to the retrieval metrics), and the\n closed-book and oracle runs as bounds.\n\n### 3.1 Retrieval ↔ answer linkage (agreed, U5; added to phase 5)\n\nJoin the per-question answer scores with the retrieval outcome of the same context\n(`eval/<eval_id>/per_item.csv.gz`: `budget_full_<B>`, `budget_any_<B>`, `rank_full`; `per_question.csv.gz`):\n\n- answer score by **context state**: gold provision fully in context / partly / absent;\n- per strategy pair (S2 − S1), split the answer-score difference into the questions where the retrieval outcome\n differs and those where it is the same: \"S2 answers better **because** it retrieves better\" vs \"S2 answers\n better from the same evidence (better chunk form)\";\n- nugget support in the context (§4.3) as the mediator: answer recall is bounded by the share of nuggets the\n context supports;\n- report the correlation of context recall / context precision with V_strict per strategy and budget.\n\nNo extra API cost beyond §4.3.\n\n## 4. Keeping the generators on the retrieved segments\n\n### 4.1 Web search: blocked at the API level\n\n- **No tools in generation requests.** `scripts/llm_client/` sends no `tools` or `plugins` today. Add a hard check\n that refuses a generation request with `tools`, `plugins`, `web_search_options` or a model id ending in\n `:online` (OpenRouter web search runs only through the `web` plugin or the `:online` suffix, $0.01 per request on\n these models; OpenAI and Gemini search grounding run only as tools).\n- **Maritaca has built-in tools** (web search, page reading, code execution, Data Ocean). Send no `tools`, and\n reject a reply whose `usage.tool_execution_details` shows any web search or page read.\n- **Check every reply:** reject tool calls, `url_citation` annotations, or a billed cost above the token cost\n (`usd_billed` vs tokens × price); log the reason in the ledger.\n- Keep the pinned providers with `allow_fallbacks: false` on OpenRouter, as for the nuggets. No search-native\n models in `llms.yaml`.\n\n### 4.2 Own (parametric) knowledge: discouraged and measured\n\nIt cannot be switched off. The P&R 2024 is public and probably in the training data of every candidate.\n\n1. **Prompt (`answer_v1`):** answer only from the numbered provisions; cite `[Documento n]` for every statement;\n write no value, date or rate absent from the provisions; if they are not enough, reply with a fixed abstention\n sentence (gives an abstention rate); do not name a \"current\" law or year beyond the context.\n2. **Structured output with quotes:** each claim with `{document ids, verbatim quote}`; a script checks that the\n quote is a substring of the cited chunk. Claims without a valid quote count as ungrounded (no LLM).\n3. **Values not in the context:** extract R$, %, dates from the answer (`nuggetizer/values.py`); flag any value\n absent from both the context and the question. Catches the worst leak: 2025 tables or limits from training.\n4. **Controls:**\n - closed-book (`k=0`): what the model knows without retrieval;\n - **wrong context:** another question's context; a good score there means the model is not reading it;\n - the \"gold missing from context\" slice (§3.1): support there points to own knowledge (or redundant provisions).\n5. **Nugget support in the context (§4.3):** the judge assigns the gold nuggets against the context itself, once\n per strategy × budget, shared by all generators. A nugget supported by the answer but not by its context is a\n direct, per-nugget leakage measure.\n6. **Memorization:** n-gram overlap of the answer with gold-answer text that is not in the context (the model\n recites the P&R).\n7. **Settings:** low or minimal reasoning, temperature 0 where allowed, knowledge cutoff recorded per generator in\n `llms.yaml`.\n\nItems 1–3 cost nothing extra; 4–5 add ≈ 10–20 % to the scoring budget and give the paper a measured leakage\nfigure.\n\n### 4.3 Context-support call\n\n`assign_v2` with the context in place of the answer (a new prompt version, e.g. `assign_ctx_v1`, since the\ncontext is legal text, not an answer). Output per nugget: supported by the context or not. Cost ≈ $2 per context\nset (715 questions at 4k, Flash flex).\n\n## 5. Generator suggestions (U3)\n\nConstraints: the primary nugget set is GPT (`gpt-6.1-sol`), the second set and auditor 1 are Gemini 3.1 Pro, the\njudge is Gemini 3.8 Flash, the third set and auditor 2 are Qwen3.8-Max. A generator from none of these families\navoids every overlap; an OpenAI generator overlaps with the creator **vendor** even when it is not \"sol\" (plan v2\n§6.2: it cancels in the paired strategy comparisons, and the three nugget sets control the cross-generator table).\n\n| Pair | Large | Small | Pros | Cons |\n|---|---|---|---|---|\n| **A (recommended for the grid): OpenAI 5.6** | `gpt-5.6-terra` ($2 / $12) | `gpt-5.6-luna` ($0.20 / $1.20) | A clean large/small pair of one release, like Sabiá-4 / Sabiazinho-4; an older generation than the creator `gpt-6.1-sol` (less stylistic overlap, earlier knowledge cutoff → less post-2024 law); affordable on the full grid | Not OpenAI's top tier |\n| **B: OpenAI 6** | `gpt-6-astra` ($10 / $50) | `gpt-6-luna` ($0.10 / $0.50) | The strongest OpenAI model | Astra ≈ $35–70 per run: only on the headline comparison (S1 vs S2 at 4k + closed-book + oracle), ideally on `stratified_70`; same generation as the creator |\n| **C (optional, no family overlap): Anthropic** | `claude-sonnet-5.5` ($2 / $10) | `claude-haiku-5.5` ($0.10 / $0.50) | No overlap with creator, auditors or judge; costs like pair A | A third vendor to pin and probe |\n\n**Recommendation:** Sabiá-4 + Sabiazinho-4 (pinned `-2026-01-06`, non-thinking, flex tier for the full runs) and\n**pair A** for the grid; `gpt-6-astra` as a \"ceiling\" generator on the headline comparison of a subset if the\nbudget allows; pair C if a vendor without overlap is wanted. DeepSeek V4 Pro / Flash later (U4), as a fourth\npair. The `-br-sp` Maritaca variants cost 30 % more for in-country processing and are not needed here.\n\nTo confirm in the pilot: which reasoning-effort levels each OpenAI model accepts (minimal / none / low), flex\navailability on OpenRouter for terra, luna and astra, and the provider pin for each.\n\n## 6. Next steps\n\n1. RAG Phase 2 (`context`, closed-book, oracle, wrong-context control) → contexts of the pilot read by hand.\n2. RAG Phase 3 (`llms.yaml` with Maritaca + pair A [+ astra, pair C, DeepSeek disabled here], `answer_v1`,\n grounding checks of §4.1, `--dry-run`) → pilot on `stratified_30`, answers read by hand, cost ledger.\n3. Nugget phase 5 `score` (with §3.1 and §4.3) on the pilot answers; judge agreement on real answers.\n4. Top up the OpenRouter key / credit with the pilot's measured costs, then the first full evaluation (§2.3).\n","20261021_210251_rag_phase2_contexts_execution.md":"# RAG Phase 2 — generator contexts: implementation and run\n\n**Generated:** 2026-10-21 21:02:51 (local time, from `date +%Y%m%d_%H%M%S`).\n**Implements:** RAG plan §6 (`docs/20260927_204356_rag_pipeline_implementation_plan.md`, stage C) and the\ncontrols of the first-evaluation note (`docs/20261021_194457_first_rag_evaluation_readiness_costs_and_grounding.md`\n§2.3, §3.1, §4.2): closed-book, oracle and wrong-context sets, and per-question gold coverage for the phase 5\nretrieval ↔ answer linkage.\n**Cost:** $0 (no API call). **Embedding:** `jua-4b-mixed`, instruction `irpf`, rankings of 2026-10-09\n(chunk file SHA-256 `a6087b7f…326a`).\n**Outputs:** `runs/contexts/jua-4b-mixed/irpf/` (20 context sets × 715 questions, 46 MB; `summary.csv` and the\nmanifests are in git, `contexts.jsonl.gz` are not), and a new retrieval evaluation\n`runs/retrieval/jua-4b-mixed/irpf/eval/either_containment_merge_skip/` (§4).\n**Status:** done (decisions of §7: items 1 and 3 settled in §9–§10). **The numbers of §3–§10 are those of the corpus\nwith the RIR/1999; since 2026-10-22 the main run excludes it** (`docs/20261022_203625_corpus_exclusion_revoked_rir1999.md`;\nthe corpus of this note is the ablation run `irpf_with_rir1999`); **gate** (RAG plan §9: \"contexts of a pilot sample reviewed by hand\") needs the user's\nreview of §5, and **three decisions** (§7), the first of which changes the headline retrieval numbers.\n\n## 1. What was built\n\n| File | Change |\n|---|---|\n| `scripts/rag/ragpipe/contexts.py` (new) | Stage C driver: set specs, retrieval / closed-book / oracle / wrong-context sets, gold coverage, consistency check against the evaluation, rendering, `summary.csv` |\n| `scripts/rag/ragpipe/context.py` | Header label (`source_label`, issuing body from the URN), versioned template (`Template`); selection option `containment_merge` (§4) |\n| `scripts/rag/prompts/context_v1.pt.md` (new) | `[Documento {n}] {fonte}` + `{texto}`, blocks joined by a blank line |\n| `scripts/rag/rag.py` | `context` and `show-context` subcommands; `--dedup containment_merge` for `evaluate` too |\n| `scripts/rag/ragpipe/data.py` | `load_chunks(with_text=True)` also loads `anexo_urn`, `texto_sha256` |\n| `scripts/rag/ragpipe/runs.py` | `write_jsonl_gz` (byte-reproducible); `git_info` computed once per process (`git status` took ≈ 3 s per manifest on this checkout: the test suite went from 196 s to 9 s) |\n| `scripts/rag/tests/test_contexts.py` (new), `test_units.py` | 10 new tests (sets, oracle, donors, rendering, labels, epígrafe fallback, spec parsing, determinism, CLI, merge); **34 passed** |\n| `scripts/rag/README.md`, `CLAUDE.md`, `.gitignore` | Phase 2 documented; `runs/contexts/**/summary.csv` versioned |\n\n```bash\nR=scripts/rag/rag.py\n.venv/bin/python $R context --retrieval runs/retrieval/jua-4b-mixed/irpf \\\n --sets S1@budget=4000,…,wrong:S2@budget=4000,oracle@budget=16000 # the 12 pilot sets + oracle 16k\n.venv/bin/python $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf --dedup containment_merge\n.venv/bin/python $R context --retrieval runs/retrieval/jua-4b-mixed/irpf --dedup containment_merge \\\n --sets S1@budget=4000,S2@budget=4000,S3@budget=4000,S2c@budget=4000,S4@budget=4000,S1@budget=8000,S2@budget=8000\n.venv/bin/python $R show-context --context runs/contexts/jua-4b-mixed/irpf/S2_budget4000 --questions 350\n```\n\nTime: 70 s for the 13 default-option sets (33 s of it loading the chunks and the Matcher), 2 min 26 s for all 20;\nthe merge evaluation ≈ 2 min.\n\n## 2. Design\n\n### 2.1 Context sets\n\n| Spec → id | Content |\n|---|---|\n| `S2@budget=4000` → `S2_budget4000` | The strategy's ranking cut by `context.select` (containment de-duplication, `skip`): **the same texts as the evaluation's budget view**, in rank order |\n| `closed_book` | Empty |\n| `oracle@budget=4000` | The question's gold articles (rules G1–G3, annex rule `either`) as S1 article units; a gold document none of whose gold articles is matchable (e.g. the treaties promulgated by decree, \"art. IX\": Q154, Q155, Q158, Q159) adds its S1 chunks. Ordered by S1 rank (unranked after, in file order), cut by the budget. Empty for the **119 questions without resolved gold** |\n| `wrong:S2@budget=4000` → `wrong-S2_budget4000` | The S2 4k context of a **donor**: another P&R chapter, no shared gold document, and no chunk of the question's gold documents in the donor context; seeded permutation (seed 13). The control for answers from the model's own knowledge |\n\nNon-default options add a suffix (`S2_budget4000_dedup-containment_merge`); a set directory refuses to be\noverwritten by another configuration (`--force`), as the other stages.\n\n### 2.2 Rendering (`context_v1`)\n\n```\n[Documento 2] DECRETO Nº 3.000, DE 26 DE MARÇO DE 1999 — Art. 77, § 1º\n[ DECRETO Nº 3.000, DE 26 DE MARÇO DE 1999 | Regulamenta a tributação, … ] Art. 77. § 1º Poderão ser considerados como dependentes, …\n```\n\n- `{fonte}` = document title (`documents.jsonl`) — issuing body when the title lacks it (titles of RFB/SRF acts\n read \"INSTRUÇÃO NORMATIVA Nº 1.500, …\"; 4,701 of 12,486 distinct headers get \"Receita Federal [do Brasil]\") —\n `Anexo` for annex chunks — the chunk's `citacao` — `(parte p de n)` for split articles.\n- **Title fallback:** 9 documents have no title in `documents.jsonl` (seven RFB service pages: DBF, DIMOB, DMED,\n DOI, DIRF, Carnê-Leão, DIAT; two soluções de consulta). The header then uses the epígrafe of the chunk's\n `[ … ]` prefix, or its ementa when the epígrafe is a URN (the DIAT page, see §6).\n- **Citation fix:** the segmentation's `citacao` writes \"Art. 71., § 1º\" / \"Parágrafo único., II\"; the header\n drops a period before a comma.\n- The chunk text is unchanged: it is what was embedded and what the budget counts.\n\n### 2.3 Gold coverage per context (phase 5 linkage)\n\nEach line of `contexts.jsonl.gz` has `gold.{document,article,provision} = {n, full, any}` (the item keys of\n`per_item.csv.gz`), by the evaluation's rules (`Matcher`; full hit = a `cobre_ids` id equal to or an ancestor of\nthe fragment, a containing grouping chunk, or all parts of a split article). Lines also carry, per item, rank,\nscore, chunk id, aliases, tokens and the header.\n\n## 3. Results\n\n### 3.1 Consistency with the retrieval evaluation\n\nFor the 9 retrieval sets with default options, the set of fully hit gold items equals the evaluation's\n`budget_full_<B>` (`v2d_either_containment_skip`) item by item: **0 mismatches** (5,912 items per strategy; e.g.\n1,936 full hits in S1 4k, 2,691 in S2 8k). The 7 merge sets match `either_containment_merge_skip`: 0 mismatches.\nSo the generator sees exactly the contexts the legal-provision test measured.\n\n### 3.2 Context sets (`summary.csv`; recall = mean share of gold items fully in the context, over questions with gold)\n\n| Set | Texts | Text tokens | Rendered tokens | Header overhead | Document recall | Article recall | Article hit | Provision recall |\n|---|---:|---:|---:|---:|---:|---:|---:|---:|\n| S1 2k | 6.3 | 1,985 | 2,245 | 13.1 % | 0.479 | 0.266 | 0.465 | 0.239 |\n| S1 4k | 11.1 | 3,984 | 4,447 | 11.6 % | 0.605 | 0.383 | 0.604 | 0.353 |\n| S1 8k | 20.9 | 7,985 | 8,869 | 11.1 % | 0.718 | 0.480 | 0.707 | 0.456 |\n| S2 2k | 7.8 | 1,983 | 2,328 | 17.4 % | 0.575 | 0.388 | 0.609 | 0.262 |\n| S2 4k | 13.7 | 3,984 | 4,593 | 15.3 % | 0.667 | 0.473 | 0.705 | 0.362 |\n| S2 8k | 26.1 | 7,984 | 9,146 | 14.6 % | 0.764 | 0.569 | 0.792 | 0.471 |\n| S2c 4k | 13.1 | 3,983 | 4,561 | 14.5 % | 0.636 | 0.431 | 0.680 | 0.324 |\n| S3 4k | 12.7 | 3,983 | 4,555 | 14.4 % | 0.655 | 0.465 | 0.693 | 0.362 |\n| S4 4k | 12.2 | 3,983 | 4,529 | 13.7 % | 0.632 | 0.428 | 0.665 | 0.338 |\n| closed-book | 0 | 0 | 0 | — | 0 | 0 | 0 | 0 |\n| **oracle 4k** | 4.7 | 2,062 | 2,265 | 9.8 % | 0.884 | **0.803** | 0.902 | 0.770 |\n| **oracle 16k** | 10.6 | 4,980 | 5,444 | 9.3 % | 0.974 | **0.946** | 0.980 | 0.925 |\n| wrong S2 4k | 13.2 | 3,984 | 4,569 | 14.7 % | **0** | **0** | 0 | 0 |\n\n- **Header overhead 10–17 %**: a 4k context is ≈ 4.45–4.6k rendered Qwen3 tokens. The cost estimates of the\n first-evaluation note (budget + 0.9k) still hold.\n- **The oracle at 4k holds 80 % of the gold articles**, not 100 %: of 1,958 gold articles, 1,293 are in it, 652 are\n reachable but do not fit in 4k (questions citing many or long articles; 248 oracle contexts are above 3.5k\n tokens), 13 are not in the LexML. At 16k it holds 95 %. Oracle 4k is the right bound for equal-budget\n comparisons, oracle 16k the ceiling.\n- **Wrong context:** no question's context holds any of its gold (by construction, verified: all coverage 0);\n the strict donor rule was never relaxed; 113 donors serve two questions (the unused-donor pool runs out of\n eligible ones late in the permutation).\n\n## 4. Finding: parents after their children repeat text (`containment` vs `containment_merge`)\n\n`containment` (the Phase 1 rule, RAG plan §6.1) drops a child ranked after a selected parent, but keeps a\n**parent ranked after its selected child**, \"since the parent adds text\". The child's text is then in the\ncontext twice. Measured on the default sets:\n\n| Set | Duplicated child tokens (share of context tokens) | Questions affected |\n|---|---:|---:|\n| S1 4k | 0.0 % | 1 / 715 |\n| S2 4k | 9.3 % | 489 |\n| S3 4k | 11.2 % | 501 |\n| S2c 4k | 13.8 % | 505 |\n| S4 4k | 14.5 % | 506 |\n| S2 8k | 11.0 % | 607 |\n\nExample (Q350, S2 4k): `Lei 9.250, Art. 35, caput` at rank 7, then the whole `Art. 35` at rank 12.\nSo at equal budget the hierarchical strategies spend 9–15 % of it on repeats, and S1 does not: a **bias against\nS2–S4 in the headline comparison**, in the retrieval test and in the generator contexts alike (and two copies of\na provision are a poor context for a generator).\n\n`containment_merge` (new option, plan §6.1 \"left for later\") lets that parent **replace** its selected children,\nin the first child's place, using only its extra tokens. Legal-provision test, `either_containment_merge_skip` vs\n`v2d_either_containment_skip` (budget view, all gold):\n\n| Strategy | Article recall 4k: containment → merge | Provision recall 4k | Provision full recall 4k | Article context precision 4k |\n|---|---|---|---|---|\n| S1 | 0.383 → 0.383 | 0.353 → 0.353 | 0.204 → 0.204 | 0.124 → 0.124 |\n| S2 | 0.473 → **0.495** (+0.022) | 0.362 → **0.404** (+0.042) | 0.210 → 0.244 | 0.157 → 0.138 |\n| S3 | 0.465 → 0.494 (+0.029) | 0.362 → 0.409 (+0.048) | 0.219 → 0.260 | 0.171 → 0.154 |\n| S2c | 0.431 → 0.468 (+0.037) | 0.324 → 0.402 (+0.078) | 0.186 → 0.238 | 0.179 → 0.147 |\n| S4 | 0.428 → 0.468 (+0.039) | 0.338 → 0.408 (+0.070) | 0.206 → 0.253 | 0.189 → 0.163 |\n\nGains are similar at 2k and 8k (+0.014 to +0.036 article recall) and smaller at 16k. Paired S1 → S2 article\nrecall difference: 2k +0.122 → **+0.136**, 4k +0.090 → **+0.111**, 8k +0.089 → **+0.107** (all p < 0.001); S2 → S3\nstays not significant (−0.001 to −0.003). Context precision drops 1–4 points: the parents bring their non-gold\nsiblings with them. The caput variants (S2c, S4) gain most: they repeat the caput sentence in every child, so a\nlater parent repeated more. The merged contexts hold fewer, longer texts (S2 4k: 12.6 vs 13.7).\n\nThe merge evaluation's comparisons use the default pairs (S1:S2, S2:S3); the caput pairs can be added with\n`--comparisons` if merge is adopted.\n\n## 5. Hand review (gate): what to look at\n\n`show-context` prints the items (rank, tokens, chunk, header) and the rendered text of any question and set. I\nread Q012 and Q350 (both in `stratified_30`) across the sets; Q350 (sogro/sogra as dependents, gold Lei 9.250\nart. 35):\n\n- **S1 4k** (9 texts): IN RFB 1.500 art. 90 (2 parts), **Lei 9.250 art. 35 (gold, rank 2)**, Solução de Consulta\n Cosit 15/2016, Decreto-Lei 1.493 art. 2º, Decreto 3.000/1999 art. 77…\n- **S2 4k** (11): IN 1.500 art. 90 caput, Decreto 3.000 art. 77 § 1º, IN 1.500 art. 90 part 1, RIR/2018 art. 71 § 1º,\n Lei 9.250 art. 35 caput **and** art. 35 (the repeat of §4)…\n- **S2 4k merge** (13): the caput is absorbed by art. 90 part 1, art. 35 appears once; the freed tokens bring\n in IN SRF 81 art. 14, IN 1.500 art. 100 § 1º, Lei 12.973 art. 25…\n- **oracle 4k**: Lei 9.250 art. 35 only (723 tokens). **wrong S2 4k**: donor Q628 (another chapter), 17 texts, no\n gold.\n\nThings the reviewer should judge on 3–5 pilot questions: header readability; whether the `[ Epígrafe | Ementa ]`\nprefix repeated in every block is acceptable (part of the 10–17 % overhead); the presence of **revoked\nregulations** (Decreto 3.000/1999, the RIR/1999, next to Decreto 9.580/2018), which the P&R cites and the corpus\ntherefore contains: a temporal-grounding risk the answer prompt and the value checks must handle, not a context\nbug.\n\n## 6. Corpus issues found (not fixed)\n\n1. **DIAT service page** (`urn_lex_br_…_servico_2026_diat.xml`, 1 chunk): its epígrafe is the URN\n (`[ urn:lex:br:…;diat | Documento de Informação e Apuração do ITR (Diat) ]`), so the embedded text starts with a\n URN. Cause: no title declared for it. The header works around it; the chunk text needs a re-parse with a title\n (`scripts/lexml/nonstat_metadata.tsv`) and a re-embedding of one text.\n2. **Missing titles** in `documents.jsonl` for 9 documents (§2.2): `build_v2_dataset.py` could take them from the\n LexML epígrafe.\n3. Long `citacao` values in some non-statutory chunks (159 headers > 220 characters: section headings used as the\n citation, e.g. NOTA PGFN/CRJ 1104/2017). Readable; left as is.\n\n## 7. Decisions for the user\n\n1. **De-duplication of the contexts (and of the headline retrieval test): `containment` or\n `containment_merge`?** Recommendation: **`containment_merge`** for the generator contexts and as the\n headline of the legal-provision test, with `containment` reported as the Phase 1 variant. It removes a\n bias against S2–S4 and duplicated text in the prompts. It changes the headline S1 → S2 gap (4k article\n recall +0.090 → +0.111), so the retrieval note's numbers would be restated. If adopted, the default\n `--dedup` of `context` and `evaluate` changes, the merge evaluation becomes the headline (it already\n exists), and the pilot sets are rebuilt (≈ 1 min).\n2. **Oracle budget:** recommendation: run **both** oracle 4k (equal budget) and oracle 16k (ceiling) in the\n generation pilot; oracle 16k adds 30 calls per generator to the 11-context pilot grid.\n3. **Header:** keep `context_v1` (title per block, ≈ 10–17 % overhead) for the pilot (recommended), or make a\n `context_v2` that names the issuing body and the citation only, since the chunk prefix already carries the\n title and ementa (saves ≈ 5–8 % of the input).\n\n## 8. Next\n\nRAG Phase 3 (generation): `llms.yaml` (Sabiá-4, Sabiazinho-4 on the Maritaca route; `gpt-5.6-terra`,\n`gpt-5.6-luna` on OpenRouter; DeepSeek disabled here), `answer_v1` with the grounding rules and the reply checks\nof the first-evaluation note §4.1, `--dry-run` cost estimate from `rendered_tokens_qwen3`, then the 30-question\npilot. The contexts are read through `contexts.jsonl.gz`, whose `context_id` and `gold` go into the answer lines.\n\n## 9. Addendum (2026-10-21, after the user's review): `containment_merge` adopted\n\n**Decision (user):** `containment_merge` is the default selection rule, for the generator contexts and for\nthe headline legal-provision test (§7 item 1). `containment` stays as the Phase 1 variant\n(`eval/v2d_either_containment_skip`).\n\n- Code: default `dedup` of `select`, `EvalConfig`, `ContextConfig` and the `evaluate` / `context` CLI is\n `containment_merge`; default comparisons of `evaluate` are now the five pairs S1:S2, S2:S3, S2:S2c, S3:S4,\n S1:S2c. Tests updated (34 passed).\n- Rerun: `rag.py evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf --force` → headline\n `eval/either_containment_merge_skip` (with the five pairs); the context folder was rebuilt with the default\n sets + `oracle@budget=16000` (13 sets, no suffix; the `_dedup-containment_merge` and containment sets of §3–§4\n are gone, regenerable with `--dedup`). Consistency with the headline evaluation: 0 mismatches.\n- Headline article recall at 4k (budget view, all gold): S1 0.383, S2 0.495, S3 0.494, S2c 0.468, S4 0.468.\n Paired: S1 → S2 **+0.111** (CI 0.090–0.135), S2 → S3 −0.001 (n.s.), S2 → S2c −0.027 (CI −0.043 to −0.011),\n S3 → S4 −0.026 (CI −0.042 to −0.011), S1 → S2c +0.085. Under `containment` the caput variants lost ≈ 0.04 to\n their base strategies; under merge ≈ 0.027.\n\n**Budget fill rule (user question).** Texts are taken in rank order and never truncated. With\n`overflow=skip` (default) a text that does not fit the remaining budget is passed over and filling continues\nwith lower-ranked texts that do fit; scanning ends when no remaining candidate fits (the suffix minimum of the\ntoken counts) or the 1,000 ranked texts are used up. With `overflow=stop` filling ends at the first text that\ndoes not fit. A merged parent needs only its tokens minus those of the children it replaces. The context is\ntherefore never above the budget, and slightly below it:\n\n| Set | Unused budget: mean / median / max | Deepest rank used: median / p90 / max | Tokens from texts ranked > 50 |\n|---|---|---|---:|\n| S1 2k | 15 / 13 / 55 | 21 / 213 / 962 | 1.0 % |\n| S1 4k | 16 / 13 / 59 | 28 / 227 / 962 | 0.6 % |\n| S2 4k | 16 / 14 / 66 | 36 / 333 / 996 | 1.4 % |\n| S4 4k | 17 / 13 / 71 | 48 / 372 / 986 | 4.0 % |\n| S2 8k | 16 / 14 / 85 | 63 / 374 / 997 | 6.2 % |\n\nThe budget counts only chunk texts (`n_tokens_qwen3`); the rendered context with headers is 10–17 % larger\n(§3.2). The deep-rank fillers are small texts (often < 100 tokens) that close the last gap; `overflow=stop`\nwould avoid them at the cost of less filled contexts, probably more so for S1, whose texts are longer\n(not measured).\n\n## 10. Addendum (2026-10-22): `context_v2` adopted\n\n**Why** (user question on §7 item 3): `context_v1` repeats the document identification twice per block: in the\nheader (9.5–11 % of the rendered tokens at 4k) and in the chunk's `[ Epígrafe | Ementa ]` prefix (17.8–23.4 %);\ntogether **≈ 30 %** of the prompt (S1 30.9 %, S2 34.5 %, S4 29.7 %, oracle 26.0 %; Qwen3 tokens). The template\nenters every generation request, so it had to be fixed before the pilot. **Decision (user): `context_v2`**, the\ndefault of `rag.py context`.\n\n**Rule.** The segmentation writes one prefix per file: `[ epígrafe | ementa ]` or `[ epígrafe ]` in a main file\n(453 files; the first field equals the `documents.jsonl` title wherever there is one), `[ epígrafe | ementa |\nannex label ]` in an annex (172 files); the only irregular one is the DIAT page (`[ urn | name ]`, §6). `context_v2`\nremoves the prefix from `{texto}`; the epígrafe is in the header already, the **annex label replaces \"Anexo\"** in\nthe header, and the **ementa is shown once per document** (`Ementa: …` line on its first block in the context;\nskipped when it equals the title, as for DIAT). The selection is unchanged: the budget counts the full chunk text,\nso the contexts hold the same texts as the evaluation (0 mismatches on the 9 retrieval sets after the rebuild).\n\n| Set | Text tokens (budget) | Rendered, `context_v1` | Rendered, `context_v2` |\n|---|---:|---:|---:|\n| S1 4k | 3,984 | 4,447 | **3,812** |\n| S2 4k | 3,984 | 4,532 | **3,814** (−16 %) |\n| S4 4k | 3,983 | 4,456 | 3,867 |\n| S2 8k | 7,984 | 9,035 | 7,505 |\n| oracle 4k | 2,062 | 2,265 | 1,965 |\n| oracle 16k | 4,979 | 5,443 | 4,621 |\n\n(v1 figures are those of the merge sets of §9.)\n\n**Pilot ablation:** `S2_budget4000_context_v1` (S2 4k rendered with `context_v1`) is kept next to the 13 default\nsets, so the pilot can compare the two templates on the same texts (≈ 30 calls per generator).\n\n**Code:** `prompts/context_v2.pt.md` (new; placeholder `{ementa}`); `context.split_prefix`, `Template.per_document_ementa`,\n`source_label(…, annex_label)`; `contexts.describe` renders per template and tracks the documents already shown;\n`ContextConfig.template` / `--template` default `context_v2`. Tests: 35 passed.\n\n**Seen in the review sample:** the ementa parsed for Solução de Consulta Cosit 15/2016 is \"(Republicação - publicação\nanterior em 11 de abril de 2016)\" (a parsing quirk of that document, harmless); RIR/2018 annex blocks read \"Anexo 1 –\nANEXO\" (the annex has no title of its own).\n","20261022_203625_corpus_exclusion_revoked_rir1999.md":"# Corpus exclusion of the revoked RIR/1999 and audit of other revoked documents\n\n**Generated:** 2026-10-22 20:36:25 (local time, from `date +%Y%m%d_%H%M%S`).\n**Origin:** the user's hand review of the pilot contexts (Q350, Q503, Q676; RAG Phase 2 gate,\n`docs/20261021_210251_rag_phase2_contexts_execution.md` §5) found the RIR/1999 (Decreto nº 3.000, de 1999) next\nto the RIR/2018 in the contexts, often ranked above it, although the P&R cites the RIR/1999 only once,\nhistorically.\n**Decision (user, 2026-10-22):** exclude it from the retrieval corpus. **Rule:** revoked documents are not part of\nthis experiment (it is about segmentation, not about telling revoked from current law).\n**Done:** the exclusion mechanism, the exclusion of `decreto_3000_19990326`, and the reruns of retrieval,\nevaluation and contexts (§2–§3), with the previous corpus kept as an ablation run. **Open:** the other revoked\ndocuments found by the audit (§4) — **decisions for the user**.\n**Cost:** $0 (no API call, no re-embedding).\n\n## 1. Analysis\n\n### 1.1 How the RIR/1999 entered the dataset\n\n- One reference: `282-12`, **embedded**, `Decreto nº 3.000, de 1999, art. 39, § 6º`. In the answer of Q282 it appears only\n inside a quoted thesis of a PGFN dispensation (Parecer SEI nº 110/2018/CRJ/PGACET/PGFN-MF, Despacho nº\n 348/2020): \"por força do art. 6º, XIV, da Lei nº 7.713, de 1988, do art. 39, § 6º, do Decreto nº 3.000, de 1999,\n e do art. 6º, § 4º, III, da IN RFB nº 1.500, de 2014, a isenção … estende-se ao resgate …\". The rules in force are in\n Lei 7.713 and IN RFB 1.500, both in the corpus.\n- The gold nuggets do not depend on its text: it appears only in the `legal_basis` of `Q282_N03`, next to five other\n sources; the nugget's content is the PGFN dispensation.\n- It was revoked as a whole by the Decreto nº 9.580, de 2018 (the RIR/2018, in the corpus). The source `.docx` says\n so in its header (\"Revogado pelo Decreto nº 9.580, de 2018\").\n\n### 1.2 Its weight in the corpus and in the contexts\n\nIt brought 6,960 chunk rows (1,036 S1 units, 6,403 S2 units) — 5 % of the S1 index, about the size of the RIR/2018\nitself (1,141 S1 units) — for a single embedded citation. Contexts of the run before the exclusion (merge selection,\n`context_v2`):\n\n| Set | Contexts with RIR/1999 | With RIR/2018 | RIR/1999 above RIR/2018, or alone | RIR/1999 share of context tokens |\n|---|---:|---:|---:|---:|\n| S1 4k | 379 | 342 | 286 | 9.3 % |\n| S2 4k | 463 | 469 | 306 | 10.3 % |\n| S4 4k | 451 | 459 | 292 | 12.0 % |\n| S2 8k | 571 | 574 | 357 | 9.6 % |\n\nA revoked near-duplicate of the current regulation (same rules, other article numbers, sometimes outdated\nvalues) took ≈ 10 % of every context budget and outranked the current text in ≈ 300 of 715 contexts: noise for\nthe segmentation comparison, and a source of the temporal misgrounding studied in\n`docs/20260929_111356_fiscalqa_pro_temporal_misgrounding_comparison.md`.\n\n### 1.3 Why exclude rather than delete\n\n- The reference is real: the dataset (`references.jsonl`, `documents.jsonl`) keeps it.\n- Deleting its chunks would change the chunk file's SHA-256, which the embedding manifests pin, so the vectors\n would have to be re-finalized or recomputed. An exclusion only removes its texts from the candidates.\n- It is reversible and gives a free ablation (§3).\n\n## 2. Implementation\n\n| File | Change |\n|---|---|\n| `scripts/rag/corpus_exclusions.yaml` (new) | The list: `decreto_3000_19990326` (rule `revoked`, revoked by Decreto 9.580/2018 art. 4º, superseded by `decreto_9580_20181122`, cited by 282-12), the rule, the decision date |\n| `scripts/rag/ragpipe/exclusions.py` (new) | `Exclusions`: load from the YAML or from a retrieval manifest; chunk-row mask of the excluded documents (main and annex files); unknown document ids are an error |\n| `ragpipe/retrieval.py` | Reads the list (default file; `--exclusions none` or another path), drops the excluded rows from every strategy index, records `corpus_exclusions` (path, SHA-256, documents, rows) in the manifest and the parameters (config hash); new `--run-name` (output `runs/retrieval/<embedding>/<run name>`, default the instruction) |\n| `ragpipe/strategies.py` | `build_index(…, exclude=)`, applied after the expected-rows check (which describes the chunk file) |\n| `ragpipe/evaluation.py` | Takes the exclusions from the retrieval manifest; excluded rows are not in any strategy; gold items of an excluded document get `unreachable_reason = excluded_from_corpus` (column `unreachable:excluded_from_corpus` in `reachability.csv`); the manifest lists the excluded documents |\n| `ragpipe/contexts.py` | Oracle candidates without excluded rows; output root `runs/contexts/<embedding>/<retrieval run name>` |\n| `rag.py`, `ragpipe/data.py` | `retrieve --run-name --exclusions`; `Paths.exclusions` |\n| `tests/test_exclusions.py` (new), `conftest.py`, CLI tests | Excluded document absent from rankings and oracle, gold reported as excluded, run-name directories, unknown id error; fixture paths use no exclusion list. **37 passed** |\n\nCommands (`/tmp/…/scratchpad/rerun_exclusion.sh`, 10 min 20 s in total):\n\n```bash\nP=.venv/bin/python; R=scripts/rag/rag.py; SETS=<the 13 pilot sets of the Phase 2 note §10>\n# ablation: the corpus before the exclusion\n$P $R retrieve --embedding jua-4b-mixed --exclusions none --run-name irpf_with_rir1999\n$P $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf_with_rir1999\n$P $R context --retrieval runs/retrieval/jua-4b-mixed/irpf_with_rir1999 --sets \"$SETS\"\n# main run, with scripts/rag/corpus_exclusions.yaml\n$P $R retrieve --embedding jua-4b-mixed --force\n$P $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf --force\n$P $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf --dedup containment --eval-id v2d_either_containment_skip --force\n$P $R context --retrieval runs/retrieval/jua-4b-mixed/irpf --sets \"$SETS\" --force\n$P $R context --retrieval runs/retrieval/jua-4b-mixed/irpf --sets S2@budget=4000 --template context_v1 --force\n```\n\nChecks: the ablation run reproduces the previous headline exactly (S1 → S2 article recall +0.1113, the value of the\nPhase 2 note §9), so the code change does not alter a run without exclusions. Main run: 6,960 chunk rows excluded\n(S1 20,461 rows, S2 68,656, S3 72,061; candidate texts 20,422 / 68,501 / 71,906); contexts ↔ evaluation 0\nmismatches in both runs; no RIR/1999 chunk in any context; Q282's RIR/1999 gold item is `excluded_from_corpus` at\nthe three levels (1 item each).\n\n**Run layout now:**\n\n| Run | Corpus | Headline evaluation | Contexts |\n|---|---|---|---|\n| `runs/retrieval/jua-4b-mixed/irpf` | **without the RIR/1999 (main)** | `eval/either_containment_merge_skip`; Phase 1 rule `eval/v2d_either_containment_skip` | `runs/contexts/jua-4b-mixed/irpf/` (13 sets + `S2_budget4000_context_v1`) |\n| `runs/retrieval/jua-4b-mixed/irpf_with_rir1999` | as before (ablation) | `eval/either_containment_merge_skip` | `runs/contexts/jua-4b-mixed/irpf_with_rir1999/` (13 sets) |\n\nThe older evaluations in `irpf/eval/` (`either_containment_skip` of 2026-09-28, `v2c_…` of 2026-10-08) belong to\nearlier chunk files and are stale.\n\n## 3. Effect on the legal-provision test (budget view, all gold, merge selection)\n\n| Article recall | 2k: with → without RIR/1999 | 4k | 8k |\n|---|---|---|---|\n| S1 | 0.266 → 0.296 (+0.030) | 0.383 → **0.398** (+0.015) | 0.480 → 0.492 |\n| S2 | 0.402 → 0.425 (+0.023) | 0.495 → **0.503** (+0.009) | 0.587 → 0.600 |\n| S3 | 0.400 → 0.424 | 0.494 → **0.507** (+0.013) | 0.584 → 0.606 |\n| S2c | 0.372 → 0.391 | 0.468 → 0.480 (+0.012) | 0.567 → 0.579 |\n| S4 | 0.364 → 0.397 | 0.468 → 0.487 (+0.020) | 0.564 → 0.593 |\n\nProvision recall gains +0.011 to +0.034, document recall +0.008 to +0.033, article context precision +0.004 to\n+0.029; every strategy and budget improves. Paired comparisons, article recall at 4k:\n\n| Pair | With RIR/1999 | Without (main) |\n|---|---|---|\n| S1 → S2 | +0.111 (0.090–0.135) | **+0.105** (0.083–0.129), p < 0.001 |\n| S2 → S3 | −0.001 (n.s.) | +0.004 (−0.004–0.012, p = 0.34) |\n| S2 → S2c | −0.027 (−0.043 to −0.011) | −0.023 (−0.039 to −0.007), p = 0.006 |\n| S3 → S4 | −0.026 (−0.042 to −0.011) | −0.020 (−0.036 to −0.004), p = 0.014 |\n| S1 → S2c | +0.085 | +0.082 |\n\nThe conclusions do not change; S1 gains slightly more than S2 at small budgets (whole-article RIR/1999 units took\nproportionally more of an S1 context), so the S1 → S2 gap narrows by 0.006. The contexts now contain the RIR/2018\nin 474 of the S2 4k contexts (469 before).\n\n## 4. Audit: other revoked documents (rule of the user: revoked documents only)\n\n**Method** (`/tmp/…/scratchpad/revoked_audit.py`): the header of every source document (`original/`, text before\nthe first article or the first 1,500 characters) scanned for whole-document status notes — \"Revogado(a) pelo(a)\",\n\"Sem eficácia\", \"Perdeu a eficácia\", \"Vigência encerrada\", \"Convertida na Lei\", \"Rejeitada\"; the 12 PDF-sourced\nsoluções de consulta checked in `lexml/nao_articulados/_text/`. Planalto and the RFB normas site put these notes\nright under the epígrafe (e.g. \"[Revogado(a) pelo(a) Instrução Normativa RFB nº 2172, de 9 de janeiro de 2024]\").\nPartial revocations (single articles) are out of scope. 14 documents carry a note; 3 are false positives.\n\n### 4.1 Revoked as a whole before the P&R date (2024-05-03) — the rule applies\n\n| Document | Revoked by (date; in the corpus?) | References | Corpus size (S1 / S2 units) |\n|---|---|---|---|\n| `decreto_3000_19990326` (RIR/1999) | Decreto 9.580, 2018 (yes) | 1 embedded (Q282) | 1,036 / 6,403 — **excluded** |\n| `in_rfb_1548_20150213` (CPF) | IN RFB 2.172, 2024-01-09 (yes, `in_rfb_2172_20240109`) | **2 explicit** (Q058, Q059) | 99 / 422 |\n| `in_rfb_1717_20170717` (restituição, compensação) | IN RFB 2.055, 2021-12-06 (yes, `in_rfb_2055_20211206`) | **2 explicit** (Q053, Q074) | 242 / 1,046 |\n| `in_srf_118_20001228` (ganho de capital em moeda estrangeira) | IN RFB 2.180, 2024-03-11 (yes, `in_rfb_2180_20240311`) | 13: **11 explicit** (Q264, Q456, Q459, Q461, Q558, Q560, Q617–Q621, Q623) | 21 / 90 |\n| `in_srf_76_20010918` (restituição pela rede arrecadadora) | IN RFB 2.155, 2023-08-04 (**no**) | **1 explicit** (Q070) | 15 / 53 |\n| `ad_pgfn_1_20090327` | AD PGFN 2, 2016-03-10 (yes, `ad_pgfn_2_20160310`) | 2 embedded (Q230, Q316) | 2 / 2 |\n| `pn_cst_36_19770530` (despesas médicas) | ADE RFB 4, 2014-08-05 (no) | 1 embedded (Q364) | 9 / 9 |\n\n### 4.2 Not in force on 2024-05-03 for another reason (not \"revoked\")\n\n| Document | Status | References | Size |\n|---|---|---|---|\n| `mp_252_20050615` | \"Sem eficácia\": lapsed in 2005, not converted | 1 embedded (Q630) | 75 / 369 |\n| `mp_497_20100727` | converted into Lei 12.350, 2010 (in the corpus) | 1 embedded (Q248) | 36 / 169 |\n| `mp_670_20150310` | converted into Lei 13.149, 2015 (in the corpus) | 1 embedded (Q248) | 5 / 5 |\n\n### 4.3 Revoked after the P&R date — in force for the P&R, kept\n\n`in_rfb_1888_20190503` (criptoativos; revoked by IN RFB 2.291 of 2025-11-14; 4 references) and\n`in_rfb_2066_20220224` (Centro Virtual de Atendimento; revoked by IN RFB 2.320 of 2026-04-06; 3 references). The\ndocuments were fetched in 2026, so their headers show later revocations; they were in force on 2024-05-03.\n\n### 4.4 False positives\n\n`lei_13043_20141113` (\"Vigência encerrada\" refers to MP 1.303/2025, which amended it), `pn_cst_179_19700727` (its\ntext says another decree was revoked), `sc_cosit_75_20200625` (a body sentence: \"esse dispositivo não foi\nrevogado\").\n\n### 4.5 The difference with the RIR/1999, and the decisions for the user\n\nThe RIR/1999 case was clear-cut: a historical, embedded mention, a 5 % share of the corpus, and the current version\nin the corpus. **Four of the revoked documents are different: the P&R 2024 cites them as the explicit legal basis of\nits answers** (17 questions: IN RFB 1.548, IN RFB 1.717, IN SRF 118, IN SRF 76). The P&R was not updated after their\nrevocation (IN SRF 118 was revoked two months before the P&R date; Q617–Q623 cite it next to its replacement IN RFB\n2.180). Excluding them:\n\n- makes their gold items unreachable (`excluded_from_corpus`) in 17 questions, for the retrieval test and the\n legal-provision score of the answers;\n- leaves the generator only the replacement act for 16 of them (IN 2.172, 2.055, 2.180 are in the corpus; IN 2.155,\n the replacement of IN SRF 76, is not, so Q070 would lose its basis);\n- does not change the nuggets (they come from the answer text).\n\nTheir corpus weight is small (≈ 380 S1 units together, 1.8 % of the index), so keeping them biases the segmentation\ncomparison far less than the RIR/1999 did.\n\nDecisions:\n\n1. **Embedded / historical revoked documents** (`ad_pgfn_1_20090327`, `pn_cst_36_19770530`): exclude, like the\n RIR/1999 (same rule, 11 S1 units, 3 embedded references). **Recommended.**\n2. **Revoked documents the P&R cites as explicit legal basis** (`in_rfb_1548_20150213`, `in_rfb_1717_20170717`,\n `in_srf_118_20001228`, `in_srf_76_20010918`): **keep (recommended)** — they are the basis of the gold answers,\n and excluding them would remove the gold of 17 questions — and report them as a dataset property (the P&R cites\n revoked norms), with a slice in the results. The strict reading of the rule (exclude every revoked document)\n is the alternative; it is one line each in `corpus_exclusions.yaml` and a 10-minute rerun.\n3. **MPs no longer in force** (`mp_252_20050615` lapsed; `mp_497_20100727`, `mp_670_20150310` converted): not\n revoked, so outside the rule as stated; all three are embedded, single-question references. Recommendation:\n treat the lapsed MP 252 like a revoked document (exclude) and keep the converted MPs out of the rule (their text\n lives on in the conversion laws, both in the corpus, and they are tiny: 41 S1 units). Your call.\n\nWhatever is decided, the exclusion rule and the list go into the paper's corpus description, and the ablation run\n(`irpf_with_rir1999`) gives the with/without numbers.\n","20261023_110952_rag_phase3_generation_pilot.md":"# RAG Phase 3 — answer generation: implementation and pilot (`stratified_30`)\n\n**Generated:** 2026-10-23 11:09:52 (local time, from `date +%Y%m%d_%H%M%S`).\n**Implements:** RAG plan §7 (`docs/20260927_204356_rag_pipeline_implementation_plan.md`, stage G) and the grounding\nsafeguards of `docs/20261021_194457_first_rag_evaluation_readiness_costs_and_grounding.md` §4.1–§4.2, on the contexts\nof Phase 2 (`docs/20261021_210251_rag_phase2_contexts_execution.md`, main corpus without the RIR/1999,\n`docs/20261022_203625_corpus_exclusion_revoked_rir1999.md`).\n**User decisions (2026-10-23):** no further corpus exclusion (the revoked INs the P&R cites stay; §4.5 of the\nexclusion note closed as \"keep everything else\"); generators **Sabiá-4, Sabiazinho-4, GPT-5.6 Terra, GPT-5.6 Luna**;\n**oracle 4k and 16k** both run; reasoning effort **none** (the lowest level offered); answer format **option A**\n(claims with verbatim quotes); no output cap tighter than the default.\n**Cost:** **$5.59** in total (ledger `runs/costs.csv`, 1,489 calls): OpenRouter **$2.90** billed (Terra $2.65, Luna\n$0.25; the key's usage counter moved by $1.88 only, probably lagging; $32.51 left of the $100 limit), Maritaca\n**R$ 13.68** at list price (≈ $2.69 at R$ 5.08/US$; Sabiá-4 R$ 11.37, Sabiazinho-4 R$ 2.31). Estimate before the run:\n$13.53 at list price.\n**Status:** pilot done; **gate** (RAG plan §9: \"pilot answers read by hand; cost per full run estimated\") needs the\nuser's reading (§6); cost per full run in §5.\n\n## 1. What was built\n\n| File | Change |\n|---|---|\n| `scripts/llm_client/client.py` | `ToolUseDetected`: refuses a registry entry with `tools` / `plugins` / `web_search_options` / … or a `:online` model; rejects (no retry, ledger `finish = rejected:<reason>`) a reply with tool calls, `url_citation` annotations, `web_search_sources` or `usage.tool_execution_details` (Maritaca), `server_tool_use`, or — opt-in `check_billed`, used by generation — a billed cost above the token cost. `temperature` passed on the OpenRouter and `openai_compat` routes; strict `json_schema` on `openai_compat`; ledger column `fx_brl_per_usd`; `request_key` / `is_cached`; `offline` mode (dry runs); `fake` provider (tests) |\n| `scripts/rag/llms.yaml` (new) | Generator registry (§2); DeepSeek V4 Pro / Flash present but `enabled: false` (other machine) |\n| `scripts/rag/prompts/answer_v1.pt.md`, `answer_closed_v1.pt.md` (new) | System part, a `<<<USER>>>` line, user part (§3) |\n| `scripts/rag/ragpipe/generation.py` (new) | Stage G: registry (BRL → USD), prompts, samples, run planning, `--dry-run` estimate, concurrent run loop on `llm_client`, grounding checks, `answers.jsonl` / `run.json` / `summary.csv` |\n| `scripts/rag/rag.py` | `generate`, `run --experiment`, `show-answers` |\n| `scripts/rag/experiments/pilot.yaml` (new) | The pilot grid (§4) |\n| `scripts/rag/tests/test_generation.py` (new) | 7 tests (outputs and checks, closed book, empty oracle skipped, cache rerun byte-identical with no new ledger row, dry run, budget stop and resume, configuration guard, disabled model, tool-use refusal, registry, CLI). **44 + 13 passed** (`scripts/rag/tests`, `scripts/llm_client/tests`) |\n| `scripts/rag/README.md`, `requirements.txt`, `.gitignore`, `CLAUDE.md` | Phase 3 documented; `runs/answers/**/{answers.jsonl,run.json,summary.csv}` versioned, `runs/answers/cache/` not |\n\n```bash\nP=.venv/bin/python; R=scripts/rag/rag.py\n$P $R run --experiment scripts/rag/experiments/pilot.yaml --dry-run # 56 runs, 1,640 calls, est. $13.53 list\n$P $R run --experiment scripts/rag/experiments/pilot.yaml --budget 18 # 5 min 53 s\n$P $R show-answers --run runs/answers/jua-4b-mixed/irpf/answer_v1/sabia-4/S2_budget4000 --questions 350\n```\n\nLayout: `runs/answers/jua-4b-mixed/irpf/<prompt>/<llm>/<context_id>/{answers.jsonl,run.json}`, run id\n`jua-4b-mixed/irpf/answer_v1/sabia-4/S2_budget4000`; `summary.csv` one row per run. A run folder refuses another\nconfiguration (prompt hash, generator settings, context set, checks version) unless `--force`; questions of other\nsamples already in `answers.jsonl` are kept, so the same runs grow from the pilot to all 715 questions.\n\n## 2. Generators (probed 2026-10-23)\n\n| Name | Route | Model | Settings | Price per 1M (list) |\n|---|---|---|---|---|\n| `sabia-4` | Maritaca direct (`chat.maritaca.ai/api`) | `sabia-4-2026-01-06` (accepted; `/models` lists only `sabia-4`; replies name `sabia-4`) | temperature 0, `max_tokens` 4000, strict `json_schema` | R$ 5 / R$ 20 (cached R$ 1,25) |\n| `sabiazinho-4` | Maritaca direct | `sabiazinho-4-2026-01-06` | same | R$ 1 / R$ 4 |\n| `gpt-5.6-terra` | OpenRouter, `only: openai/flex`, no fallbacks | `openai/gpt-5.6-terra` (snapshot `-20260709`) | reasoning effort `none` (offered: none, low, medium = default, high, xhigh, max; no `minimal`); **no temperature parameter** on any endpoint; `max_tokens` 4000 | $2 / $12; flex bills ≈ 57 % of list in the pilot |\n| `gpt-5.6-luna` | same | `openai/gpt-5.6-luna` (`-20260709`) | same | $0.20 / $1.20 |\n\n- Knowledge cutoff (OpenRouter catalog): GPT-5.6 **2026-02-16** — after the P&R date, so 2025–2026 law is in its\n training data; Maritaca publishes none.\n- **FX:** `fx_brl_per_usd: 5.08` (PTAX of 2026-10-16, found by web search on 2026-10-23), recorded in `llms.yaml`,\n each `run.json` and each ledger row; to be replaced by the rate of the billing date. The BRL prices stay in\n `run.json`. Maritaca night (22–06 BRT) and flex discounts are not modelled: the ledger is at list price.\n- No reply in the pilot showed tool use or a billed cost above its token cost (all 1,489 ledger rows `stop`);\n no reasoning tokens; no retries; served provider OpenAI on every GPT call.\n\n## 3. Prompt and reply format\n\n`answer_v1` (pt-BR): answer only from the numbered provisions; **reference date** exercício 2024 / ano-calendário\n2023 (the recommendation of `docs/20260929_111356_fiscalqa_pro_temporal_misgrounding_comparison.md` §5 item 4);\nclaims that, read in order, form the answer; each claim with one or more `{documento, trecho}` — a short (≈ 30\nwords) verbatim excerpt; legal provisions cited in the usual form in the claim text; no value, date, rate, law or\nyear absent from the provisions; a negative answer may rest on an exhaustive list or an unmet condition; answer\nthe supported part only; abstain (empty claims, `abstencao: true`) when nothing is supported. `answer_closed_v1`:\nthe same without documents, from the model's own knowledge (closed-book control).\n\nStrict schema `{afirmacoes: [{texto, fundamentos: [{documento, trecho}]}], abstencao}`. **The scored answer is the\nclaim texts joined by newlines**; no claim → the fixed sentence \"As disposições fornecidas não são suficientes para\nresponder à pergunta.\" (closed book: \"Não sei responder a esta pergunta.\"), `abstained: true`.\n\n**Changes made during the probes (Q350, Q012, Q676 on S2 4k, 18 calls, $0.09), before the pilot:**\n\n1. Quotes of whole articles (≈ 600 output tokens for Terra on Q350) → \"trecho curto (até cerca de 30 palavras) … Não\n copie artigos inteiros\": Terra's output fell to ≈ 220 tokens on the same questions.\n2. `abstencao` moved after `afirmacoes` in the schema (the model writes what the context supports before deciding).\n3. Rule 6 added (negative answers): both Sabiá models abstained on Q350 (\"sogro/sogra as dependents?\") with Lei 9.250\n art. 35 in the context — the answer is that the exhaustive list of dependents does not include them. With the\n rule both answer correctly. Many P&R questions are of this \"is X allowed? — no\" form.\n4. Quote check on words (punctuation ignored): Luna's quote of art. 35 failed on one missing comma.\n\n### 3.1 Grounding checks (no LLM, per answer)\n\n- **Quote status** per fundamento: `ok` (the quote's words appear contiguously and in order in the cited\n `[Documento n]` block; case, punctuation and spacing ignored; an ellipsis may skip text, the pieces then in\n order), `not_found`, `too_short` (< 3 words), `bad_document` (no such block). A claim is **grounded** when one of\n its quotes is `ok`.\n- **Values not in context:** R$, % and dates of the answer (`nuggetizer/values.py`) found in neither the context nor\n the question (a date without a year matches day and month).\n- `cited_chunk_ids` (document numbers → chunk ids) for the legal-provision score of phase 5.\n\n## 4. Pilot grid\n\n14 context sets × 4 generators × 30 questions (`stratified_30`): S1, S2, S3, S2c, S4 at 4k; S1, S2 at 2k and 8k;\nclosed book; oracle 4k and 16k; wrong context (S2 4k); `S2_budget4000_context_v1` (template ablation). 1,680 answer\nlines: **1,639 ok, 40 skipped** (the oracle of the 5 sample questions without resolved gold, × 2 oracle sets × 4\ngenerators), **1 error** (§6.6). ≈ 150 calls were cache hits (most oracle 4k and 16k prompts are identical: the\noracle of these questions fits in 4k).\n\n### 4.1 Per generator (all sets)\n\n| Generator | Abstention | Mean output tokens (max) | Quote `ok` | Claims grounded* | List USD | Billed |\n|---|---:|---:|---:|---:|---:|---:|\n| Sabiá-4 | 11.7 % | 622 (2,334) | 90.5 % | 85.0 % | 2.42 | R$ 11.37 |\n| Sabiazinho-4 | 7.3 % | 620 (1,997) | 87.3 % | 85.4 % | 0.49 | R$ 2.31 |\n| GPT-5.6 Terra | 9.3 % | 395 (1,389) | 99.4 % | 89.2 % | 4.95 | $2.65 |\n| GPT-5.6 Luna | 21.0 % | 338 (1,167) | 98.8 % | 91.7 % | 0.47 | $0.25 |\n\n\\* Over all claims, closed book (no quotes) included; on the retrieval sets the grounded share is 0.90–0.98\n(Maritaca) and 0.97–1.00 (GPT).\n\n### 4.2 Abstention rate by set\n\n| Set | Sabiá-4 | Sabiazinho-4 | Terra | Luna |\n|---|---:|---:|---:|---:|\n| S1 / S2 / S3 / S2c / S4 4k | 0.03 each | 0 | 0–0.03 | 0.10–0.17 |\n| S1 2k / S2 2k | 0.03 / 0.10 | 0 | 0 / 0.07 | 0.23 / 0.17 |\n| S1 8k / S2 8k | 0 / 0 | 0 | 0.03 / 0.03 | 0.20 / 0.13 |\n| closed book | 0.03 | 0 | 0 | 0 |\n| oracle 4k / 16k (25 questions) | 0.12 | 0.08 | 0.04 | 0.16 |\n| **wrong context** | **1.00** | **0.87** | **0.97** | **1.00** |\n| S2 4k with `context_v1` | 0.07 | 0 | 0.03 | 0.23 |\n\nMost retrieval-set abstentions are on questions whose gold articles are not in the context (e.g. Luna S2 4k: 3 of\n5); the oracle abstentions all have the gold in the context (Luna: Q023, Q039, Q350, Q705).\n\n### 4.3 Other measures\n\n- **Answer length** (non-abstained): ≈ 650–900 characters on the retrieval sets, growing with the budget for every\n generator (S1 2k → 8k: Terra 667 → 1,008; Sabiá-4 677 → 817). Length must be reported next to nugget recall.\n- **Values not in context** (retrieval and oracle sets): 7 answers in 1,350, **all false positives** (checked one by\n one): 6 values the context writes in words (\"quinze por cento\" for \"15%\", Q113 ×4; \"vinte por cento\", Q703 ×2) and\n one date written \"1° de janeiro de 1992\" with a degree sign (Q710): limits of the check (§6.3). Closed book: 20–47 % of\n the answers carry a value the question does not contain (expected: they come from the model's knowledge; the\n closed-book answers are the leakage reference).\n- **Bad document numbers:** 55 quotes in 1,639 answers, almost all Maritaca (a quote attributed to the wrong block,\n e.g. Sabiazinho Q012: the excerpt is in Documento 1, cited as Documento 4).\n- **`abstencao` true with claims:** 27 answers, all Sabiazinho-4 (partial answers flagged as abstentions). The flag\n is not used: an answer with claims counts as answered.\n\n## 5. Cost per full run (715 questions), from the pilot's billed cost per call\n\n| Grid | Sabiá-4 | Sabiazinho-4 | Terra (flex) | Luna (flex) | OpenRouter total |\n|---|---:|---:|---:|---:|---:|\n| one 4k retrieval run | $4.4–4.9 (R$ 22–25) | $0.9–1.0 (R$ 5) | $5.1–5.4 | $0.5 | $5.6–5.9 |\n| headline grid (5 strategies at 4k + closed book + oracle 4k) | $27.4 (R$ 139) | $5.5 (R$ 28) | $31.6 | $3.0 | **$34.6** |\n| the pilot's 11-run grid (§2.3 of the first-evaluation note) | $46.4 (R$ 236) | $9.4 (R$ 48) | $54.9 | $5.2 | $60.1 |\n| all 14 pilot sets | $58.8 (R$ 299) | $12.0 (R$ 61) | $69.4 | $6.6 | $76.0 |\n\nMaritaca at list price; its flex tier (−50 %) or the night discount (−30 %) would halve or cut these. Oracle and\nclosed-book runs over all 715 questions are slightly overestimated (119 questions have an empty oracle, and the\nper-call mean is used).\n\n**Against the budget:** the OpenRouter key has **$32.51 left** (limit $100, expires 2026-11-20). The headline grid's\ngeneration alone (**≈ $35**) does not fit, and phase 5 scoring adds ≈ $28–42 (primary nugget set, 28 runs) + ≈ $12\n(context support) + the cross-set scoring of S1 vs S2 (≈ $16–24). **The first full evaluation needs ≈ $90–115 on\nOpenRouter**, so the key limit must be raised (≈ $84 of prepaid credit was left behind it on 2026-10-21) before it\nstarts. The pilot measured GPT costs ≈ 30 % above the first-evaluation note's flex estimate (Terra $31.6 vs\n$22 for 7 runs), mostly from the longer output (quotes) and the flex discount being ≈ 43 % rather than 50 %.\n\n## 6. Observations and open items\n\n1. **Hand reading (gate):** I read Q350, Q012, Q676 (probes), Q503 and Q440 across generators and S1/S2 at 4k. The\n answers are on topic, follow the provisions, cite them in the usual form and quote correctly; Terra gave the\n gold provision for Q503 (IN SRF 83, art. 2º, VI, \"e\"), Sabiá-4 the same article with a wrong inciso (\"V\"), a\n citation error the legal-provision score will see. **To be read by the user:**\n `rag.py show-answers --run runs/answers/jua-4b-mixed/irpf/answer_v1/<llm>/<set> --questions <n>` on 3–5 pilot\n questions; suggested Q350, Q440, Q503, Q676, Q705.\n2. **\"Insufficiency\" claims.** Answers to partly supported questions often end with a claim such as \"As disposições\n fornecidas não estabelecem em qual ano-calendário…\" (Q440, Terra and Sabiá-4). It is honest and matches rule 7,\n but it is not content: the judge will mark it `not_support` for every nugget, so it does not inflate recall; it\n lowers precision-like measures, if any are reported.\n3. **Value check: spelled-out numbers and \"1°\".** The provisions write many values in words (\"quinze por cento\",\n \"vinte por cento\"), and some ordinals with a degree sign; the check compares digits and `º` only, so every flag\n of the pilot outside closed book is a false positive. Fix for phase 5 (pt-BR number words → digits, `°` as `º`,\n in the presence test). The closed-book rate is unaffected (no context).\n4. **The wrong-context control works, and its failures are off-topic answers, not leaks.** The 5 non-abstentions\n (Sabiazinho Q039, Q259, Q291, Q564; Terra Q039) answer the **donor question's** topic from the donor context\n (Q039 \"local de apresentação\" answered with book-expense deductions; Q291 \"indenização do locador\" with prizes in\n goods): the context is followed, the question is not. Nugget scoring will give them ≈ 0; report them as\n \"off-topic\" next to the abstention rate.\n5. **Luna abstains most** (10–23 % on retrieval sets, 4 of 25 oracle contexts with the gold in them): a generator\n trait that lowers its recall on every strategy alike; it does not bias the paired strategy comparisons, but the\n abstention rate must be reported per generator and set.\n6. **One error:** Sabiazinho-4, `S2_budget4000_context_v1`, Q291: the output reached `max_tokens` (4,000) and Maritaca\n rejected the truncated strict-schema reply with HTTP 400 (not retried; at temperature 0 a retry would loop again).\n Recorded in the answer line (`status: error`); scoring should count it as an empty answer. If it recurs in the\n full runs (it is 1 of 1,640 here), raise `max_tokens` for Maritaca to 8,000 in a new registry version.\n7. **`context_v1` vs `context_v2`** (S2 4k, same texts): abstention and grounding are similar (Luna abstains more\n with v1: 0.23 vs 0.17); the input is 14 % shorter with v2. The answer-score comparison needs phase 5.\n8. **Answer length grows with the budget** (§4.3); report it with every score.\n9. **Negative-inference questions in the oracle (user review, 2026-10-23).** Q350 (sogro/sogra as dependents; oracle\n = Lei 9.250 art. 35 only) and Q705 (compensation of tax withheld on financial investments; oracle = IN RFB 1.585\n art. 70, whose inciso II makes it \"definitivo, no caso de pessoa física\") have their gold fully in the oracle 4k\n context (1 and 2 texts, 736 and 1,342 tokens). The answers that read as \"no context\" were **abstentions**, not a\n pipeline error (`show-answers` did not print the context; it now does, with `--context` for the full text).\n Terra and Sabiazinho-4 answer both correctly (\"Não\"); Luna abstains on both; Sabiá-4 abstains on Q350 (it answered\n on S2 4k, whose context also holds the IN 1.500 and RIR/2018 lists) and answers Q705 with a **self-contradicting\n verdict** (\"Sim, … é definitivo … não havendo previsão de compensação\") — the verdict-flip case the Flash judge\n detects (96 % in the known-answer tests). Rule 6 of `answer_v1` reduced but did not remove abstention on answers\n that must be inferred from an exhaustive list or a definitive regime. Q440's oracle is empty because the question\n has no reference at all (its answer points to questions 229 and 439): correctly skipped.\n\n## 7. Next\n\n**Update (2026-10-23):** the budget, the trimmed grid adopted by the user, the staging and the S2 / S3 hypotheses are\nin `docs/20261023_120734_first_full_evaluation_budget_trimmed_plan_and_s2_s3_hypotheses.md`; it supersedes item 3.\n\n1. **User:** read the pilot answers (§6.1) — the Phase 3 gate.\n2. Nugget phase 5 `score` on the pilot answers (`assign_v2`, Flash), with the retrieval ↔ answer linkage (first-\n evaluation note §3.1, the `gold` coverage of each context line joins by `context_id` + `question_number`), the\n context-support call (§4.3 there), the value checks (with the fix of §6.3) and the legal-provision score from\n `cited_chunk_ids` and the claim texts; judge agreement on real answers.\n3. **Raise the OpenRouter key limit** (§5) before the first full evaluation; decide its grid (headline 7 runs per\n generator recommended; the wrong-context and `context_v1` controls on a subset).\n4. DeepSeek V4 from the other machine (`llms.yaml` entries to enable after a probe there).\n","20261023_120734_first_full_evaluation_budget_trimmed_plan_and_s2_s3_hypotheses.md":"# First full RAG evaluation — budget, trimmed plan, staging, and the S2 / S3 hypotheses\n\n**Generated:** 2026-10-23 12:07:34 (local time, from `date +%Y%m%d_%H%M%S`).\n**Context:** discussion of 2026-10-23 after the RAG Phase 3 pilot (`docs/20261023_110952_rag_phase3_generation_pilot.md`).\nIt sizes the first full evaluation against the OpenRouter budget, records the **trimmed plan the user chose**, the\nstaging, what the scoring (nugget phase 5) covers, and the analysis of the S2 / S3 hypotheses with the ideas kept\nfor later. Builds on `docs/20261021_194457_first_rag_evaluation_readiness_costs_and_grounding.md` (**first-evaluation\nnote**) and `docs/20261011_224049_gold_answer_nuggetization_plan_v2.md` (**plan v2**).\n**Status:** decisions and analysis only; no API call (three S1/S2/S3 16k context sets were built locally in the\nsession scratchpad, outside `runs/`, for §4.1).\n\n## 0. Decisions and open questions (2026-10-23)\n\n| # | Item | Status |\n|---|---|---|\n| D1 | **Trimmed grid** (§2) for the first full evaluation | **adopted by the user** |\n| D2 | Staged execution (§3), each stage sized with `--dry-run`, capped with `--budget`, ledger reviewed; stop and report on any overrun | adopted |\n| D3 | The 16k point and the extra Terra run of §4.4 | **not adopted now; kept in mind** (user) |\n| Q1 | Do the OpenAI, Gemini and Qwen (DashScope) accounts have their own budget, and how much? Decides whether to move GPT generation and/or the judge off OpenRouter (§1.2) | open (user) |\n| Q2 | Raise the OpenRouter key limit (now $100) to use the prepaid credit left | open (user) |\n| Q3 | Stage 0 (scoring of the pilot answers, ≈ $4–5) after the user's reading of the pilot answers | next |\n\n## 1. Budget\n\n### 1.1 Where the money stands\n\nThe whole experiment has **$150 prepaid on OpenRouter** (user). Used so far: **$67.49** (nuggetization and the RAG\npilot; key status 2026-10-23), so **≈ $82.5 of prepaid credit is left**; the key's $100 limit leaves $32.51 of it\nusable until the limit is raised (Q2). Maritaca is billed separately in BRL and is not part of the $150.\n\nThe first-evaluation note's full first evaluation (4 generators × 7 headline runs, scoring with all extras) needs\n**≈ $90–115** at OpenRouter flex prices (pilot measurements, Phase 3 note §5): it does not fit.\n\n### 1.2 Splitting across keys moves the cost, it does not reduce it\n\nOpenRouter already uses the half-price flex endpoints for GPT and Gemini; OpenAI's own flex tier / Batch API and\nGemini's Batch API are also ≈ half of the list price. So the total is about the same whichever account pays; a split\nhelps only if the other accounts have their own money (Q1). If they do:\n\n- **GPT generation (≈ $35 of the full plan) → `OPENAI_API_KEY`.** The client already has the `openai` provider\n (Responses API, `reasoning_effort`, strict schema) and batch support (`llm_client/batch.py`); `rag.py generate` needs\n the flex `service_tier` or batch mode wired in. `OPENAI_API_KEY` is not in this machine's `.env`. The route enters\n the cache key and the run configuration, so **each generator keeps one route for the whole paper**: switching\n regenerates the 30 pilot questions of Terra and Luna (< $1).\n- **The Flash judge (the largest item, §3.1) → `GEMINI_API_KEY`** (in `.env`; used by the nugget preview and pilot,\n `--route direct`), synchronous or Batch API: OpenRouter would then be almost untouched.\n- **Qwen (DashScope)** is not needed for generation or scoring (the Qwen nugget set already exists); its best use is\n the second judge of the judge-agreement check on real answers (§3.1 item 4).\n\n## 2. The trimmed grid (D1)\n\n| Cut | Saves |\n|---|---:|\n| Terra only on S1 4k, S2 4k, closed book, oracle 4k; Luna, Sabiá-4, Sabiazinho-4 on all 7 headline runs (S1, S2, S3, S2c, S4 at 4k, closed book, oracle 4k) | ≈ $16 |\n| Cross-set scoring (Gemini and Qwen nugget sets) only for S1 vs S2 at 4k, on 2 generators | ≈ $8–12 |\n| Context-support calls on S1 4k, S2 4k, oracle 4k only | ≈ $6 |\n| Wrong-context and `context_v1` controls kept at pilot size (`stratified_30`) | — |\n\n**Total ≈ $58–75** (OpenRouter prices), within the ≈ $82.5 left even if everything stays on OpenRouter; with GPT on\nOpenAI and the judge on Gemini (Q1), OpenRouter keeps a reserve. S3, S2c and S4 are **not** dropped: only Terra, the\nexpensive generator (≈ $5.2 per 4k run + scoring), is limited to S1 / S2, the main hypothesis, as the strong-model\ncheck. Maritaca across all stages: ≈ R$ 170 at list price (its flex −50 % and night 22–06 BRT −30 % discounts: to be\nconfirmed with one call whether flex can be requested through the API).\n\n## 3. Staging (D2)\n\n| Stage | Content | Estimate |\n|---|---|---:|\n| 0 | Nugget phase 5 `score` on the pilot answers: measures the real cost per scored answer (scoring is the largest and least certain item) | ≈ $4–5 |\n| 1 | Core result: S1 vs S2 at 4k + closed book + oracle 4k, all 715 questions, 4 generators, generated and scored | ≈ $30–35 |\n| 2 | S3, S2c, S4 at 4k (Luna, Sabiá-4, Sabiazinho-4) | ≈ $15–20 |\n| 3 | Budget sweep: S1 / S2 at 2k and 8k, Luna and Sabiazinho-4 only, or on `stratified_70` (see §4.4 for the alternative 16k point) | ≈ $5–8 |\n| 4 | Cross-set scoring, robustness; DeepSeek V4 later from the other machine (cheap) | ≈ $10–15 |\n\nBefore each stage: `--dry-run`, then `--budget` set to the stage's estimate, then the ledger (`runs/costs.csv`, and\nthe nugget ledgers) reviewed; any overrun stops the work and is reported (CLAUDE.md rule).\n\n### 3.1 What the scoring covers (nugget phase 5)\n\n**Paid (LLM calls):**\n\n1. **Answer assignment — the main cost.** Gemini 3.8 Flash (`assign_v2`, medium reasoning) reads the question, all\n gold nuggets of the question and one system answer, and labels each nugget `support` / `partial_support` /\n `not_support` / `contradicts` with a short justification (plan v2 §5.2). One call per answer and nugget set, i.e.\n 715 per run → V_strict (headline), V, A_strict, A, W, contradiction rate (§5.3). ≈ **$1.0–1.5 per run and nugget\n set**, dominated by the judge's reasoning tokens; the judge does not read the context, so the cost does not grow\n with the context budget.\n2. **Cross-set scoring (robustness):** the same assignment against the second (Gemini 3.1 Pro) and third (Qwen3.8-Max)\n nugget sets, so no conclusion depends on the nugget creator. Each extra set costs as much as item 1.\n3. **Context support** (first-evaluation note §4.3; new prompt `assign_ctx_v1`): the judge assigns the gold nuggets\n against the **context** instead of an answer. Gives which nuggets each context holds → answer recall relative to\n what the context allowed (utilisation), a per-nugget leakage measure (nuggets supported by the answer but not by\n its context), and the size × strategy test of §4.3. One call per question and context set, shared by all\n generators: ≈ **$2 per context set** (it reads the 4k context).\n4. **Judge agreement on real answers** (the deferred part of nugget phase 4): a second judge on a sample of answers;\n small; candidate for the Qwen key.\n\n**Free (scripts):** value checks (plan v2 §5.4: value hit, value conflict, temporal substitution; with the fix for\nspelled-out numbers and \"1°\" of the Phase 3 note §6.3), the legal-provision score of the answers' citations (§5.5;\n`cited_chunk_ids` + `scripts/dataset/citations.py` on the claim texts), the retrieval ↔ answer linkage\n(first-evaluation note §3.1), paired and chapter-cluster bootstraps, the robustness analyses (§5.6), the known-answer\ntests (§5.7).\n\n**In the trimmed plan:** primary set on 25 runs ≈ $25–38; cross-sets on 8 runs ≈ $8–12; context support on 3 sets\n≈ $6; stage 0 ≈ $4–5 — **≈ $43–61 of the ≈ $58–75 total**: scoring, not generation, is the largest part.\n\n### 3.2 Why Gemini 3.8 Flash is the judge (reminder)\n\nPlan v2 D2 (2026-10-11), confirmed in nugget phase 4 (`docs/20261021_155704_nuggetization_phases_2_to_4_execution.md`\n§2.5; `docs/20261013_103834_nuggetization_open_decisions.md` §3):\n\n1. **Another family than the nugget creator.** The primary nugget set is GPT (`gpt-6.1-sol`); a GPT judge could\n favour answers phrased like its own nuggets (plan v2 §6.2). Candidates were therefore Gemini and an open-weight\n Qwen; Qwen3.8-Max was excluded (it created the third nugget set and is not cheaper than Gemini, plan v2 D11, §6.4).\n2. **Cost.** Flash was the Gemini candidate; Gemini 3.1 Pro would replace it only with a balanced accuracy > 0.05\n higher on the known-answer tests.\n3. **Selected by the known-answer tests** (3,354 tests: corrupted gold answers, wrong-question and empty answers):\n Flash and 3.1 Pro both reached **99.0 % balanced accuracy**, and Flash caught **96 % of flipped verdicts**\n (\"Sim\" ↔ \"Não\") against **67 %** for Pro (6 of 9 missed: Pro reconciled a flipped \"Não\" with the affirmative\n body); Flash detection: value ± step 97 %, corpus value of another year 100 %, year 99 %.\n\nThe open-weight Qwen judge (plan v2 D4) was left out at the user's request.\n\n### 3.3 What the scoring contributes to the segmentation analysis\n\nThe scoring is **not mainly a robustness measure of the nuggetization**: it is **how answer quality is measured**,\nthe dependent variable of the answer-level experiment. Without it the paper has only the retrieval test, which shows\nthat S2 *retrieves* the gold provisions better than S1, not that it *answers* better.\n\n| Part | Contribution to the segmentation analysis | Role | Trimmed-plan cost |\n|---|---|---|---:|\n| Answer assignment, primary nugget set | The headline outcome: V_strict per strategy × generator → the paired S2 − S1 (and S3 − S2, S2c − S2, S4 − S3) answer-quality differences, each strategy against the closed-book and oracle bounds, and the contradiction rate, which tests the hypothesis that S2 inciso chunks, isolating one period's value, give fewer wrong-year answers than S1 article chunks mixing several years' tables (plan v2 §5.4, temporal substitution) | **core**: the dependent variable | ≈ $25–38 |\n| Context support (`assign_ctx_v1`) | Which nuggets each context holds → splits an answer difference into \"the context held more\" (retrieval) and \"the generator used what it had better\" (chunk form); tests the S3 \"explains better\" hypothesis and the size × strategy hypothesis (§4.2–§4.3); a per-nugget leakage measure | **core**, segmentation-specific | ≈ $6 |\n| Cross-set scoring (Gemini, Qwen nugget sets) | S2 > S1 does not depend on which model wrote the nuggets | robustness of the segmentation conclusion against nugget-creator bias | ≈ $8–12 |\n| Judge agreement on real answers | The conclusion does not depend on the judge | robustness | small |\n| Free: value checks, legal-provision score of the answers' citations, retrieval ↔ answer linkage | Segmentation-specific detail (citation accuracy comparable to the retrieval metrics; answer score by context state) | core | $0 |\n\nSo ≈ $31–44 of the scoring budget is the core measurement and only ≈ $8–12 is robustness, already trimmed to the one\ncomparison that matters most (S1 vs S2 at 4k, 2 generators).\n\n**No free substitute for the main assignment:** the value checks cover only nuggets carrying a value (R$, %,\ndates); rules, conditions and verdicts — most of the P&R — need a judge. **If the budget gets tight, cut in this\norder:** cross-set scoring (fewer runs, or `stratified_70` instead of all questions), then Terra's runs; the primary\nassignment and the context-support calls last.\n\n## 4. Why S1 / S2 at 4k, and the S2 / S3 hypotheses\n\n### 4.1 What the retrieval test says (main corpus, budget view, all gold, `either_containment_merge_skip`)\n\nArticle recall:\n\n| Budget | S1 | S2 | S3 | S2c | S4 |\n|---|---:|---:|---:|---:|---:|\n| 2k | 0.296 | 0.425 | 0.424 | 0.391 | 0.397 |\n| 4k | 0.398 | 0.503 | 0.507 | 0.480 | 0.487 |\n| 8k | 0.492 | 0.600 | 0.606 | 0.579 | 0.593 |\n| 16k | 0.574 | 0.674 | **0.693** | 0.652 | 0.669 |\n\nPaired differences (`comparisons.csv`):\n\n| Pair | Article recall | Provision recall |\n|---|---|---|\n| S1 → S2 | +0.10 to +0.14 at every budget (16k +0.099), p < 0.001 | +0.04 to +0.06, p < 0.001 |\n| S2 → S3 | ≈ 0, n.s., up to 8k; **+0.020 at 16k** (CI 0.010–0.030, p < 0.001) | +0.005 to +0.012 up to 8k (p 0.02–0.09); **+0.034 at 16k**, p < 0.001 |\n| S2 → S2c, S3 → S4 | −0.013 to −0.034, mostly significant | ≈ 0, n.s. |\n\n- **S1 vs S2 does not depend on the budget** (the earlier assumption that strategies converge at large budgets is\n wrong for retrieval): 4k is not special, but the middle of the range, cheap, and matched by the oracle 4k bound.\n- **S3 differs from S2 only at 16k**, as expected from how it works: it adds grouping chunks (whole sections,\n chapters; Tipos CAP, LIV, PRT, SBT, SEC, SSC, TIT), which are large and fit mostly in large budgets.\n- **S2c / S4 retrieve slightly worse at article level**, but the caput sentence is meant for the generator (readable\n paragraph chunks), so only answer scores can judge them; they stay in the grid.\n\nWhat S3's contexts hold (computed in the session; S2 / S3 16k sets built in the scratchpad):\n\n| | S3 4k | S3 16k |\n|---|---:|---:|\n| Share of context tokens from grouping chunks | 18.7 % | 26.1 % |\n| Questions with ≥ 1 grouping chunk | 415 / 715 (pilot 21 / 30) | 642 / 715 (pilot 28 / 30) |\n| Contexts identical to S2's | 299 / 715 (pilot 9 / 30) | 73 / 715 (pilot 2 / 30) |\n\n### 4.2 The hypotheses (user)\n\n- **S2 better than S1 through accuracy:** smaller units rank the specific provision better and more distinct\n provisions fit in the budget. Retrieval already supports it (+0.10 article recall); whether it becomes better\n answers is the main phase 5 result.\n- **S3 better than S1 (or S2) through context that explains the subject:** a grouping chunk brings neighbouring\n articles (definitions, conditions, exceptions). **The 4k comparison is the cleanest test of this mechanism:** S2 and\n S3 hold the gold equally often at 4k, but S3 spends ≈ 19 % of the budget on whole sections instead of isolated\n provisions, so an S3 − S2 answer difference at 4k comes from the **form** of the context, not from retrieval. The\n phase 5 decomposition (answer difference on questions with the same vs a different retrieval outcome, first-\n evaluation note §3.1) separates the two; at 16k both effects mix (S3 also retrieves more).\n- **Smaller generators may handle S3 worse** (more irrelevant text next to the relevant one): plausible\n (long-context distraction; `docs/20260929_111356_fiscalqa_pro_temporal_misgrounding_comparison.md` reports that\n whole-article prompting made long articles worse). Two caveats: S1 is noisy too (a whole article where one inciso\n matters); the cleanest context is S2's. And **the retrieval test cannot measure this noise:** its context precision\n counts every token of a chunk that contains any gold (`evaluation.py`, `gold_toks / total`), so a chapter holding one\n gold article counts as fully relevant — which is why it rates S3 the \"most precise\" (article level, 4k: S1 0.129, S2\n 0.145, S3 0.169; 16k: 0.058, 0.069, 0.124).\n\n### 4.3 How phase 5 tests the size hypothesis\n\nWith the context-support call (§3.1 item 3): for each generator, the share of the **context-supported** nuggets\nthat the answer recovers (utilisation). The hypothesis predicts that utilisation drops from S2 to S3 more for the\nsmall model of each pair than for the large one: the **interaction** (S3 − S2)_small − (S3 − S2)_large, within\nvendor (Sabiá-4 / Sabiazinho-4, Terra / Luna) — the reason the generators come in same-release size pairs. An\ninteraction needs far more data than a main effect; with 715 paired questions it may stay inconclusive, and should\nthen be reported with its confidence interval, not as \"no effect\".\n\n### 4.4 Ideas kept for later (D3)\n\n- **A 16k point instead of the 2k / 8k sweep in stage 3:** S2 and S3 at 16k for Sabiá-4 and Sabiazinho-4 (the\n within-family size contrast, off OpenRouter: ≈ R$ 125 for 2 runs each) and Luna (≈ $2.6); S1 16k optional (≈ $1.3\n Luna, ≈ R$ 12 Sabiazinho, ≈ R$ 50 Sabiá-4) for S1 → S2 at 16k; scoring ≈ $1–1.5 per run. The 16k S1 / S2 / S3\n contexts are built locally in about a minute (`rag.py context --sets S1@budget=16000,…`). The 2k / 8k sweep adds\n little now that S1 vs S2 is flat across 2k–8k.\n- **Terra on S3 4k** (≈ $5.4 + scoring), so the OpenAI pair also has an S2 vs S3 contrast.\n- **Terra at 16k** (≈ $14.5 per run), only if the cheaper generators show an S3 effect there.\n\n## 5. What the pilot says about these hypotheses (very little)\n\nNot scored yet; only the proxies, at 4k:\n\n| | Sabiá-4 | Sabiazinho-4 | Terra | Luna |\n|---|---|---|---|---|\n| Claims grounded (S1 / S2 / S3) | 0.92 / 0.95 / 0.98 | 0.90 / 0.93 / 0.97 | 0.99 / 0.99 / 1.00 | 1.00 / 0.98 / 0.99 |\n| Abstention (S1 / S2 / S3) | 0.03 / 0.03 / 0.03 | 0 / 0 / 0 | 0 / 0 / 0 | 0.10 / 0.17 / 0.17 |\n\nNo sign that the small models struggle with S3 at 4k: Sabiazinho-4's grounded share is in fact highest on S3. But a\nvalid quote shows that the model read the context, not that the answer is right or complete; 30 questions, 9 of them\nwith identical S2 / S3 contexts, cannot show a small difference; and stage 0 will give the first answer-level numbers,\nnot an answer to the size question, which needs the 715 questions.\n\n## 6. Next\n\n1. **User:** read the pilot answers (Phase 3 gate; suggested Q350, Q440, Q503, Q676, Q705); answer Q1, Q2.\n2. Stage 0: implement nugget phase 5 `score` (with the context-support call, the value-check fix and the linkage) and\n run it on the pilot answers; replace the scoring estimates of §3.1 with the measured cost.\n3. Stages 1–4 of §3, each sized and capped; revisit D3 after stage 2.\n","20261023_151928_rag_phase3_trimmed_full_generation.md":"# RAG Phase 3 — generation of the trimmed grid on all 715 questions (stages 1 and 2)\n\n**Generated:** 2026-10-23 15:19:28 (local time, from `date +%Y%m%d_%H%M%S`).\n**Implements:** the generation part of stages 1 and 2 of the trimmed grid adopted by the user\n(`docs/20261023_120734_first_full_evaluation_budget_trimmed_plan_and_s2_s3_hypotheses.md` §2–§3, D1/D2), after the\nuser's review of the pilot answers (`docs/20261023_110952_rag_phase3_generation_pilot.md`, Phase 3 gate).\n**Cost:** **$41.95** billed (ledger `runs/costs.csv`, 14,387 new calls): OpenRouter **$16.38** (Terra $14.15, Luna\n$2.23), Maritaca **$25.58 ≈ R$ 130** at list price (R$ 5.08/US$). Estimate from the pilot's cost per call: $47.9.\nLedger total since the start of RAG Phase 3: $47.54. OpenRouter key: **$65.18 left** of the $150 limit (2026-10-23\n15:19).\n**Status:** generation done; scoring (nugget phase 5) not started — stage 0 of the plan (scoring the pilot answers\nto measure the real scoring cost) is next.\n\n## 1. What was run\n\n| Experiment file | Sets (all 715 questions) | Generators | Runs | New calls | Billed | Time |\n|---|---|---|---:|---:|---:|---:|\n| `scripts/rag/experiments/full_stage1.yaml` | S1 4k, S2 4k, closed book, oracle 4k | Sabiá-4, Sabiazinho-4, Terra, Luna | 16 | 10,329 | $30.39 | 86 min |\n| `scripts/rag/experiments/full_stage2.yaml` | S3 4k, S2c 4k, S4 4k | Sabiá-4, Sabiazinho-4, Luna | 9 | 4,058 | $11.56 | 41 min |\n\n```bash\nset -a; . ./.env; set +a # rag.py does not read .env itself\nP=.venv/bin/python; R=scripts/rag/rag.py\n$P $R run --experiment scripts/rag/experiments/full_stage1.yaml --dry-run\n$P $R run --experiment scripts/rag/experiments/full_stage1.yaml --budget 43 # cap on the ledger total ($5.59 before)\n$P $R run --experiment scripts/rag/experiments/full_stage2.yaml --budget 56 # ledger total $35.98 before\n```\n\nThe runs grew the pilot folders (`runs/answers/jua-4b-mixed/irpf/<prompt>/<llm>/<set>/`): the 30 `stratified_30`\nanswers were reused from the cache. Stage 2 needed only 4,058 of 6,165 calls: S3 / S4 prompts identical to S2 /\nS2c ones (e.g. 299 S3 contexts are identical to S2's, plan note §4.1) are cache hits, so their answers are the same\nby construction. The controls (wrong context, `context_v1`) and the 2k / 8k / oracle 16k sets stay at pilot size.\n\nPer run (billed USD):\n\n| Set | Sabiá-4 | Sabiazinho-4 | Terra | Luna |\n|---|---:|---:|---:|---:|\n| S1 4k | 4.40 | 0.89 | 4.84 | 0.45 |\n| S2 4k | 4.30 | 0.84 | 4.67 | 0.45 |\n| S3 4k | 2.59 | 0.52 | — | 0.27 |\n| S2c 4k | 3.83 | 0.76 | — | 0.40 |\n| S4 4k | 2.46 | 0.49 | — | 0.26 |\n| closed book | 1.15 | 0.24 | 1.51 | 0.11 |\n| oracle 4k (596 questions) | 2.61 | 0.52 | 3.13 | 0.30 |\n\n## 2. Proxies (from `summary.csv`; no answer scores yet)\n\n| Set | Abstention: Sabiá-4 / Sabiazinho-4 / Terra / Luna | Claims grounded |\n|---|---|---|\n| S1 4k | 0.055 / 0.032 / 0.036 / 0.241 | 0.95 / 0.93 / 0.99 / 0.98 |\n| S2 4k | 0.034 / 0.027 / 0.035 / 0.168 | 0.94 / 0.95 / 0.99 / 0.98 |\n| S3 4k | 0.042 / 0.022 / — / 0.175 | 0.95 / 0.95 / — / 0.98 |\n| S2c 4k | 0.038 / 0.022 / — / 0.182 | 0.95 / 0.94 / — / 0.98 |\n| S4 4k | 0.053 / 0.024 / — / 0.190 | 0.95 / 0.94 / — / 0.98 |\n| closed book | 0.013 / 0 / 0 / 0.003 | — |\n| oracle 4k | 0.121 / 0.057 / 0.047 / 0.128 | 0.95 / 0.93 / 1.00 / 0.98 |\n\n- Luna abstains most on every set (as in the pilot); S1 → S2 lowers abstention for Luna (0.24 → 0.17) and Sabiá-4.\n- The oracle abstention is higher than the retrieval sets' for the Maritaca models and Luna: the negative-inference\n questions of the pilot note §6.9 (gold in the context, answer to be inferred) at full scale.\n- All 14,387 ledger rows `stop`: no tool use, no billed cost above the token cost, served provider OpenAI on every\n GPT call.\n\n## 3. Errors: 6 truncated replies (Maritaca)\n\n6 of 16,669 answers are `status: error`, all `max_tokens_reached` (output reached 4,000 tokens; Maritaca rejects the\ntruncated strict-schema reply with HTTP 400 and returns no text, so the cause — a long answer or a repetition loop —\ncannot be seen; two of them broke off before `afirmacoes` was closed):\n\n| Generator | Set | Question |\n|---|---|---|\n| Sabiazinho-4 | S2 4k | Q659 |\n| Sabiazinho-4 | closed book | Q468, Q672 |\n| Sabiazinho-4 | S2c 4k | Q137 |\n| Sabiá-4 | S2c 4k | Q346, Q659 |\n\nNot billed (no ledger row). Scoring counts them as empty answers (pilot note §6.6). Q659 fails twice: worth a look.\nOption, if the user wants them answered: a new registry version with `max_tokens` 8,000 for Maritaca and a rerun of\nthe failed questions only (the run folder's configuration guard requires `--force` or a new generator name).\n\n## 4. Next\n\n1. Stage 0: nugget phase 5 `score` on the pilot answers (implementation still to be done), then scoring of these\n 25 runs (≈ $25–38 primary set, plan note §3.1), context support on S1 / S2 / oracle 4k, cross-set scoring of S1 vs\n S2 on 2 generators.\n2. Stages 3–4 of the plan note (budget sweep or the 16k point of §4.4; DeepSeek V4 from the other machine).\n","20261023_210727_rag_phase5_scoring_and_analysis.md":"# Nugget phase 5 — scoring of the trimmed grid and the first full RAG analysis\n\n**Generated:** 2026-10-23 21:07:27 (local time, from `date +%Y%m%d_%H%M%S`).\n**Implements:** nugget phase 5 (plan v2 §5,\n`docs/20261011_224049_gold_answer_nuggetization_plan_v2.md`) on the 25 runs of the trimmed grid\n(`docs/20261023_151928_rag_phase3_trimmed_full_generation.md`): stage 0 and the scoring parts of stages 1, 2 and 4\nof `docs/20261023_120734_first_full_evaluation_budget_trimmed_plan_and_s2_s3_hypotheses.md` §3.\n**Cost:** **$55.96** billed (ledger `nuggets/scoring/costs.csv`, 22,096 ledger rows, 0 failed answers): stage 0 $4.28, primary\nscoring $29.94, context support $8.30, cross-set scoring $11.09, second judge $2.35. The plan note estimated\n$43–61. OpenRouter key: **$9.08 left** of the $150 limit (2026-10-23 21:07).\n**Update 2026-10-24:** §10 audits the context-support result of §4 (steps a–e, $3.86; key: $5.22 left).\n**Status:** scoring and the free analyses are done. Not done: stages 3 and 4 (budget sweep or 16k point;\nDeepSeek V4), plus the open items of §9.\n\n## 1. What was run\n\nAll judge calls use Gemini 3.8 Flash (`google-ai-studio/flex` on OpenRouter); the only exception is the second\njudge in §7.4. Commands (global options before the subcommand):\n\n```bash\nP=.venv/bin/python; N=scripts/nuggets/nuggets.py; A=runs/answers/jua-4b-mixed/irpf; C=runs/contexts/jua-4b-mixed/irpf\nO=\"--out nuggets/scoring --workers 24\"\n# stage 0: the 56 pilot runs (stratified_30) and context support on the 11 pilot context sets\n$P $N $O --sample stratified_30 --budget 6 score --runs \"$A/*/*/*\"\n$P $N $O --sample stratified_30 --budget 6 ctxsupport --contexts \"$C/*\"\n# primary scoring, 715 questions (28 outputs: the 25 runs + Terra's pilot-size S3/S2c/S4)\n$P $N $O --sample all --budget 45 score --runs \"$A/*/*/*\"\n# context support (S1, S2, oracle 4k) and the cross-sets (S1/S2 4k, Terra and Sabiá-4)\n$P $N $O --sample all --budget 58 ctxsupport --contexts $C/S1_budget4000 $C/S2_budget4000 $C/oracle_budget4000\nfor s in gemini-3.1-pro.rep0 qwen3.8-max.rep0; do\n $P $N $O --sample all --budget 58 score --set $s --runs \"$A/answer_v1/gpt-5.6-terra/S[12]_budget4000\" \"$A/answer_v1/sabia-4/S[12]_budget4000\"\ndone\n# second judge on stratified_70\n$P $N --out nuggets/scoring --sample stratified_70 --workers 12 --budget 57.5 score --judge gemini-3.1-pro \\\n --runs \"$A/answer_v1/gpt-5.6-terra/S[12]_budget4000\" \"$A/answer_v1/sabia-4/S[12]_budget4000\"\n# tables and analyses (no LLM)\nfor s in gold gemini-3.1-pro.rep0 qwen3.8-max.rep0; do $P $N --out nuggets/scoring --sample all scoretable --set $s; done\n$P $N --out nuggets/scoring --sample all analyze # ≈ 8 min\n```\n\n| Item | Calls | Billed | Estimate | Per call |\n|---|---:|---:|---:|---:|\n| Stage 0 (56 pilot runs + 11 pilot context sets) | 1,567 | $4.28 | $4–5 | $0.0023 / $0.0047 |\n| Primary scoring, 28 outputs × 715 | 13,238 | $29.94 | $25–38 | $0.0023 |\n| Context support, S1 / S2 / oracle 4k | 1,898 | $8.30 | $9.09 (plan: $6) | $0.0044 |\n| Cross-sets (Gemini 3.1 Pro, Qwen3.8-Max sets), 4 runs each | 5,133 | $11.09 | $12.1 (plan: $8–12) | $0.0022 |\n| Second judge (Gemini 3.1 Pro), `stratified_70` × 4 runs | 257 | $2.35 | ≈ $2.7 | $0.0091 |\n\nAnswers that are abstentions or errors are not sent to the judge: every nugget gets `not_support`. Identical\nanswers (S3 / S4 prompts that repeat S2 / S2c ones) are cache hits.\n\n**Code:**\n- `nuggets.py score | ctxsupport | scoretable | analyze`.\n- `nuggetizer/scoring.py`: per-question scores and the paired, permutation and chapter-cluster statistics.\n- `nuggetizer/analysis.py`: the analyses that need no LLM.\n- `nuggetizer/values.py`: `digits_for_words`, the fix for spelled-out numbers.\n- `prompts/assign_ctx_v1.pt.md`: the judge applied to the context instead of the answer.\n\n**Outputs:**\n- `nuggets/scoring/score/<set>/<judge>/<run_id>/` and `ctxsupport/<set>/<judge>/<context path>/`: `labels.jsonl`,\n `calls.jsonl`, `manifest.json`.\n- `tables/<set>/<judge>/<sample>/`: `runs.csv`, `comparisons.csv`, per-question tables, context-support tables.\n- `analysis/gold-v0-auto/gemini-3.8-flash/all/`: one CSV per analysis below.\n\n## 2. Answer scores (primary set, 715 questions)\n\nVital-nugget recall with strict credit (V_strict, the headline), plus V, A_strict, W, the share of answers that\ncontradict at least one nugget (\"contra.\"), abstention and answer length. Oracle 4k: the 596 questions with a\ngold provision in the corpus.\n\n| Generator | Set | V_strict | V | A_strict | W | contra. | abstained | chars |\n|---|---|---:|---:|---:|---:|---:|---:|---:|\n| Terra | closed book | **0.351** | 0.490 | 0.308 | 0.448 | 0.295 | 0.000 | 1,049 |\n| Terra | S1 4k | 0.325 | 0.456 | 0.284 | 0.419 | 0.092 | 0.036 | 740 |\n| Terra | S2 4k | 0.341 | 0.479 | 0.303 | 0.441 | 0.080 | 0.035 | 764 |\n| Terra | oracle 4k | 0.368 | 0.514 | 0.325 | 0.471 | 0.065 | 0.047 | 735 |\n| Sabiá-4 | closed book | 0.239 | 0.379 | 0.213 | 0.350 | 0.382 | 0.013 | 1,016 |\n| Sabiá-4 | S1 4k | 0.290 | 0.446 | 0.257 | 0.409 | 0.115 | 0.054 | 787 |\n| Sabiá-4 | S2 4k | **0.317** | 0.470 | 0.285 | 0.433 | 0.112 | 0.034 | 822 |\n| Sabiá-4 | S3 / S2c / S4 4k | 0.315 / 0.305 / 0.307 | | | | | | |\n| Sabiá-4 | oracle 4k | 0.319 | 0.462 | 0.278 | 0.422 | 0.091 | 0.121 | 706 |\n| Sabiazinho-4 | closed book | 0.177 | 0.327 | 0.159 | 0.300 | 0.380 | 0.000 | 1,030 |\n| Sabiazinho-4 | S1 4k | 0.267 | 0.427 | 0.241 | 0.395 | 0.139 | 0.032 | 722 |\n| Sabiazinho-4 | S2 4k | 0.272 | 0.439 | 0.242 | 0.403 | 0.119 | 0.027 | 683 |\n| Sabiazinho-4 | S3 / S2c / S4 4k | 0.277 / 0.286 / 0.287 | | | | | | |\n| Sabiazinho-4 | oracle 4k | 0.293 | 0.461 | 0.263 | 0.425 | 0.117 | 0.057 | 601 |\n| Luna | closed book | 0.259 | 0.420 | 0.220 | 0.378 | 0.266 | 0.003 | 672 |\n| Luna | S1 4k | 0.271 | 0.387 | 0.235 | 0.351 | 0.080 | 0.241 | 624 |\n| Luna | S2 4k | 0.299 | 0.424 | 0.261 | 0.388 | 0.085 | 0.168 | 692 |\n| Luna | S3 / S2c / S4 4k | 0.300 / 0.314 / 0.304 | | | | | | |\n| Luna | oracle 4k | 0.338 | 0.475 | 0.299 | 0.435 | 0.065 | 0.128 | 673 |\n\nWrong-context control: V_strict 0 for every generator, which is the expected result.\n\n## 3. Paired comparisons (V_strict, b − a, 714 questions)\n\n| Comparison | Luna | Terra | Sabiá-4 | Sabiazinho-4 |\n|---|---|---|---|---|\n| **S1 → S2 4k** | **+0.028** (0.008, 0.049) p .007 | +0.016 (−0.004, 0.037) p .11 | **+0.027** (0.007, 0.047) p .009 | +0.005 (−0.015, 0.025) p .63 |\n| S2 → S3 4k | +0.000 p .98 | — | −0.002 p .74 | +0.005 p .56 |\n| S2 → S2c 4k | +0.014 p .15 | — | −0.012 p .22 | +0.013 p .16 |\n| S3 → S4 4k | +0.005 p .66 | — | −0.007 p .44 | +0.010 p .30 |\n| closed book → S1 | +0.013 p .43 | −0.027 p .12 | **+0.051** p .003 | **+0.090** p < .001 |\n| closed book → S2 | **+0.041** p .011 | −0.010 p .56 | **+0.078** p < .001 | **+0.095** p < .001 |\n| S1 → oracle 4k (595) | **+0.044** p .002 | +0.014 p .33 | +0.005 p .69 | +0.009 p .52 |\n| S2 → oracle 4k (595) | +0.021 p .14 | +0.004 p .78 | −0.016 p .21 | +0.009 p .54 |\n\nThe intervals are 95 % paired-bootstrap CIs, and p is a paired permutation test. The chapter-cluster bootstrap\nagrees on S1 → S2: Luna (0.006, 0.052), Sabiá-4 (0.004, 0.047), Terra (−0.002, 0.037), Sabiazinho-4 (−0.010, 0.023).\nAll tables are in `tables/gold-v0-auto/gemini-3.8-flash/all/comparisons.csv`, for every metric.\n\n**Reading:**\n- **S2 answers better than S1 for all four generators, but the gain is small.** It is significant for Luna and\n Sabiá-4. With the other nugget sets it is significant for Terra as well (§7.3).\n- **S3, S2c and S4 add nothing measurable over S2** (all |diff| ≤ 0.014, none significant). The pilot hints of\n S3 / S2c gains were noise.\n- **Retrieval helps the Maritaca models and Luna, but not Terra.** Terra's closed-book score is as high as its\n RAG scores (0.351 against 0.341). At the same time, closed-book answers contradict at least one nugget in\n 27–38 % of the questions, against 8–14 % with retrieval. So retrieval mainly buys correctness rather than\n recall: Terra's closed-book recall partly comes from what it already knows about the P&R content.\n- **The oracle gives little.** With the cited provisions as context (within 4k tokens), V_strict reaches only\n 0.29–0.37. §4 and §5 give two reasons; §10 tests the first one.\n\n## 4. Context support (what the context holds)\n\nThe judge applies the same nuggets to the context instead of an answer (`assign_ctx_v1`). PGD/program\ninstructions missing from the texts count as `not_support`, and so does another period's value.\n\n| Context | Questions | V_strict | V | A_strict | contra. |\n|---|---:|---:|---:|---:|---:|\n| S1 4k | 715 | 0.397 | 0.509 | 0.372 | 0.025 |\n| S2 4k | 715 | 0.411 | 0.524 | 0.385 | 0.027 |\n| oracle 4k | 596 | 0.483 | 0.598 | 0.463 | 0.029 |\n\n- **The oracle context fully supports fewer than half of the vital nuggets, as judged.**\n - Measured: the article chunks of the cited provisions, cut to 4,000 tokens (80 % of the gold articles fit),\n judged by Flash with `assign_ctx_v1`.\n - Per nugget (595 questions): support 46.7 %, partial_support 20.1 %, not_support 32.7 %, contradicts 0.5 %.\n - Without PGD nuggets, and only on questions whose context holds every gold article and provision (804\n nuggets, 317 questions): 47.4 % / 22.0 % / 29.7 %.\n - This bounds the RAG answers of §2. Whether it reflects the P&R document (answers that go beyond, or cite\n other provisions than, the legal texts), the corpus, the 4k cut or the context judge was not tested when\n this section was written: §10 tests it.\n- **S2's contexts hold barely more than S1's** (+0.014 V_strict). The retrieval test's +0.10 article recall\n turns into little extra nugget content.\n\n## 5. Linkage and utilisation (`linkage_*.csv`, `utilisation_runs.csv`)\n\n**What the answer uses from the context** (vital nuggets, nugget level, S1 / S2 / oracle 4k):\n\n| Generator | Context supports | Utilisation P(ans support \\| ctx support) | Leakage P(ans support \\| ctx not_support) | Answer support not in context |\n|---|---|---|---|---|\n| Terra | 0.380 / 0.386 / 0.467 | 0.625 / 0.649 / 0.591 | 0.024 / 0.025 / 0.028 | 3.8 / 3.5 / 2.9 % |\n| Sabiá-4 | same contexts | 0.566 / 0.610 / 0.520 | 0.018 / 0.030 / 0.012 | 3.1 / 4.7 / 1.5 % |\n| Sabiazinho-4 | same contexts | 0.494 / 0.479 / 0.471 | 0.027 / 0.030 / 0.020 | 5.3 / 5.7 / 2.6 % |\n| Luna | same contexts | 0.546 / 0.557 / 0.541 | 0.018 / 0.016 / 0.017 | 3.3 / 2.8 / 1.9 % |\n\n- **Generators state only 48–65 % of the vital nuggets their context fully supports.** This is the second limit,\n after the ceiling of §4. Utilisation is higher on S2 than on S1 for three generators. It is *lower* on the\n oracle for all four: Luna abstains on more oracle questions, and so do the Maritaca models (pilot note §6.9:\n negative-inference questions).\n- **Leakage with retrieval is small.** 2–6 % of the answers' `support` labels are for nuggets the context does\n not support. RAG answers come from the context; recall from the model's own knowledge shows up only in closed\n book.\n- **Answer score follows the context.** Answer V_strict is 0.07–0.13 when the context supports no vital nugget,\n 0.26–0.34 when it supports some, and 0.54–0.72 when it supports all of them. The Spearman correlation between\n answer and context V_strict per question is 0.53–0.67.\n- **S1 → S2 decomposition** (552 questions with both scores): the context support changes in only 73 questions.\n - Where it improves (47), the answer gains +0.04 to +0.13.\n - Where it worsens (26), the answer loses −0.05 to −0.11.\n - **Most of the S2 gain comes from the 479 questions whose context support is unchanged**: Luna +0.024 of its\n +0.025, Sabiá-4 +0.009 of +0.016.\n\n So S2 helps the generator use what it gets (smaller, focused sub-unit chunks, more of the gold provisions:\n article recall +0.094 in those questions). It does not mainly help by bringing new facts into the context.\n\n## 6. Value checks and citations (no LLM)\n\n### 6.1 Value checks (plan v2 §5.4; `values_*.csv`)\n\nThere are 539 nuggets with values per run (R$, %, dates).\n\n- **The value-hit rate (0.19–0.44) is above the judge's `support` (0.06–0.21).** The value is often there while a\n condition of the nugget is missing.\n- **When the judge says `support`, the value is in the answer in 79–95 % of the cases.** The rest are\n paraphrases: \"fora do prazo\" for \"after 31/05/2024\", \"último dia útil de maio\".\n- **Overall judge–value agreement is 0.72–0.85.** This doubles as a free check of the judge.\n- **Value conflicts are rare: at most 1.1 % of the value nuggets, 1–6 per run.** A conflict is another value of\n the same kind in the answer sentence that restates the nugget, or the answer's only value of that kind.\n - The first, looser rule (\"any other value of the same kind\") flagged whole tables: a single 30 % in an answer\n flagged 11 rate nuggets of Q706.\n - Most of the judge's `contradicts` labels on value nuggets are therefore not value swaps (≤ 17 % are). They\n are verdicts, conditions and rules.\n - **The temporal-substitution hypothesis (S2 inciso chunks cause fewer wrong-year values than S1) cannot be\n tested.** There are only 0–4 temporal substitutions per RAG run (1–6 in closed book).\n- **The \"values not in context\" proxy of Phase 3, with spelled-out numbers and \"1°\" fixed, drops to 0–0.5 % of the\n answers** (it was up to 1.3 %). The remaining flags are real; closed book is excluded because it has no context.\n\n### 6.2 Legal-provision score of the citations (plan v2 §5.5; `citations_*.csv`)\n\nThe texts each answer cites (`cited_chunk_ids`) are scored against the gold provisions with the matcher of the\nretrieval evaluation. Precision is the share of cited (or retrieved) texts that touch a gold unit; it is a count\nshare, not the evaluation's token-weighted precision. 596 questions with gold, article level:\n\n| Generator | Texts cited (S1 / S2) | Cited recall S1 / S2 / oracle | Context recall S1 / S2 / oracle | Cited precision S1 / S2 | Context precision S1 / S2 |\n|---|---|---|---|---|---|\n| Terra | 2.2 / 2.5 | 0.296 / 0.351 / 0.559 | 0.398 / 0.503 / 0.803 | 0.362 / 0.400 | 0.103 / 0.122 |\n| Sabiá-4 | 3.1 / 3.7 | 0.330 / 0.417 / 0.568 | same | 0.320 / 0.331 | same |\n| Sabiazinho-4 | 3.6 / 4.1 | 0.346 / 0.415 / 0.627 | same | 0.284 / 0.299 | same |\n| Luna | 2.1 / 2.5 | 0.273 / 0.336 / 0.538 | same | 0.366 / 0.369 | same |\n\n- **Generators cite 66–86 % of the gold articles the context holds.**\n- **Their citations are about 3× as precise as the context.**\n- **S2 raises cited recall by 0.05–0.09 for every generator.** That is the retrieval gain carried into the answer.\n- Closed-book answers have no cited texts; scoring their in-text legal citations (`citations.py` + act\n attribution) was not done.\n\n## 7. Robustness\n\n### 7.1 Nugget subsets (`slices_comparisons.csv`, S1 → S2 V_strict)\n\n- **Without PGD nuggets** (613 questions), S1 → S2 is Luna +0.035 (p .003), Sabiá-4 +0.026 (p .022), Terra +0.019,\n Sabiazinho-4 +0.004. That is slightly larger than with them.\n- **PGD nuggets score low everywhere** (V_strict 0.11–0.30). The exception is Terra closed book, at 0.297.\n- **On temporal nuggets** (302 questions) the difference is −0.01 to +0.02 and not significant. Sub-article chunks do not\n help period-specific facts more than others (no support for the S2 temporal hypothesis).\n- **On `condicao` nuggets** (235) it is +0.004 to +0.015, not significant. The expected S2 advantage on conditions\n and exceptions does not show.\n- **Stable-only** (nuggets that all three families produced) and **not-audit-flagged** nuggets give the same\n results as the full set: Luna +0.028 / +0.033, Sabiá-4 +0.028 / +0.025, both significant.\n- **By chapter** (`chapters_s1_s2.csv`), S2 > S1 in 19–24 of 48 chapters per generator. No single chapter carries\n the gain. \"Aplicações financeiras\" is positive for all four (+0.02 to +0.13).\n\n### 7.2 Perturbed nugget sets (`perturbation_s1_s2.csv`, 1,000 replicates)\n\nShare of replicates in which S2 − S1 keeps its sign and stays significant (paired t, p < .05), V_strict:\n\n| Damage | Luna | Sabiá-4 |\n|---|---:|---:|\n| none | 1.00 | 1.00 |\n| random deletion 10 % / 15 % / 20 % | 0.95 / 0.89 / 0.78 | 0.97 / 0.93 / 0.86 |\n| random deletion 30 % / 40 % / 50 % | 0.60 / 0.48 / 0.32 | 0.79 / 0.68 / 0.60 |\n| vital ↔ okay flips 10 % / 20 % / 30 % | 0.95 / 0.79 / 0.65 | 0.97 / 0.90 / 0.81 |\n| all `condicao` nuggets deleted | 1.00 | 1.00 |\n| audit-flagged deleted; stable-only | 1.00; 1.00 | 1.00; 1.00 |\n\n- **The S2 − S1 result survives 15–20 % nugget damage**, the bar set by plan v2 §5.6. The break-even (< 50 % of\n replicates significant) is around 40 % random deletion for Luna and above 50 % for Sabiá-4.\n- **The sign is kept in every replicate.**\n- Terra: the difference is significant under A_strict (+0.019, p .036) but not under V_strict. It is fragile to\n deletion (0.34–0.64).\n\n### 7.3 Cross-sets (`crossset_*.csv`; Terra and Sabiá-4, S1 / S2 4k)\n\n| Nugget set | Terra S1 → S2 | Sabiá-4 S1 → S2 |\n|---|---|---|\n| primary (GPT-6.1 Sol) | +0.016 (−0.004, 0.037) p .11 | +0.027 (0.007, 0.047) p .009 |\n| Gemini 3.1 Pro set | **+0.024** (0.004, 0.045) p .020 | **+0.023** (0.003, 0.043) p .022 |\n| Qwen3.8-Max set | **+0.026** (0.006, 0.047) p .010 | **+0.028** (0.008, 0.048) p .007 |\n\n- **Every difference keeps its sign and is significant under both other sets**, with the chapter-cluster CI above\n zero. Terra becomes significant.\n- **The ranking of the 4 runs is identical under the three sets** (Kendall τ = 1).\n- **The conclusion does not depend on the nugget creator.** The primary set is the most conservative of the three.\n\n### 7.4 A second judge on real answers (`judge_*_gemini-3.1-pro.csv`)\n\nGemini 3.1 Pro judged `stratified_70` × {Terra, Sabiá-4} × {S1, S2 4k}: 280 answers, 1,364 nugget labels.\n\n- **Agreement with Flash is 94.7 % on the four labels** (Cohen's κ 0.90), and κ = 0.93 for `support` against the\n rest.\n- **Disagreements sit on the boundaries.** 34 Flash `partial_support` labels are Pro `not_support`, 12 Flash\n `support` are Pro `partial_support`, and 10 Flash `contradicts` are Pro `not_support`. Flash is a little harsher\n on `contradicts` (2.4 % of labels against 1.6 %).\n- **Both judges give the same S1 → S2 direction and size on this sample**: Terra −0.020 (Flash) / −0.013 (Pro),\n Sabiá-4 −0.032 / −0.025, none significant at n = 70.\n- **The judge choice (D2) holds on real answers.**\n\n## 8. Conclusions of the first full evaluation\n\n1. **Hierarchical segmentation (S2) gives better answers than article chunks (S1), but by little:** +0.02 to\n +0.03 V_strict. The gain is significant for Luna and Sabiá-4 on the primary set, and for Terra and Sabiá-4 on\n both other nugget sets. It is robust to nugget damage, chapter clustering and nugget subsets. Sabiazinho-4\n shows no gain.\n2. **The groupings and caput variants (S3, S2c, S4) add nothing over S2 at 4k.**\n3. **The gain is small because the answers are limited by two things that segmentation does not change:**\n - what the context holds of the P&R answers: about 47 % of vital nuggets fully supported even by the cited\n provisions within 4k tokens (§4). This rests on one context judge; how much of it reflects the P&R document\n itself is the subject of §10;\n - how much of the supported content the generator states (48–65 %, §5).\n\n S2's advantage comes mostly from better use of the context. It brings little extra content.\n4. **Retrieval mainly reduces contradictions** (27–38 % → 8–14 % of answers). It helps recall only for the weaker\n generators; Terra answers the P&R questions about as well from its own knowledge.\n5. **The temporal and condition hypotheses for S2 are not supported**: no extra gain on temporal or `condicao`\n nuggets, and value conflicts are too rare to test.\n\n## 9. Open items\n\n1. Stages 3 and 4 of the plan note: the 16k point (S2 / S3 for Sabiá-4 and Sabiazinho-4, plan note §4.4) or the\n 2k / 8k sweep, and DeepSeek V4 from the other machine. **$9.08 was left on the OpenRouter key ($5.22 after\n §10).** At the\n measured $0.0023 per scored answer, a 715-question run costs ≈ $1.6 to score, plus generation.\n2. The 6 truncated Maritaca answers (generation note §3) still count as empty. They change no mean by more than\n 0.003.\n3. Citation scoring of closed-book answers (in-text citations, act attribution).\n4. A human calibration sample (plan v1 §4.4): the 72 Flash–Pro disagreements of §7.4 are natural candidates.\n5. Commit the scoring outputs. Only `labels.jsonl`, `calls.jsonl`, manifests and the tables are small enough for\n git; `nuggets/scoring/cache/` is gitignored.\n\n## 10. Update (2026-10-24 01:58): do the cited provisions hold the P&R answers?\n\n**Question (user, after §4):** §4 found that the oracle context fully supports only about 47 % of the vital\nnuggets. Does that mean the legal texts the P&R cites do not hold much of what its answers state? If so, it is a\nfinding about the source document's consistency. It must then be shown that the result is not an artefact of the\noracle context, the corpus or the context judge.\n\n**What §4 had not ruled out:**\n- The 4k cut: only 80 % of the gold articles fit.\n- A single, untested context judge (`assign_ctx_v1` had no known-answer tests; Flash only).\n- Facts that sit in legislation the P&R does not cite.\n- Content in the nuggets that is not normative (PGD instructions).\n\nSteps a–e were run on `stratified_70`: the 57 questions with resolvable references, 212 vital nuggets.\n**Cost: $3.86** billed (617 calls, ledger `nuggets/scoring/costs.csv`); the OpenRouter key has **$5.22 left**.\n\nCommands:\n\n```bash\nP=.venv/bin/python; N=scripts/nuggets/nuggets.py; C=runs/contexts/jua-4b-mixed/irpf\nO=\"--out nuggets/scoring --sample stratified_70\"\n$P $N $O --budget 57 ctxsupport --contexts $C/oracle_budget16000 $C/wrong-S2_budget4000 # c, a (negative)\n$P $N $O --budget 58.5 ctxsupport --contexts $C/oracle_budget16000 --judge gemini-3.1-pro # b\n$P $N $O --budget 61 ctxaudit known # a: phase 4 tests + needle tests, judged with assign_ctx_v1\n$P $N $O --budget 61 ctxaudit corpus # d: corpus search for the unsupported vital nuggets\n$P $N $O --budget 61.5 ctxaudit classify # e: cause of each unsupported nugget (Gemini 3.1 Pro)\n```\n\nOutputs are in `nuggets/scoring/ctxaudit/gold-v0-auto/stratified_70/`: `known/`, `corpus/`, `classify/`, and\n`classify/review.csv` (the 60 unsupported nuggets, all the evidence, the classifier's cause and the reviewed\ncause). Code: `nuggetizer/ctx_audit.py`, `nuggets.py ctxaudit`, prompt `ctxaudit_classify_v1.pt.md`.\n\n### 10.1 (a) The context judge is reliable\n\nKnown-answer tests judged with `assign_ctx_v1`. The test text plays the role of the context: it is the gold\nanswer, corrupted as in phase 4 (§2.5 of the phases 2–4 note).\n\n| Test | Tests | Result |\n|---|---:|---|\n| G (gold answer as context) | 70 | 98.0 % of nuggets `support` |\n| V / VP / Y (value or year changed) | 14 / 3 / 14 | detected 100 % (`contradicts` 100 % / 100 % / 53 %; the rest `not_support`, as the period rule asks) |\n| N (verdict flipped) | 14 | 89 % |\n| D (span deleted) / C (condition removed) | 44 / 25 | 94 % / 80 % |\n| W (another question's answer) / E (empty) | 70 / 70 | 99.4 % / 100 % `not_support` |\n| **Pooled** | 324 | sensitivity 98.7 %, specificity 98.4 %, **balanced accuracy 98.5 %** |\n| Needle: the nugget's P&R source sentence appended to its 16k oracle context | 60 | `support` 65 %, `partial_support` 28 %, `not_support` 7 % |\n| Wrong context (`wrong-S2_budget4000`), real legal texts of another question | 70 | 99.1 % `not_support` (0 `support`) |\n\n- **The judge finds a fact that is in a long legal context.** The needle partials and misses are list fragments of\n the P&R answer that do not carry their own subject: \"Ganho apurado na alienação de imóveis adquiridos até\n 1969;\" is not, by itself, a statement that the gain is exempt.\n- **The judge does not invent support from unrelated legal text.**\n\n### 10.2 (b, c) The oracle context without the 4k cut, and a second judge\n\n`oracle_budget16000`: 94.5 % of gold articles fit (4k: 80 %). Vital nuggets of the 57 questions:\n\n| Context, judge | support | partial | not_support | contradicts |\n|---|---:|---:|---:|---:|\n| oracle 4k, Flash | 38.2 % | 17.5 % | 44.3 % | 0 |\n| **oracle 16k, Flash** | **50.5 %** | 20.8 % | 28.3 % | 0.5 % |\n| oracle 16k, Gemini 3.1 Pro | 49.5 % | 19.8 % | 30.2 % | 0.5 % |\n\n- **The 4k cut made the gap look bigger than it is.** On these questions the cut hid 12 points of support. Of the\n 212 labels, 41 moved up from 4k to 16k and 1 moved down (`support` → `partial_support`).\n- **Two judges give the same picture.** Flash and Pro agree on 86.6 % of the labels (κ 0.79; κ 0.79 on `support`\n against the rest), and the disagreements are between adjacent labels.\n- **So about half the vital nuggets are fully stated by the cited provisions, one fifth in part, and 28–30 % not\n at all.**\n\n### 10.3 (d, e) Why 60 vital nuggets are not supported\n\n**d. Corpus search.** For each unsupported nugget, the context was made of other texts:\n- the 4 texts a TF-IDF search on the nugget text ranks highest in the whole corpus, outside the cited articles;\n- plus the question's dense S2 retrieval, outside the cited articles.\n\nThe revoked RIR/1999 is excluded, as in the RAG runs. Flash then judged the nugget against that context: 13 of\nthe 60 are fully supported there and 15 partly.\n\n**e. Classification.** Gemini 3.1 Pro saw the question, the official answer, its references, the nugget, both\ncontexts and both judges' labels, and assigned one cause per nugget. I then read all 60 classifications against\nthe evidence, and changed 17 of them:\n- **12 `corpus_gap` → `oracle_gap`.** All are on Q560, Q326 and Q592, and the cited provision is in the corpus\n but not in the oracle context:\n - Q560 and Q326 cite 17 articles each and overflow 16k tokens: 6 and 11 of 17 fit.\n - Q592 lost part 1 of a split article (Lei 8.981 art. 21).\n - The cause is in the oracle construction: a cited document without article ids (mostly Soluções de\n Consulta) enters the context whole and uses up the budget.\n- **4 `interpretation` → `other_provision`** (Q271 ×3, Q165): the fact is stated in a Solução de Consulta of the\n corpus that the answer does not cite.\n- **1 `other_provision` → `interpretation`** (Q555_N02): no text in either context states it.\n\nThe classifier found no `judge_error` and no `nugget_problem`.\n\nShare of the 212 vital nuggets. The CI is a 95 % bootstrap over the 57 questions (clusters):\n\n| Reviewed class | Nuggets | Share | 95 % CI | Questions |\n|---|---:|---:|---|---:|\n| supported by the cited provisions | 107 | 50.5 % | 39.3–62.4 | |\n| partly supported | 44 | 20.8 % | 12.5–28.1 | |\n| `oracle_gap`: cited, in the corpus, not in our oracle context | 12 | 5.7 % | 0.0–12.7 | 3 |\n| `other_provision`: stated in another, uncited text of the corpus | 15 | 7.1 % | 3.0–12.4 | 10 |\n| `interpretation`: the Receita's application, combination or *a contrario* reading of the provisions | 20 | 9.4 % | 4.5–17.1 | 14 |\n| `pgd_practical`: program, form, field instructions | 8 | 3.8 % | 0.6–9.2 | 5 |\n| `not_in_legislation`: no basis in any corpus text (administrative position) | 5 | 2.4 % | 0.0–7.4 | 2 |\n| contradicts (not audited) | 1 | 0.5 % | | |\n\n**Examples:**\n- **interpretation:**\n - Q350: a parent-in-law is not a dependant unless the spouse files jointly. The law lists only \"pais\".\n - Q661: selling part of one's only property does not get the exemption for the \"único imóvel\".\n - Q604: a transfer of quotas between spouses under comunhão universal is not an alienação.\n- **other_provision:**\n - Q023: someone travelling on the deadline still has to file. This is Decreto-Lei 5.844/1943 art. 194, not\n cited.\n - Q267: late carnê-leão payments bear charges. This is IN RFB 1.500/2014 art. 107, not cited.\n - Q515: three rules of IN SRF 84/2001 arts. 9 and 19; the answer cites only art. 3.\n- **not_in_legislation:**\n - Q533: four rules on the treatment of rural-activity assets after the property is sold.\n - Q283: tax-exempt grants do not justify an increase in wealth.\n\n### 10.4 What this supports, and what it does not\n\n**Supported, on this sample:**\n- **Most of the vital content of a P&R answer is stated by the provisions it cites:** 50.5 % fully, 20.8 % in part.\n- **About one vital nugget in six (15.6 %, CI 8.2–25.7 %, in 20 of 57 questions) is not stated in any legal text\n of the corpus.** It is the Receita's own application of the provisions to the case (9.4 %), program\n instructions (3.8 %) or an administrative position (2.4 %).\n- **About one in fourteen (7.1 %) is stated in legislation the answer does not cite.** The P&R's citations are\n then incomplete for that fact.\n- **These conclusions do not depend on the context judge** (98.5 % balanced accuracy on known answers, needle and\n wrong-context controls passed, Flash and Pro agree), **nor on the 4k cut.**\n\nFor the RAG results this means the oracle ceiling is mainly the P&R document's own content beyond its citations,\nplus our oracle construction. It is not the judge.\n\n**Not yet supported:**\n- **Sample size and concentration:** 57 questions. Q560 alone has 12 of the 60 unsupported nuggets, so the CIs are\n wide.\n- **The 44 partly supported nuggets (20.8 %) were not audited.** They probably mix missing conditions,\n interpretation and the same `oracle_gap`.\n- **The causes come from one classifier plus my reading.** The legal calls — mainly `interpretation` against\n `not_in_legislation` — need a tax-law reader. `review.csv` has a `reviewed_cause` column for that.\n- **The corpus is the legislation the P&R cites anywhere, not all IRPF legislation.** `not_in_legislation` means\n \"not in this corpus\", and the corpus search is one lexical and one dense search, so a fact it missed could\n still exist.\n- **The oracle construction understates the cited content for questions with many references.** The same\n `oracle_gap` affects the oracle answer runs of §2–§3.\n\n**Next, to make it a paper claim:**\n1. Context support with the 16k oracle on all 596 questions (≈ $3.3, nearly all of the $5.22 left on the key).\n2. The same classification on the 44 partial nuggets (≈ $0.8).\n3. Your review of `review.csv` (60 rows; then the partials).\n4. An oracle that keeps all cited articles before whole uncited-article documents, or a larger budget, so that\n `oracle_gap` disappears. It is free to build; scoring it costs the same as item 1.\n","20261024_145130_slide_deck_first_full_evaluation.md":"# Slide deck: first full evaluation (rationale, method, results, robustness)\n\nDate: 2026-10-24. A 29-slide deck that presents the hierarchical-segmentation RAG experiment to\npeers and reviewers who know RAG, retrieval evaluation and LLM judges, but not this dataset or\nexperiment. It covers the state after the phase 5 scoring and analysis\n(`20261023_210727_rag_phase5_scoring_and_analysis.md`, including its §10 ceiling audit).\n\n- **Live deck (private until shared from the page's Share menu):**\n https://claude.ai/artifact/M7A2qaMUx4AHye6F6sNtTq (claude.ai Slides artifact; PDF / PPTX export\n from the page).\n- **Copy in the repo:** `docs/slides/20261024_145130_first_full_evaluation_deck/`\n - `project/deck.json` — slide order, sections, fonts (the artifact type's index format, v4);\n - `project/slides/<id>.html` — one 1920×1080 `<section>` per slide, inline styles, speaker notes\n in `<aside>`;\n - `deck.html` — offline view of all slides, scaled to the window, each with its notes below it\n (print to PDF for a handout). Regenerate with `python3 build_standalone.py` after editing a\n slide. Fonts come from Google Fonts, so it needs internet access for the intended typefaces.\n\nThe copy was downloaded from the published version (1792808737-9c99) and matches the source files\nbyte for byte. `deck.html` has not been checked in a browser here (no headless browser in this\nenvironment), and neither has the live deck: page through both once for overflowing text or\noverlapping chart labels.\n\n## How it was made\n\n1. **Sources.** Every number comes from the notes in `docs/`, mainly:\n `20261023_210727_rag_phase5_scoring_and_analysis.md` (results, robustness, ceiling audit),\n `20261023_120734_first_full_evaluation_budget_trimmed_plan_and_s2_s3_hypotheses.md` (H1–H6, the\n trimmed grid, the perturbation threshold), `20261023_151928_rag_phase3_trimmed_full_generation.md`,\n `20261021_155704_nuggetization_phases_2_to_4_execution.md` (nugget QA, judge selection),\n `20260923_193852_segmentation_strategies_for_rag_experiments.md`,\n `20261022_203625_corpus_exclusion_revoked_rir1999.md`, the retrieval report\n `runs/retrieval/jua-4b-mixed/irpf/eval/either_containment_merge_skip/report.md`,\n `segmented/segmentation_report.md`, `scripts/rag/llms.yaml` and the prompt\n `scripts/rag/prompts/answer_v1.pt.md`.\n2. **Checked against the data, not only the notes:**\n - the Q350 nuggets on the nuggets slide come from `nuggets/gold/v0-auto/nuggets.jsonl` (N02\n vital: parent-in-law only in a joint return, with the R$ 24.511,92 limit; N01, N03 okay). A first\n draft paraphrased them from memory; it was replaced with the real ones;\n - the article-chunk example (Lei 9.250/1995, art. 35: ≈ 720 tokens as an S1 article chunk, ≈ 140\n tokens as the S2 inciso VI chunk) comes from `segmented/chunks_all.csv.gz`.\n3. **Structure.** It is laid out like a paper: motivation → hypotheses → data → method → evaluation\n design → results → robustness → synthesis, with a section marker in each footer and speaker\n notes on every slide aimed at the questions a reviewer would ask.\n4. **Look.** Light paper background with dark cover/closing slides; Source Serif 4 for headings,\n IBM Plex Sans for text. One colour per strategy throughout (S2 blue `#2E62A8`, S1 orange\n `#B85F22`). Charts are inline SVG (retrieval recall vs budget, S1→S2 forest plot, perturbation\n curve) or plain bar layouts (contradictions, decomposition, ceiling causes).\n5. **Fixes during review of the slide sources:** forest-plot p-value labels repositioned; retrieval\n slide shortened to fit; contradiction bars rescaled to their percentages; an unsupported table\n `colspan` replaced by separate boxes; label collisions on the perturbation chart moved; the\n ceiling-causes chart narrowed to fit the slide.\n6. **Wording kept honest:**\n - the second-judge slide says both judges give the *same* S1→S2 Δ. On its 70-question sample\n that Δ is slightly negative and not significant for both judges, so the check shows the judges\n agree with each other; it does not reproduce the main effect;\n - the phase 5 note says the 60 cause classifications were all read and 17 changed. That review\n was done by the assistant, not by a person, so the slides say \"re-checked against the evidence\",\n and the limitations slide says a tax-law expert still needs to confirm them;\n - the ceiling audit (slides 24–25) is marked as exploratory: it was run after the main analysis,\n on 57 questions.\n\n## Outline and description\n\n| # | Slide | Content |\n|---|---|---|\n| 1–4 | Motivation | Earlier work on structural segmentation of Brazilian law only measured retrieval, not answers. H1–H6 from the plan note. The slides point out that H3–H6 were written down before any answer was scored, so their null results aren't post hoc. |\n| 5–9 | Data and pipeline | Dataset and LexML corpus (715 Q&A, 1,916 references, 453 documents, RIR/1999 excluded). Lei 9.250 art. 35 as one ~720-token S1 article chunk vs a ~140-token S2 inciso chunk, tied to Q350. The five strategies, all filtered from one chunk table and one embedding run. The comparison is at equal token budget (4k), not equal number of chunks. Four generators in two same-vendor size pairs, with closed-book, oracle and wrong-context controls. |\n| 10–12 | Evaluation design | Nugget creation (primary GPT-6.1 Sol set, 3,175 nuggets) shown on Q350's real nuggets. Quality checks against fixed thresholds, including the one that wasn't met (3 leftover validator errors). Why Gemini 3.8 Flash was chosen as judge (BA 99.0 % on 3,354 known-answer tests). V_strict as the headline metric. Paired bootstrap, permutation test, chapter-cluster bootstrap. |\n| 13–19 | Results | S2 retrieves about 0.10 more of the cited articles at every budget (chart). V_strict table. Forest plot of S1→S2: Luna +0.028 (p .007), Sabiá-4 +0.027 (p .009), Terra +0.016 (n.s.), Sabiazinho-4 +0.005 (n.s.). S3, S2c and S4 add nothing over S2. Retrieval mainly cuts contradictions (27–38 % of answers → 8–14 %). Two limits on answer quality: what the context holds (oracle 0.48) and how much the generator uses (48–65 %). Most of S2's gain comes from the 479 questions where the context holds the same facts under both strategies. |\n| 20–25 | Robustness | Opens with a map pairing each threat with the check that addresses it, then: nugget subsets and chapter clustering; deliberately damaged nugget sets (the effect survives 15–20 % damage, against the threshold set in the plan); rescoring with the Gemini and Qwen nugget sets (Terra also significant there); a second judge (κ 0.90, same Δ); the exploratory ceiling audit (context judge BA 98.5 %, a 16k oracle raises support to 50.5 %; about one vital fact in six isn't stated in any legal text of the corpus). |\n| 26–29 | Synthesis | Scorecard of the six hypotheses (H1, H2 supported; H3–H6 not). Limitations grouped by type of validity. Cost (≈ $184 in LLM calls, all in the ledgers) and reproducibility. Next steps. |\n\n## Before presenting\n\n- Fill in the placeholders `[co-authors]` (cover) and `[contact]` (last slide). The author line\n uses the git user name.\n- Chunk counts on the strategies slide (S1 21.5k, S2 73.1k, S3 77.1k) are from the segmentation\n report, i.e. before the RIR/1999 exclusion.\n- To change a slide, edit the live artifact (or ask Claude to), then download it again into this\n folder and rerun `build_standalone.py`. The copy here is a snapshot of the published version\n above, not the source the artifact is published from.\n","20261024_180016_hugging_face_release_plan.md":"# Hugging Face release plan: BR-TaxQA-R v2.0 dataset and the RAG evaluation data\n\nDate: 2026-10-24. Status: **phase 1 done (2026-10-24): both repos staged as private under `eduseiti`, see §9.** Every upload, visibility change, tag\nor repo move below is an outward-facing step. Each one waits for the user's go-ahead.\n\nThis plan covers what goes to the Hugging Face Hub, how it is described (dataset cards, configs,\nlicenses), and how to deploy it: first under the personal account `eduseiti`, then under the\n`unicamp-dl` organization. The user is a member of the organization (checked with `whoami` on\n2026-10-24; the token in `.env` is fine-grained). Earlier notes already decided that bulk outputs\ngo to the Hub and only provenance stays in git: embedding plan §4.2\n(`20260925_122058_*`), RAG plan §5 (`20260927_204356_*`), nugget plan v2 D10 (`20261011_224049_*`),\nand the nugget cache resolution §3.2 (`20261012_154616_*`). This note puts those decisions into one\nrelease.\n\n---\n\n## 1. Summary of decisions\n\n| # | Decision | Proposal |\n|---|---|---|\n| R1 | Number of repos | **Two public dataset repos**: (A) the **benchmark** (questions, references, corpus, chunks, gold nuggets), (B) the **evaluation data** (embeddings, rankings, contexts, answers, scores, raw LLM responses). A is small (≈ 130 MB) and is what most users want. B is ≈ 1.3 GB and is for reproduction and further analysis. |\n| R2 | Final names | A = **`unicamp-dl/BR-TaxQA-R`**, as revision v2.0 of the existing repo (v1.1 is kept under the tag `v1.1`). B = **`unicamp-dl/BR-TaxQA-R-RAG-eval`** (new). |\n| R3 | Staging | Both are first built as **private** repos under `eduseiti`: `eduseiti/BR-TaxQA-R` and `eduseiti/BR-TaxQA-R-RAG-eval`. Validation (§6.3) runs there. |\n| R4 | Moving to the org | B: **move** the repo (`HfApi.move_repo`). The history is kept and the old URL redirects. A: the target repo already exists, so a move cannot merge into it. **Re-upload** the validated tree to `unicamp-dl/BR-TaxQA-R` as one commit, then tag it `v2.0`. |\n| R5 | File layout | **Mirror the GitHub repo paths** (`dataset/`, `original/`, `lexml/`, `segmented/`, `nuggets/`, `runs/`, `embeddings/`). Then `documents.jsonl`'s `original_file` / `lexml_file` paths resolve inside the HF repo too. `hf download … --local-dir .` in a checkout of the code gives back the state that `rag.py` and `nuggets.py` expect. The config `data_files` point into these paths. |\n| R6 | File formats | Keep the native formats (JSONL, CSV(.gz), NPY, XML, DOCX/PDF). The Hub viewer converts JSONL/CSV configs to Parquet by itself (`refs/convert/parquet`). Raw LLM caches (≈ 51k small JSON files) are packed as `tar.gz` per cache, because the Hub handles many small files poorly. |\n| R7 | License | **CC BY 4.0** for both, as in v1.1. The legal texts are not protected by copyright in Brazil (Lei 9.610/1998, art. 8º, IV). The embedding model `ufca-llms/jua-4B-mixed` is MIT. Provider terms for LLM outputs are to be checked (§7, C5). |\n| R8 | Versioning | Git tag `v2.0` on GitHub and HF tags `v2.0` on both repos, pointing at the same content. `release/hf_release.json` in git records the HF commit SHAs (§6.4). The code stays on GitHub (`eduseiti/br-taxqa-r_v2.0`), and the cards link to it. |\n\n---\n\n## 2. Repo A: the benchmark, `BR-TaxQA-R` v2.0\n\n### 2.1 Files\n\n| Path in the HF repo | Source in git repo | Size | Content |\n|---|---|---:|---|\n| `README.md` | new; based on `dataset/README.md` | — | dataset card (§2.3) |\n| `dataset/questions.jsonl` | `dataset/` | 2.1 MB | 715 questions, gold answers (`answer_cleaned`), linked questions, raw reference text, cited `document_ids` |\n| `dataset/references.jsonl` | `dataset/` | 1.6 MB | 1,916 rows, one per cited act per question: resolution to a corpus document and URN, cited articles and `fragment_id`s (`provisions`) |\n| `dataset/documents.jsonl` | `dataset/` | 0.24 MB | 453 corpus documents: URN, title, statutory flag, paths to `original/` and `lexml/` files, number of citing questions |\n| `dataset/build_report.json` | `dataset/` | 14 KB | build counts, dropped and unresolved references, answer overrides, validation |\n| `dataset/reference_overrides.json`, `dataset/answer_overrides.json` | `scripts/dataset/` | small | hand-verified corrections to v1.1 (references, gold answers) and why each was made |\n| `nuggets/v0-auto/nuggets.jsonl` | `nuggets/gold/v0-auto/` | 3.0 MB | **gold nuggets**: 3,175 atomic facts of the gold answers (`importance` vital/okay, `category`, `values`, `source_span`, audit flags, `stability`) |\n| `nuggets/v0-auto/manifest.json` | same | 331 B | how the set was frozen (source run, auditors, counts, route) |\n| `original/articulados/*.docx` | `original/` | 14 MB | 209 statutory source documents as fetched |\n| `original/nao_articulados/*.{docx,pdf}` | `original/` | 19 MB | 244 non-statutory source documents (12 born-digital PDFs) |\n| `lexml/articulados/*.xml` (+ `PARSER_VERSION`, `skipped_report.txt`) | `lexml/` | 43 MB | LexML XML of the statutory documents: one main file plus one file per annex. `*.err.log` stays out (local paths, parser noise) |\n| `lexml/nao_articulados/*.xml` (+ `PARSER_VERSION`) | `lexml/` | 6 MB | LexML XML of the non-statutory documents (`DocumentoGenerico`). `_text/` is included: it is the parser input for the PDF sources |\n| `segmented/chunks_all.csv.gz` | `segmented/` | 19 MB | **all chunks of all strategies** (104,574 rows; S1 21,497, S2/S2c 73,118, S3/S4 77,080), with `chunk_id`, `urn`, `Rotulo`, `Texto`, `n_tokens`, `variante` … |\n| `segmented/README.md`, `segmentation_report.{md,json}`, `annex_manifest.csv`, `groupings_over_limit.csv` | `segmented/` | 0.4 MB | strategy definitions with examples, validation, annex treatment, S3/S4 groupings left out |\n| `docs/P&R IRPF 2024 - v1.0 - 2024.05.03.pdf` | `docs/` | — | the Receita Federal source of the questions |\n| `LICENSE` | new | — | CC BY 4.0 text plus the note on the legal texts |\n| `SHA256SUMS` | generated | — | checksum of every file (§6.1) |\n\nNot included: `segmented/chunks_all.csv` (the uncompressed copy), and `segmented/statutory/`\nand `non_statutory/` per-document CSVs (99 + 9 MB). They are the same rows as `chunks_all`\n(audit `20261021_165327_*`). Leaving them out avoids ≈ 700 small files that only duplicate it.\nThe v1.1 files (`BR-TaxQA-R.py`, `questions_QA_2024_v1.1.json`,\n`referred_legal_documents_QA_2024_v1.1.json`, `acordaos_CARF_2023.json`) are **removed from\n`main`** and stay reachable under the tag `v1.1`. The card says how to load it\n(`revision=\"v1.1\"`).\n\nTotal ≈ 130 MB and ≈ 1,300 files (most of them the `original/` and `lexml/` corpus).\n\n### 2.2 Configs (viewer and `load_dataset`)\n\n```yaml\nconfigs:\n- config_name: questions # default\n default: true\n data_files: [{split: test, path: dataset/questions.jsonl}]\n- config_name: references\n data_files: [{split: test, path: dataset/references.jsonl}]\n- config_name: documents\n data_files: [{split: test, path: dataset/documents.jsonl}]\n- config_name: nuggets\n data_files: [{split: test, path: nuggets/v0-auto/nuggets.jsonl}]\n- config_name: chunks\n data_files: [{split: corpus, path: segmented/chunks_all.csv.gz}]\n```\n\n`chunks` has mixed-type columns (`Num_Inicio`, ids that look like numbers). Before publishing,\ncheck that the viewer and `load_dataset(..., \"chunks\")` read it. If they don't, add an explicit\n`features:` block or publish a Parquet copy `segmented/chunks_all.parquet` with string dtypes for\nthe config. The CSV stays for the scripts.\n\n### 2.3 Card (`README.md`)\n\nYAML header: `license: cc-by-4.0`, `language: [pt]`, `pretty_name: BR-TaxQA-R v2.0`,\n`task_categories: [question-answering, text-retrieval]`, `task_ids: [open-domain-qa,\ndocument-retrieval]`, `size_categories: 1K<n<10K` (questions; the chunks are 100K<n<1M),\n`tags: [legal, tax, brazil, portuguese, rag, lexml, nuggets]`, `annotations_creators:\n[expert-generated, machine-generated]` (gold answers by Receita Federal, nuggets by LLM),\n`source_datasets: [unicamp-dl/BR-TaxQA-R]`, and the `configs:` block of §2.2.\n\nSections:\n1. **Summary.** 715 IRPF 2024 questions with gold answers and resolved legal references, a\n 453-document legal corpus in LexML, five segmentation strategies, and gold nuggets for\n nugget-based evaluation of generated answers.\n2. **What's new in v2.0.** The current \"Changes from v1.1\" section of `dataset/README.md`, plus\n the corpus, the chunks and the nuggets.\n3. **Configs and schemas.** The field tables of `dataset/README.md`, plus `nuggets` (from\n `scripts/nuggets/README.md`) and `chunks` (from `segmented/README.md`).\n4. **Corpus files.** The `original/` and `lexml/` layout, how annexes are stored, URNs, and\n `PARSER_VERSION`.\n5. **Segmentation strategies.** The S1–S4 table and how to filter `chunks_all` per strategy\n (`scripts/segmentation/strategies.py` on GitHub).\n6. **Gold nuggets.** How they were made (`create_v4`, GPT-5 family creator, two auditors,\n freeze), the counts, what `stability` and the flags mean, and known limits (machine-generated,\n not human-verified; `has_pointer` answers).\n7. **Usage.** `load_dataset` per config, `hf_hub_download` for a LexML file, and `snapshot_download`\n into a code checkout.\n8. **Companion repo.** Link to `BR-TaxQA-R-RAG-eval`.\n9. **License and sources.** CC BY 4.0, the Receita Federal source, and the public-domain status of\n legal texts.\n10. **Citation.** v1.1 paper BibTeX, plus the v2.0 paper when available.\n11. **Versions.** `v1.1` (tag) and `v2.0`.\n\n---\n\n## 3. Repo B: the evaluation data, `BR-TaxQA-R-RAG-eval`\n\n### 3.1 Files\n\n**Embeddings** (`jua-4b-mixed` = `ufca-llms/jua-4B-mixed` @ `57f491c`, TEI float16 serving,\n2,560 dims)\n\n| Path | Size | Content |\n|---|---:|---|\n| `embeddings/jua-4b-mixed/corpus/vectors.npy` | 1.04 GB | float32 (101,943 × 2,560), one row per distinct chunk text (`text_id`); `np.load(..., mmap_mode=\"r\")` |\n| `embeddings/jua-4b-mixed/corpus/texts.csv` | 2.7 MB | row → `text_id`, text hash, tokens |\n| `embeddings/jua-4b-mixed/corpus/chunk_map.csv.gz` | 1.4 MB | `chunk_id` (all strategies) → `text_id` |\n| `embeddings/jua-4b-mixed/queries/irpf/{vectors.npy,queries.csv}` | 7.5 MB | 715 query vectors with the instruction `irpf` |\n| `…/manifest.json` (corpus, queries), `parity.json`, `check.json`, `endpoint_meter.jsonl`, `embeddings/costs.csv` | small | provenance: model revision, templates, endpoint, parity check, cost |\n\nNot included: `corpus_prev_20260926/` (superseded), `run.log`. A float16 copy (≈ 520 MB) is\noptional (embedding plan D6). The proposal is not to publish it, because float32 is canonical\nand the repo stays smaller.\n\n**Retrieval** (`runs/retrieval/jua-4b-mixed/<run>/`; `<run>` = `irpf` main, without the revoked\nRIR/1999, and `irpf_with_rir1999`)\n\n| Path | Size | Content |\n|---|---:|---|\n| `<run>/<S>/rankings.csv.gz`, S ∈ {S1, S2, S2c, S3, S4} | ≈ 15 MB each | ranked chunks per question (`question_number, rank, text_id, chunk_id, alias_chunk_ids, score`) |\n| `<run>/manifest.json` | small | embedding, exclusions, k |\n| `<run>/eval/<eval_id>/` | ≈ 8 MB each | legal-provision retrieval test: `report.md`, `metrics.csv`, `comparisons.csv`, `reachability.csv`, `per_question.csv.gz`, `per_item.csv.gz`, `metrics_by_chapter.csv.gz`, `manifest.json` |\n\nAll four `eval_id`s of `irpf` are included. They are the metric variants described in\n`20261013_111626_*`.\n\n**Generator contexts** (`runs/contexts/jua-4b-mixed/<run>/<context_id>/contexts.jsonl.gz` +\n`manifest.json`, plus `summary.csv` per run; 30 + 27 MB). There are 15 context sets in `irpf`:\n`closed_book`, `oracle_budget{4000,16000}`, `S1_budget{2000,4000,8000}`,\n`S2_budget{2000,4000,8000}`, `S2_budget4000_context_v1`, `S2c/S3/S4_budget4000`,\n`wrong-S2_budget4000`. Each row is one question: the rendered `context`, the `items` (chunk ids,\nranks, tokens) and the `gold` coverage.\n\n**Generated answers** (`runs/answers/jua-4b-mixed/irpf/<prompt>/<llm>/<context_id>/answers.jsonl`\n+ `run.json`; 62 MB). LLMs: `sabia-4`, `sabiazinho-4`, `gpt-5.6-terra`, `gpt-5.6-luna`. Prompts:\n`answer_v1` and `answer_closed_v1`. There are **25 full runs** (715 questions) of the trimmed grid,\nand **31 pilot-only** sets (30 questions of `stratified_30`). Each row has the answer, claims,\ncited chunk ids, the abstention flag, checks, usage and cost, and the `cache_key` of the raw\nresponse. `runs/costs.csv` (2 MB) is the generation cost ledger.\n\n**Nugget runs and scoring** (`nuggets/`, without `cache/` and `input/`)\n\n| Path | Size | Content |\n|---|---:|---|\n| `nuggets/full/` (`create/`, `selfscore/`, `align/`, `audit/`, `known/`, `roundtrip/`, `report_full.md`, `costs.csv`, `sample.json`) | 48 MB | phases 2–4: the nugget sets of the three creators and their replicas, self-scores, alignments, audits, known-answer tests. This is where `v0-auto` comes from |\n| `nuggets/pilot/`, `nuggets/preview*/`, `nuggets/parity_openrouter/` | 8 MB | phase 1 pilot, the three previews, and the direct-vs-OpenRouter parity check. Provenance for the prompt decisions |\n| `nuggets/scoring/score/<nuggets>/<judge>/…/labels.jsonl` (+ `calls.jsonl`, `manifest.json`) | 30 MB | **per-answer nugget labels** (support / partial / contradicts / not_mentioned …) for every answer set, judge `gemini-3.8-flash`. Also the second judge `gemini-3.1-pro` and the alternative nugget sets `gemini-3.1-pro.rep0`, `qwen3.8-max.rep0` |\n| `nuggets/scoring/ctxsupport/…` | 3.6 MB | whether each context supports each nugget |\n| `nuggets/scoring/ctxaudit/gold-v0-auto/stratified_70/` | 2.8 MB | audit of nuggets not supported by the corpus (`20261024_*` investigation) |\n| `nuggets/scoring/tables/…` | 0.4 MB | **result tables**: `runs.csv` (V_strict, V, A_strict, A, W, contradicts, abstained per run), `comparisons.csv`, `per_question.csv.gz`, `ctxsupport_*` |\n| `nuggets/scoring/analysis/…` | 0.8 MB | the phase 5 analyses (chapters, citations, linkage, perturbation, judge agreement, values) |\n| `nuggets/scoring/costs.csv` | 5.3 MB | scoring cost ledger |\n\n`probe_openrouter/` (a connectivity probe) stays out.\n\n**Raw LLM responses** (`raw/`; the only exact record of non-deterministic outputs, and what makes\nreruns free and reproducible)\n\n| Path | Files packed | Unpacked | Restores |\n|---|---:|---:|---|\n| `raw/runs_answers_cache.tar.gz` | 15,874 | 301 MB | `runs/answers/cache/` |\n| `raw/nuggets_full_cache.tar.gz` | 12,519 | 246 MB | `nuggets/full/cache/` |\n| `raw/nuggets_scoring_cache.tar.gz` | 22,688 | 444 MB | `nuggets/scoring/cache/` |\n| `raw/nuggets_parity_openrouter_cache.tar.gz` | — | 1.4 MB | `nuggets/parity_openrouter/cache/` |\n| `raw/nuggets_pilot_cache.tar.gz` | — | ≈ 20 MB | `nuggets/pilot/cache/`; **not on this machine** (see C1) |\n\nEach cache file holds `request` (provider, model, params, system and user prompts), `response`,\n`text`, `usage`, `model_served`, `latency_s`, `ts`. The packed size is still to be measured.\nJSON compresses well, so expect ≈ 100–200 MB in total. `raw/README.md` gives the cache-key\nscheme (SHA-256 of the canonical request, `scripts/llm_client/`) and the unpack command.\n\n**Other:** `README.md` (card, §3.3), `LICENSE`, `SHA256SUMS`, and `docs/` with a copy of the\nnotes the card cites (the strategy, nugget, RAG phase 3 and phase 5 notes), so the repo makes sense\nwithout GitHub.\n\nTotal ≈ 1.3–1.5 GB in ≈ 700 files.\n\n### 3.2 Configs\n\nOnly the tables people browse get viewer configs. Rankings, vectors and raw responses do not:\n\n```yaml\nconfigs:\n- config_name: run_metrics # default; one row per (llm, context set), the main result table\n default: true\n data_files: [{split: all, path: nuggets/scoring/tables/gold-v0-auto/gemini-3.8-flash/all/runs.csv}]\n- config_name: answers\n data_files: [{split: full, path: \"runs/answers/jua-4b-mixed/irpf/*/*/*/answers.jsonl\"}]\n- config_name: nugget_labels\n data_files: [{split: full, path: \"nuggets/scoring/score/gold-v0-auto/gemini-3.8-flash/**/labels.jsonl\"}]\n- config_name: per_question_scores\n data_files: [{split: all, path: nuggets/scoring/tables/gold-v0-auto/gemini-3.8-flash/all/per_question.csv.gz}]\n- config_name: retrieval_metrics\n data_files: [{split: irpf, path: runs/retrieval/jua-4b-mixed/irpf/eval/either_containment_merge_skip/metrics.csv}]\n```\n\nTwo problems to solve in the build script (§6.1):\n\n- The `answers` glob mixes full and pilot sets, and the rows of `answers.jsonl` carry `run_id`\n but not the LLM and context set as separate columns. Check that `run_id` is enough to tell them\n apart. If it isn't, generate a flat **`answers_full.jsonl`** with\n `llm, prompt, context_id, question_number, answer, abstained, cited_chunk_ids, …` from the 25\n full runs only, and point the config at it. The per-run files stay for the scripts.\n- `labels.jsonl` rows have `source` and a nested `labels` list. The path holds the run identity.\n Use the same fix: a flat `nugget_labels_full.jsonl`, one row per (run, question, nugget).\n\n### 3.3 Card (`README.md`)\n\nYAML: `license: cc-by-4.0`, `language: [pt]`, `pretty_name: BR-TaxQA-R v2.0 — RAG evaluation\ndata`, `task_categories: [question-answering, text-retrieval]`, `tags: [rag, evaluation, nuggets,\nllm-as-judge, embeddings, legal, tax, brazil]`, `size_categories: 10K<n<100K`,\n`source_datasets: [unicamp-dl/BR-TaxQA-R]`, plus `configs:`.\n\nSections:\n1. **What this is.** The full trail of the first RAG evaluation on BR-TaxQA-R v2.0: embeddings →\n rankings → contexts → answers → nugget scores → tables.\n2. **Pipeline and the experiment grid.** Segmentation strategies × token budgets × 4 generators;\n oracle, closed-book and wrong-context controls; the trimmed grid; the `irpf` and\n `irpf_with_rir1999` runs. Include a figure from the slide deck.\n3. **Headline results.** The `runs.csv` table (S2 > S1 by +0.02–0.03 V_strict; S3/S2c/S4 ≈ S2) with\n a pointer to the paper.\n4. **File layout.** The tables of §3.1.\n5. **Models and versions.** Embedding model and revision. Generators, judges and nugget creators\n with the model ids actually served (`model_served`), routes (OpenRouter / Maritaca), dates and\n temperatures.\n6. **Reproducing.** `git clone` the code, `hf download unicamp-dl/BR-TaxQA-R-RAG-eval\n --repo-type dataset --local-dir .`, unpack `raw/*.tar.gz`, then rerun `rag.py` / `nuggets.py`.\n Cached calls cost nothing.\n7. **Costs.** The ledgers, and the totals per phase (generation $41.95, scoring $55.96, …).\n8. **Limitations.** LLM judge, machine-made nuggets, one embedding model, served-model drift.\n9. **License, citation, links.**\n\n---\n\n## 4. Not uploaded anywhere\n\n- `.env`, the `.venv`, `__pycache__`, `.~lock.*`.\n- `*.err.log`, `run.log`, `nuggets/**/input/` (regenerated from `questions.jsonl`; its SHA-256 is\n in `sample.json`), and `nuggets/**/batches/*.jsonl`.\n- `embeddings/jua-4b-mixed/corpus_prev_20260926/`, `nuggets/probe_openrouter/`.\n- `docs/slides/` and the internal notes, except the copies listed in §3.1.\n\n---\n\n## 5. Staging and deployment strategy\n\n### 5.1 Phase 1: private staging under `eduseiti`\n\n1. Create `eduseiti/BR-TaxQA-R` and `eduseiti/BR-TaxQA-R-RAG-eval` as **private** dataset repos\n (`HfApi.create_repo(..., repo_type=\"dataset\", private=True)`).\n2. Build the two release trees in a scratch folder with `scripts/release/build_release.py` (§6.1).\n3. Upload. Use `upload_folder` for A. Use `upload_large_folder` for B: it resumes and handles the\n 1 GB `.npy`. New repos store files with Xet, so later re-uploads only send the changed chunks.\n4. Validate (§6.3). Fix and re-upload until it passes.\n5. **This private copy also serves as the cache backup** that the nugget notes have kept postponing\n (open decisions §2.2). It can happen before the paper is final.\n\nStorage: ≈ 1.5 GB private, well inside the free private quota.\n\n### 5.2 Phase 2: optional review access\n\nIf co-authors or reviewers need access before publication:\n- Add them as collaborators, or make the repos public under `eduseiti` for a short time.\n- **If the paper is under double-blind review**, `eduseiti` and `unicamp-dl` both reveal the\n authors. Use an anonymous link instead, for example a separate anonymous HF account or the\n venue's supplementary material (see C7).\n\n### 5.3 Phase 3: publication under `unicamp-dl`\n\nPrerequisites: a write role in `unicamp-dl` for `eduseiti`, and a token whose fine-grained\npermissions include write on `unicamp-dl` repos and repo creation in the org. Check both with\n`whoami` before starting.\n\n**Repo A (the existing `unicamp-dl/BR-TaxQA-R`):**\n1. `create_tag(\"unicamp-dl/BR-TaxQA-R\", tag=\"v1.1\", revision=\"9f0f4263928c6152a40f888da3e63375a24bb0f3\")`.\n This is the current `main`, last modified 2025-11-22.\n2. Upload the validated tree from `eduseiti/BR-TaxQA-R` (same local folder, same build) to\n `unicamp-dl/BR-TaxQA-R` with `upload_folder(..., delete_patterns=[\"*\"])` and the commit\n message \"BR-TaxQA-R v2.0\". `delete_patterns` removes the v1.1 files from `main`. Alternative:\n open it as a PR (`create_pr=True`), review it on the Hub, and merge. **Recommended**, because\n the org repo is public and already used.\n3. `create_tag(..., tag=\"v2.0\")` on the merge commit.\n4. Delete `eduseiti/BR-TaxQA-R` or keep it private. It cannot be moved, because the name in the org\n is taken.\n\n**Repo B:**\n1. `move_repo(from_id=\"eduseiti/BR-TaxQA-R-RAG-eval\", to_id=\"unicamp-dl/BR-TaxQA-R-RAG-eval\",\n repo_type=\"dataset\")`. History and tags move with it, and the old URL redirects.\n2. Make it public with `update_repo_settings(private=False)`, then `create_tag(tag=\"v2.0\")`.\n\nThen check again (§6.3, steps 2–4) against the org URLs. Update the cross-links between the two\ncards and the GitHub README, and record the commit SHAs (§6.4).\n\n### 5.4 Later updates\n\nNew experiments (stages 3–4 of the trimmed plan, more embedding models, human-verified nuggets):\n- New evaluation outputs go to B as new commits under new paths (e.g. `embeddings/<model>/`),\n with a tag per paper version (`v2.1`, …).\n- A changes only if the benchmark changes (e.g. `nuggets/v1-human/`), which is a dataset\n version bump.\n- Do not rewrite history on a published repo.\n\n---\n\n## 6. Implementation\n\n### 6.1 `scripts/release/build_release.py` (new)\n\n- Input: a YAML file list per repo (`scripts/release/repo_a.yaml`, `repo_b.yaml`) that encodes\n §2.1 and §3.1 as include/exclude globs. Output: `<out>/repo_a/` and `<out>/repo_b/` with the\n HF paths. It hardlinks where possible, so the 1 GB `.npy` is not copied.\n- Packs each cache into `raw/*.tar.gz` (deterministic: sorted names, fixed mtime) and writes\n `raw/README.md`.\n- Generates the flat `answers_full.jsonl` / `nugget_labels_full.jsonl` if §3.2 needs them.\n- **Checks** (it fails on any of these):\n - secret patterns in every file, caches included (`sk-…`, `sk-or-…`, `hf_…`, `AIza…`,\n `Bearer`). A sample of 9,000 cache files had 0 hits on 2026-10-24;\n - absolute local paths (`/work/`, `/home/`, `/root/`). Three embedding manifests have them\n today (corpus, `corpus_prev_20260926`, queries). Rewrite them to repo-relative paths in the\n release copy only;\n - every path in `documents.jsonl` (`original_file`, `lexml_file`, `lexml_annex_files`) exists in\n tree A;\n - the row counts in the card match the files.\n- Writes `SHA256SUMS` and `release_manifest.json` (git commit, build time, file list with sizes\n and hashes) in each tree.\n\n### 6.2 `scripts/release/push_release.py` (new)\n\n`--repo-id`, `--tree`, `--private`, `--create-pr`, `--tag`, `--dry-run` (lists what would change\nagainst the remote). It reads `HF_TOKEN` from `.env`. It never changes visibility or moves a repo\nunless the matching flag is set. Moves and visibility changes stay manual one-liners in the\nREADME.\n\n### 6.3 Validation\n\n1. In a clean venv (`datasets`, `huggingface_hub` only): `load_dataset(repo, config)` for every\n config of A and B, checking row counts (715 / 1,916 / 453 / 3,175 / 104,574; answers 25 × 715).\n2. The Hub viewer shows every config without errors, including the Parquet conversion of `chunks`.\n3. `snapshot_download` both repos into a fresh clone of the GitHub repo, then `sha256sum -c\n SHA256SUMS`.\n4. Reproduction smoke test: unpack `raw/`, then rerun `rag.py run` for one full run and\n `nuggets.py score` / `scoretable` for one run with `--budget 0.01`. Every call must come from\n the cache ($0), and `runs.csv` must match byte for byte.\n5. Read both cards on the Hub: links, tables, citation.\n\n### 6.4 Changes in the git repo\n\n- `release/hf_release.json`: the repo ids, the commit SHAs and tags of each publication.\n- `dataset/README.md`: fix the stale counts. It says 1,917 references and 458 documents, but\n `build_report.json` and the files have **1,916** and **453**. Turn it into the source of the\n repo A card, or replace it with a pointer to the card.\n- The repo has no top-level `README.md` yet. Add a short one that points to the two HF repos.\n `CLAUDE.md` and the `.gitignore` comments (\"released on the HF Hub\") get the final URLs. The nugget manifest records the Hub revision (plan v2, W1).\n- A git tag `v2.0` on the release commit, pushed to GitHub, with the user's go-ahead.\n\n---\n\n## 7. Checks before going public\n\n| # | Check | Status |\n|---|---|---|\n| C1 | **Pilot and preview nugget caches**: they are not on this machine (`nuggets/pilot/cache/` is missing; see the two-machine memory note). Copy them from the other computer before building B, or document them as not released. Missing: `nuggets/{pilot,preview,preview_v2,preview_v3}/cache/`. Copy them with `scripts/release/transfer_caches.py` (`pack` there, `unpack` here; see `scripts/release/README.md`) | open |\n| C2 | Full secret scan of every released file (§6.1) | sample OK |\n| C3 | Absolute paths in manifests (§6.1) | 3 files found |\n| C4 | Stale counts in `dataset/README.md` (§6.4) | open |\n| C5 | Provider terms for publishing model outputs: OpenAI (GPT-5.x via OpenRouter), Google (Gemini), Alibaba (Qwen), Maritaca (Sabiá-4). All four generally allow it, but check Maritaca's terms and OpenRouter's pass-through terms specifically | open |\n| C6 | Source documents: Receita Federal Q&A PDF and the acts are public works. CARF decisions and soluções de consulta are official acts. Check that no non-statutory document contains personal data of taxpayers beyond what the authority already publishes | open |\n| C7 | Double-blind review: is the paper submitted anonymously? This decides whether §5.2 needs an anonymous mirror | to decide |\n| C8 | Whether to include the 31 pilot-only answer sets and the preview/pilot nugget runs (proposal: yes, under the same paths; they are small and cited by the notes) | to decide |\n| C9 | Org repo name for B (`BR-TaxQA-R-RAG-eval`), and whether `unicamp-dl` wants a different naming | to decide |\n| C10 | Whether to also publish a float16 copy of the vectors (proposal: no) | to decide |\n\n---\n\n## 8. Order of work\n\n1. User decisions C7–C10, and C1 (copy the caches from the other machine).\n2. Write `build_release.py`, `push_release.py` and the two YAML file lists. Build both trees\n locally and review the trees and the cards (no upload).\n3. **Go-ahead 1:** create the private repos under `eduseiti` and upload. Validate (§6.3).\n4. Resolve C4–C6. Final card text.\n5. **Go-ahead 2:** tag `v1.1`, open the PR on `unicamp-dl/BR-TaxQA-R`, and move B to `unicamp-dl`.\n6. **Go-ahead 3:** merge the PR, make B public, add the tags, and run the final validation. Commit\n `release/hf_release.json` and the README updates, and tag `v2.0` on GitHub.\n\nHF storage and transfer cost nothing for public datasets of this size. No LLM calls are needed\n(only the cached $0 smoke test in §6.3).\n\n---\n\n## 9. Execution: phase 1, private staging (2026-10-24)\n\nUploaded with the user's go-ahead. The user agreed to the proposals for C8–C10: pilot and preview runs\nincluded, the name `BR-TaxQA-R-RAG-eval`, no float16 copy of the vectors. The token is `HF_RELEASE_TOKEN` in\n`.env`. It is fine-grained, with write access to repos of `eduseiti` and `unicamp-dl`. `HF_TOKEN` stays the\ninference-only embedding token. The repos, commit SHAs and build commits are recorded in\n`release/hf_release.json`.\n\n| Repo | Private | HF commit | Files | Size |\n|---|---|---|---:|---:|\n| <https://huggingface.co/datasets/eduseiti/BR-TaxQA-R> | yes | `2b10e0f` | 1,119 | 122 MB |\n| <https://huggingface.co/datasets/eduseiti/BR-TaxQA-R-RAG-eval> | yes | `af37fda` | 894 | 1.73 GB |\n\n**Validation (§6.3):**\n- **Steps 1 and 3 done.** Every config loads from the Hub in a clean venv (`datasets` 5.1.0) with the expected\n rows. Repo A: 715 / 1,916 / 453 / 3,175 / 104,574. Repo B: `answers` 18,805, `nugget_labels` 82,186,\n `run_metrics` 56, `per_question_scores` 18,309, `comparisons` 336, `retrieval_metrics` 11,255. A full\n download of each repo passes `sha256sum -c SHA256SUMS` (1,117 and 892 files).\n- **The archives are exact.** Every `raw/*.tar.gz` member is byte-identical to its source cache file, and the\n member counts equal the cache folders: 15,874 / 12,519 / 22,688 / 931 / 90 / 30 / 90 / 89.\n- **Not done:**\n - **Step 2, the dataset viewer.** It does not run on private repos of non-PRO accounts. Check it after\n publication.\n - **Step 4, the replay smoke test.** Rerunning one run from the restored caches has not been tried yet.\n\n**Changes from the plan:**\n- **One reader per repo.** `datasets` reads every config of a repo with one reader, so formats cannot be\n mixed. A CSV config also failed on its own, because the JSON reader cannot type columns that are empty in\n the first rows. So:\n - Repo A's configs are all JSON Lines. `chunks` reads `segmented/chunks_all.jsonl.gz`, a copy of the CSV in\n which missing strings are written as `\"\"`, as the CSV holds them.\n - Repo B's configs are all Parquet copies in `tables/` (`answers`, `nugget_labels`, `run_metrics`,\n `per_question_scores`, `comparisons`, `retrieval_metrics`). The CSV and JSONL originals stay at their repo\n paths.\n- **`all` is a reserved split name**, so repo B's splits are `results` (`irpf` for the retrieval metrics).\n- **The Q&A PDF is at `source/`** in repo A, not under `docs/`.\n- **Secret scan false positives.** Nine cache files matched the key patterns. Every match was inside a\n provider's encrypted reasoning blob (`reasoning_details[].data`, `encrypted_content`), which is random base64.\n The pattern now ignores matches that start inside a longer token. With it, the caches packed with no hit.\n- **Rewritten paths (in the copies only):**\n - in the embedding manifests, the repo path and `../br-taxqa-document-fetcher/`;\n - in `segmentation_report.{md,json}` and one doc note, the repo path and Claude Code scratchpad paths, which\n become `<scratchpad>/`.\n- **`pyarrow` was added to the project venv.** It is listed in `scripts/release/requirements.txt`.\n- **Plan check C4 is done.** `dataset/README.md` now says 1,916 references and 453 documents.\n\n**Next (phase 3, §5.3).** Each step waits for the user's go-ahead:\n1. Close the remaining checks: C5 (provider terms), C6 (personal data) and C7 (double-blind review).\n2. Tag `v1.1` on `unicamp-dl/BR-TaxQA-R`, and open the v2.0 PR there from the same tree.\n3. Move repo B to `unicamp-dl` and make it public.\n4. Check the viewer, tag `v2.0`, and update `release/hf_release.json`.\n","20261108_153258_gemini_embedding_2_comparison_plan.md":"# Plan: reproduce the best jua-4b-mixed results with gemini-embedding-2\n\n**Generated:** 2026-11-08 15:32:58 (local time, from `date +%Y%m%d_%H%M%S`).\n**Status:** **executed on 2026-11-08: steps 1–8, B then A.** Results, costs and what is not done are in\n`20261108_175117_gemini_embedding_2_setup_embedding_and_retrieval_gate.md`. The rest of this note is the plan as written. **The open points were decided by the\nuser on 2026-11-08 (§6):**\n- the embedding goes through OpenRouter;\n- the document template is `title: none`;\n- Terra is not added;\n- **all texts are embedded.**\n\nThe OpenRouter key limit was raised to $200: $55.22 left at 17:15.\n**Builds on:**\n- the scoring and analysis note `20261023_210727_rag_phase5_scoring_and_analysis.md` (the jua results);\n- the trimmed-grid plan `20261023_120734_first_full_evaluation_budget_trimmed_plan_and_s2_s3_hypotheses.md`\n and the generation note `20261023_151928_rag_phase3_trimmed_full_generation.md` (measured costs);\n- the embedding plan `20260925_122058_embedding_implementation_plan.md` (§1.1, §5.2, §8.2, §9.2: the Gemini\n design that was deferred);\n- the HF release plan `20261024_180016_hugging_face_release_plan.md` (§3.1, §9: what is on the Hub).\n\n**Goal:** test whether a stronger embedding changes the main result, using as few new runs as possible. The\nmain result is that S2 beats S1 by a small but robust margin, and S3, S2c and S4 add nothing. Every number\nhere comes from the jua-4b-mixed runs. Only the retrieval stage changes: segmentation, generators, prompts,\nnugget set, judge and the 4k budget stay the same.\n\n---\n\n## 1. Which results to compare against\n\n### 1.1 The best results with jua-4b-mixed (V_strict, 715 questions, phase 5 note §2–§3)\n\n| Generator | closed book | S1 4k | S2 4k | best other 4k set | oracle 4k | S1 → S2 |\n|---|---:|---:|---:|---|---:|---|\n| GPT-5.6 Terra | **0.351** | 0.325 | **0.341** | — | 0.368 | +0.016, p .11 (significant under both other nugget sets) |\n| Sabiá-4 | 0.239 | 0.290 | **0.317** | S3 0.315 | 0.319 | **+0.027, p .009** |\n| GPT-5.6 Luna | 0.259 | 0.271 | 0.299 | **S2c 0.314** | 0.338 | **+0.028, p .007** |\n| Sabiazinho-4 | 0.177 | 0.267 | 0.272 | **S4 0.287** | 0.293 | +0.005, p .63 |\n\nRetrieval-side numbers that a new embedding can move:\n- context support (vital nuggets the context fully states): S1 4k 0.397, S2 4k 0.411, oracle 4k 0.483 (§4);\n- context article recall on the 596 questions with gold: S1 0.398, S2 0.503, oracle 0.803 (§6.2);\n- the legal-provision retrieval test (`runs/retrieval/jua-4b-mixed/irpf/eval/`): free to recompute.\n\n### 1.2 What the comparison should contain\n\n**Keep:** S1 4k and S2 4k. S2 4k is the best RAG strategy for Sabiá-4 and Terra, and S1 → S2 is the paper's\nmain hypothesis. Rerunning both shows two things:\n- whether the better embedding raises the scores;\n- whether the S2 gain survives it, grows, or disappears. A stronger embedding may find the right article\n in S1 anyway.\n\n**Do not rerun:**\n- **closed book and the oracle contexts.** They do not use retrieval, so the jua answers and scores are the\n reference for both embeddings.\n- **S3, S2c and S4.** They add nothing measurable over S2 (all |diff| ≤ 0.014, none significant).\n Luna's S2c 0.314 is the best Luna score, but its gain over S2 (+0.014, p .15) is not significant. It is an\n optional extension (§4.3).\n- **the 2k / 8k budgets and `wrong-S2`**: they are controls and sweeps, not best results.\n\n**Generators**, ranked by how informative they are for the cost:\n\n| Generator | Why | Cost of one 715-question run (generation + scoring) |\n|---|---|---:|\n| **GPT-5.6 Luna** | S1 → S2 significant. It gains most from better contexts (S1 → oracle +0.044, p .002), so it is the most sensitive to retrieval quality. Cheapest generator | ≈ $0.48 + $1.65 = **$2.1** |\n| **Sabiá-4** | S1 → S2 significant. It is the Portuguese model, and one of the two generators in the cross-set and second-judge checks | ≈ $4.6 (Maritaca, direct) + $1.65 = **$6.3** |\n| GPT-5.6 Terra | Highest RAG score, but retrieval does not help it (closed book 0.351 ≥ S2 0.341). A better embedding mainly shows up as fewer contradictions, not higher recall | ≈ $5.0 + $1.65 = $6.7 |\n| Sabiazinho-4 | No S1 → S2 gain; utilisation of the context is lowest (0.48–0.49) | ≈ $0.93 + $1.65 = $2.6 |\n\n**Recommendation: Luna and Sabiá-4 on S1 4k and S2 4k (4 runs).** These are the two generators where both\nretrieval and segmentation matter significantly. Add context support on the two new context sets: it is the\ndirect measure of what the better embedding puts in the context, and it lets the linkage decomposition of\n§5 of the phase 5 note be repeated. Terra and Sabiazinho-4 are optional (§4.3).\n\n### 1.3 A free gate before any LLM call\n\nRun the legal-provision retrieval test on the Gemini rankings first (`rag.py evaluate`, no LLM, ≈ 30 s) and\ncompare it with jua (`rag.py compare`, or the metrics side by side):\n- article recall at the 4k budget, S1 and S2;\n- recall@k of the unit and raw-rank views.\n\nIf Gemini is clearly better, go on to generation. If it is no better or worse, stop and report: generation\nand scoring would then measure noise. That would still be a result: \"the stronger embedding does not\nretrieve the cited provisions better\".\n\n---\n\n## 2. Downloading what is on Hugging Face\n\n### 2.1 What this machine (`f3593e5b57d4`) has now (checked 2026-11-08)\n\n- The git checkout is clean and up to date (HEAD `1783692`), so everything tracked in git is here:\n - `dataset/`, `nuggets/gold/v0-auto/`;\n - the answer files (`answers.jsonl`, `run.json`);\n - the scoring labels and tables (`nuggets/scoring/`, 299 files);\n - the manifests.\n- `segmented/chunks_all.csv.gz` is the released one (SHA-256 `a6087b7f…326a`, 104,574 rows, 101,943 unique\n texts).\n- **The local jua embeddings and rankings are stale. Do not use them.**\n - `embeddings/jua-4b-mixed/corpus/vectors.npy` has 115,582 rows: it is the 2026-10-08 store.\n - The release, and every RAG run, uses the 2026-10-09 store with 101,943 rows (its `manifest.json` is\n here, its vectors are not).\n - `runs/retrieval/jua-4b-mixed/irpf/*/rankings.csv.gz` are also from 2026-10-08.\n- **Missing:**\n - the generator contexts (`runs/contexts/…/contexts.jsonl.gz`; only the manifests are here);\n - all raw LLM caches (`runs/answers/cache/`, `nuggets/scoring/cache/`, `nuggets/full/cache/`).\n- **`.env`** has `HF_TOKEN`, `GEMINI_API_KEY`, `OPENAI_API_KEY` and `DASHSCOPE_API_KEY`. It does **not**\n have:\n - `OPENROUTER_API_KEY` (needed for Luna, the judge, and the OpenRouter embedding route);\n - `MARITACA_API_KEY` (Sabiá-4);\n - `HF_RELEASE_TOKEN` (needed to read the private repos).\n\n### 2.2 Operations (repo B, private `eduseiti/BR-TaxQA-R-RAG-eval`, HF commit `af37fda`)\n\nThe repo mirrors the git paths (release plan R5), so `hf download … --local-dir .` puts files where `rag.py` and\n`nuggets.py` expect them. Repo A (`eduseiti/BR-TaxQA-R`) is not needed: everything in it that the pipeline\nreads is already in git here.\n\n```bash\ncd /work/doutorado/artigos/RAG_evaluation/br-taxqa-r_v2.0\n# 0. credentials: add OPENROUTER_API_KEY, MARITACA_API_KEY and HF_RELEASE_TOKEN to .env (copy from the other machine)\nset -a; . ./.env; set +a\n.venv/bin/pip install -U \"huggingface_hub[cli]\" # if `hf` is missing\n# 1. move the stale jua store and rankings aside (keep them until the download is verified)\nmkdir -p ../stale_jua_20261008\nmv embeddings/jua-4b-mixed/corpus/vectors.npy embeddings/jua-4b-mixed/corpus/texts.csv \\\n embeddings/jua-4b-mixed/corpus/chunk_map.csv.gz ../stale_jua_20261008/\nfor s in S1 S2 S2c S3 S4; do mv runs/retrieval/jua-4b-mixed/irpf/$s/rankings.csv.gz ../stale_jua_20261008/rankings_$s.csv.gz; done\n# 2. download (pinned to the staged commit, into a scratch folder first: downloaded files are untrusted data)\nR=eduseiti/BR-TaxQA-R-RAG-eval; REV=af37fda92b62c05755ed61d1d7185f59f2aeef64; D=../hf_rag_eval_af37fda\nHF_TOKEN=$HF_RELEASE_TOKEN hf download $R --repo-type dataset --revision $REV --local-dir $D \\\n --include \"SHA256SUMS\" \"embeddings/**\" \"runs/retrieval/**\" \"runs/contexts/**\" \\\n \"raw/runs_answers_cache.tar.gz\" \"raw/nuggets_scoring_cache.tar.gz\"\n# 3. verify only what was downloaded, then copy into the checkout\n(cd $D && grep -E ' (embeddings|runs/retrieval|runs/contexts|raw/(runs_answers|nuggets_scoring))' SHA256SUMS | sha256sum -c --quiet)\nrsync -a --ignore-existing $D/embeddings/ embeddings/\nrsync -a $D/runs/retrieval/ runs/retrieval/ # replaces the stale rankings; manifests are identical to git\nrsync -a --ignore-existing $D/runs/contexts/ runs/contexts/\n# 4. unpack the two caches (archives hold only cache JSON files; check the member list first)\ntar -tzf $D/raw/runs_answers_cache.tar.gz | head; tar -xzf $D/raw/runs_answers_cache.tar.gz -C runs/answers/\ntar -tzf $D/raw/nuggets_scoring_cache.tar.gz | head; tar -xzf $D/raw/nuggets_scoring_cache.tar.gz -C nuggets/scoring/\ngit status --short # must stay clean: everything downloaded is gitignored\n```\n\nCheck `raw/README.md` in the repo for the exact archive root before step 4. The release plan says each archive\nrestores its folder, but the member paths may start with `cache/`. Size: ≈ 1.1 GB vectors + ≈ 0.2 GB rankings and\nevals + 57 MB contexts + the two cache archives. There are 38 GB free on `/work`.\n\n**What each download is for:**\n\n| Item | Needed for | Required? |\n|---|---|---|\n| `runs/retrieval/jua-4b-mixed/**` (rankings, evals) | side-by-side retrieval test against Gemini (§1.3) | **yes** |\n| `runs/contexts/jua-4b-mixed/**` | the citation and linkage analyses (`nuggets.py analyze` reads contexts), and to compare contexts per question | **yes** |\n| `embeddings/jua-4b-mixed/**` | only to rerun jua retrieval or try a hybrid; replaces the stale store | recommended (it avoids keeping a wrong store on disk) |\n| `raw/runs_answers_cache.tar.gz` | reruns of the jua answers at no cost; not needed for the Gemini runs | optional |\n| `raw/nuggets_scoring_cache.tar.gz` | free cache hits when an answer is identical to one already scored (likely for some Gemini answers on questions whose retrieved context did not change) | recommended (it saves a few dollars) |\n\n**Check after the download:** rerun `rag.py retrieve --embedding jua-4b-mixed` and `rag.py evaluate` (≈ 30 s,\nno cost). The rankings and `metrics.csv` must be byte-identical to the downloaded ones. This proves the local\npipeline reproduces the released jua run before Gemini is compared with it.\n\n---\n\n## 3. What has to be implemented first\n\n1. **An embedding provider for gemini-embedding-2 in `scripts/embedding/`.** The `openai` and `gemini`\n providers of the embedding plan §5.3 were never implemented.\n - **Route A: OpenRouter, recommended.** OpenRouter's `/api/v1/embeddings` is OpenAI-compatible, so it can\n be either a small `openrouter` provider or the `tei` provider in `openai_compat` mode with a base URL and\n headers. It needs:\n - provider pinning in the request: `provider: {only: [google-ai-studio], allow_fallbacks: false,\n data_collection: deny}`;\n - the reported `usage` added up into the ledger.\n - **Route B: direct Google (`google-genai`, `GEMINI_API_KEY`)**, as designed in §5.3 of the embedding\n plan, optionally with the Batch API (`--gemini-batch`).\n2. **The registry entry** (`models.yaml`, from embedding plan §5.2), with:\n - `dim: 3072` (native; no `output_dimensionality`);\n - `query_template: \"task: search result | query: {text}\"`;\n - `document_template: \"title: none | text: {text}\"` (decision D3, §8.2: **confirm `title: none` before\n the run**, since changing it later means re-embedding);\n - `price: {usd_per_million_tokens: 0.20, checked: 2026-11-08}`.\n\n **Check the prefixes against the current gemini-embedding-2 docs while implementing.** OpenRouter lists no\n `supported_parameters` for this model, so the task must go in the text and not in a `task_type` field.\n3. **Cost ledger for API models** (embedding plan §9.2): tokens × price, with `source=provider_reported` when\n the response has `usage`.\n4. **Length guard:**\n - The longest S2 text is 8,103 Qwen3 tokens. Gemini counts fewer tokens than Qwen3 on this corpus (sample\n of 2026-09-25: Gemini max 7,253 against Qwen3 8,119). With the ≈ 7-token prefix, every text fits in\n 8,192.\n - The guard stays on the Qwen3 count plus a margin. Gemini `countTokens` is used only for texts above\n 7,000 Qwen3 tokens.\n - Also confirm that the API does not truncate silently: send one over-long synthetic text and expect an\n error.\n5. **API-model check** (plan §5.4): embed the parity sample twice. The norms must be 1 and the results\n deterministic to about 1e-6. Also check that the reported dimension is 3072.\n6. **Full store (decided 2026-11-08).** Embed all 101,943 unique texts, the same store jua has.\n - `rag.py retrieve` and `evaluate` then run on all five strategies (S1, S2, S2c, S3, S4) without changes.\n - Only S1 and S2 4k go on to generation.\n7. **Experiment file** `scripts/rag/experiments/gemini_core.yaml`:\n - `contexts: runs/contexts/gemini-emb-2/irpf`;\n - sets `[S1_budget4000, S2_budget4000]`;\n - llms `[gpt-5.6-luna, sabia-4]`;\n - prompt `answer_v1`.\n\n Answers go to `runs/answers/gemini-emb-2/irpf/answer_v1/<llm>/<set>/`. The embedding slug is in the path,\n so nothing of the jua runs is touched.\n8. **Analysis.** `nuggets.py scoretable` / `analyze` must pair a Gemini run with the jua run of the same\n generator and set (paired bootstrap and permutation, as in phase 5 §3). Check whether `--runs` globs\n across embeddings already work; otherwise add the jua ↔ Gemini pairs to the comparison list.\n\nTests: extend `scripts/embedding/tests` with a mocked OpenRouter/Gemini response (usage, dimension, error on\nan over-long input). No network.\n\n---\n\n## 4. Cost estimate\n\n### 4.1 Embedding\n\n| Text set | Unique texts | Tokens (Qwen3 count) | OpenRouter / Google standard ($0.20 / M) | Google Batch API ($0.10 / M) |\n|---|---:|---:|---:|---:|\n| **S1 ∪ S2** (= S2; S1 is a subset) | 72,960 | 16.46 M (+0.5 M prefix) | **≈ $3.4** | ≈ $1.7 |\n| all strategies (S3 groupings, caput variants) | 101,943 | 27.88 M (+0.7 M) | ≈ $5.7 | ≈ $2.9 |\n| 715 queries | 715 | < 0.1 M | < $0.02 | — |\n| determinism check, smoke tests | — | — | < $0.10 | — |\n\n- The Qwen3 counts are an upper bound: Gemini's tokenizer gave ≈ 10 % fewer tokens on the sample.\n- The revoked RIR/1999 is embedded too, as with jua. Retrieval excludes it (`corpus_exclusions.yaml`), and\n the store stays comparable with jua's.\n- **Prices checked on 2026-11-08:**\n - OpenRouter catalogue: `google/gemini-embedding-2`, $0.20 / M prompt tokens on `google-ai-studio`,\n `google-vertex/us` and `google-vertex/global` ($0.22 on `google-vertex/eu`), context 8,192.\n - Google's pricing page: text $0.20 standard, $0.10 Batch. The free tier is free of charge but\n rate-limited, and free-tier data may be used by Google.\n\n**Route choice:**\n- **OpenRouter (recommended):** one key and one ledger with the rest of the experiment. The cost difference\n from the Batch API is ≈ $1.7.\n- **Google Batch API:** the cheapest, but asynchronous. It needs the direct provider and the billing-report\n import for the ledger (plan §9.2, §10).\n- **Google free tier:** possible for $0, but the rate limits make 73k long texts slow. The cost would also no\n longer be reportable as a market price.\n\n**Decided (2026-11-08):** OpenRouter, all texts: **≈ $5.7**.\n\n### 4.2 Core grid (recommended): Luna + Sabiá-4 × S1 4k + S2 4k, 715 questions\n\n> **Update 2026-11-08, after the user's decisions (§6).** All texts are embedded, so the embedding line is\n> ≈ $5.7 instead of $3.4, and E3 is part of the core.\n>\n> | | Estimate | With 20 % contingency |\n> |---|---:|---:|\n> | **Core total** | ≈ $28.8 | ≈ $35 |\n> | OpenRouter | ≈ $19.6 | ≈ $23.5 |\n> | Maritaca | ≈ $9.2 | ≈ $11 |\n>\n> The table below keeps the original S2-only estimate.\n\nThe per-call costs are measured on the jua runs: `runs/costs.csv` and `nuggets/scoring/costs.csv`. Generation\nper run is scaled from the 685 / 650 non-pilot calls of the full runs to 715. Context lengths are the same,\nbecause the 4k budget is fixed.\n\n| Step | Calls | Route | Estimate |\n|---|---:|---|---:|\n| Embedding S2 texts + queries (§4.1) | ≈ 1,000 requests | OpenRouter | $3.4 |\n| Retrieval, retrieval test, contexts (`retrieve`, `evaluate`, `context`) | 0 | local | $0 |\n| Generation Luna S1, S2 | 1,430 | OpenRouter (OpenAI flex) | ≈ $1.0 |\n| Generation Sabiá-4 S1, S2 | 1,430 | Maritaca, direct | ≈ $9.2 (≈ R$ 47) |\n| Scoring, 4 runs × 715 ($0.0023 / answer) | 2,860 | OpenRouter (Gemini 3.8 Flash flex) | ≈ $6.6 |\n| Context support, Gemini S1 + S2 4k ($0.0044 / question) | 1,430 | OpenRouter | ≈ $6.3 |\n| **Total** | | | **≈ $26.5** |\n| of which OpenRouter | | | ≈ $17.3 |\n| of which Maritaca | | | ≈ $9.2 |\n\nWith a 20 % contingency: **≈ $32 ($21 OpenRouter + $11 Maritaca)**. A `stratified_30` pilot first costs about\n4 % of this (≈ $1.2) and can be skipped: the generation and scoring pipeline is unchanged and was validated\nin the jua pilot.\n\n### 4.3 Optional extensions (each independent)\n\n| Extension | Adds | Estimate |\n|---|---|---:|\n| E1: Terra S1 + S2 4k | the strongest generator; tests whether a better context finally beats closed book | ≈ $13.3 OR (gen $10.0 + scoring $3.3) |\n| E2: Sabiazinho-4 S1 + S2 4k | completes the four generators of the jua grid | ≈ $5.2 (Maritaca $1.9 + OR $3.3) |\n| E3: embed the remaining texts (S3, S2c, S4) | the free retrieval test for all five strategies | ≈ $2.3 OR |\n| E4: Luna S2c 4k (needs E3) | the best jua Luna score (0.314) | ≈ $2.1 OR |\n| E5: cross-set scoring (Gemini 3.1 Pro and Qwen3.8-Max nugget sets), Sabiá-4 S1/S2 | nugget-creator robustness, as in phase 5 §7.3 | ≈ $6.3 OR |\n\nCore + all extensions: ≈ $62 (≈ $45 OpenRouter, ≈ $17 Maritaca), before contingency.\n\n### 4.4 Budget status and caps\n\n- **OpenRouter key:**\n - On 2026-10-24 it had $5.22 left of its $150 spending limit. This is a limit on the key, not the\n account's prepaid credit. Reading the account credit needs a management key.\n - **The user raised the limit to $200 on 2026-11-08.** `GET /api/v1/key` at 17:15 gave usage $144.78\n and **$55.22 left**.\n - That covers the core grid (≈ $23.5 OpenRouter with contingency) and leaves ≈ $32 for extensions. E2 and\n E4 fit in it; E5 too, but not all three together with the contingency.\n - Check `GET /api/v1/key` before each paid step.\n- Pass `--budget` on every run, as usual. The ledgers are cumulative (`runs/costs.csv`,\n `nuggets/scoring/costs.csv`, `embeddings/costs.csv`), so the caps are the current total plus the step's\n estimate × 1.2.\n- Stop and report if any step goes above its estimate.\n\n---\n\n## 5. Order of execution (each step waits for the user's go-ahead)\n\n1. **Set up** (no cost):\n - add the missing keys to `.env`;\n - download and verify the HF files (§2.2);\n - reproduce the jua retrieval and evaluation byte for byte.\n2. **Implement** the provider, the registry entry, the ledger and the tests (§3). Confirm `title: none`\n (D3).\n3. **Embed** all texts and the queries with gemini-embedding-2 (≈ $5.7).\n - `embed.py corpus --model gemini-emb-2 --dry-run` first: it gives the token count and the expected\n cost.\n - Then the determinism check, then the full run.\n4. **Retrieve and evaluate** all five strategies ($0). Compare with jua (§1.3). **This is the gate: report\n and decide here.**\n5. **Contexts** S1 / S2 4k (`rag.py context`, $0). Compare gold coverage per question with jua\n (`summary.csv`).\n6. **Generate** the core grid (≈ $10.2).\n7. **Score and run context support** (≈ $12.9). Then run `scoretable` and `analyze`, and pair each run with\n jua.\n8. **Write the results note:**\n - Gemini vs jua per generator and set;\n - S1 → S2 under each embedding;\n - context support and linkage;\n - the decision on the extensions of §4.3.\n\n## 6. Decisions (user, 2026-11-08)\n\n1. **Route: OpenRouter.** Pin the provider to `google-ai-studio`, with no fallbacks and `data_collection:\n deny`.\n2. **D3: `title: none`.** Every embedding model then gets exactly the same chunk string. Gemini's template\n adds only its fixed task prefix.\n3. **Terra (E1) is not added for now.** The core grid stays Luna + Sabiá-4 × S1 / S2 4k.\n4. **All texts are embedded (E3 is in the core),** so the retrieval stage can be checked fully on all five\n strategies.\n5. **OpenRouter key limit: $200.** It has $55.22 left (§4.4).\n","20261108_175117_gemini_embedding_2_setup_embedding_and_retrieval_gate.md":"# gemini-embedding-2: setup, corpus embedding and the retrieval gate\n\n**Generated:** 2026-11-08 17:51:17 (local time, from `date +%Y%m%d_%H%M%S`).\n**Implements:** steps 1–5 of `20261108_153258_gemini_embedding_2_comparison_plan.md` §5. The user's decisions of\n2026-11-08 (plan §6) were: OpenRouter route, `title: none`, no Terra, all texts embedded.\n**Cost:** **$26.91** in total for steps 1–8 (§7.3). Embedding alone is **$5.08** billed (`embeddings/costs.csv`):\n\n| Step | Cost |\n|---|---:|\n| smoke check | $0.00001 |\n| determinism check | $0.035 |\n| queries | $0.005 |\n| corpus | $5.036 |\n\n- Plan estimate: ≤ $5.72.\n- OpenRouter key after this step: usage $149.86 of the $200 limit, **$50.14 left**.\n\n**Status:**\n- Stopped at the gate (plan §1.3, step 4).\n- **User decision (2026-11-08): B, then A.**\n- B (context support) is done: §6.\n- A (generation and scoring of the core grid) is done: §7.\n\n## 1. Step 1: Hugging Face download and the jua reproduction\n\n- **Source:** private repo `eduseiti/BR-TaxQA-R-RAG-eval`, pinned to commit `af37fda`.\n- **Downloaded:** `embeddings/**`, `runs/retrieval/**`, `runs/contexts/**`, and the caches\n `raw/runs_answers_cache.tar.gz` and `raw/nuggets_scoring_cache.tar.gz`.\n- **Staging folder:** `../hf_rag_eval_af37fda/`.\n- **Checksums:** all 115 files pass `sha256sum -c` against the repo's `SHA256SUMS`.\n- **What was copied into the checkout:**\n - only the 51 files that git does not track;\n - the 60 tracked files are identical to the download;\n - the 2 embedding manifests that differ only by the release's path rewrites were left as they are in git.\n- **Stale files moved aside to `../stale_jua_20261008/`:** the 2026-10-08 jua store (115,582 rows) and its\n rankings.\n- **Vectors:** the restored `vectors.npy` / `texts.csv` / `chunk_map.csv.gz` match the SHA-256 in the git\n manifest.\n- **Caches:**\n - both archives held only `<cache dir>/<sha256>.json` regular files;\n - unpacked: `runs/answers/cache/` 15,874 files, `nuggets/scoring/cache/` 22,688 files.\n- **Reproduction:** `rag.py retrieve --embedding jua-4b-mixed --run-name irpf_repro` followed by `evaluate`\n gives:\n - rankings (5 strategies) byte-identical to the release;\n - `metrics.csv`, `comparisons.csv`, `reachability.csv` and the per-question / per-item / per-chapter tables\n byte-identical too.\n\n The scratch run was then deleted.\n- **CLI quirk:** `hf download … --include a b c` treated part of the list as file names and skipped\n `SHA256SUMS`. Fetch it separately, as was done here.\n\n## 2. Step 2: the OpenRouter embedding provider\n\n**New files:**\n- `scripts/embedding/embedding/providers/openrouter.py`: `POST /api/v1/embeddings`. It provides:\n - the `provider` routing block from `models.yaml`;\n - a check of the served provider on every reply;\n - `usage.prompt_tokens` and `usage.cost` added up for the ledger;\n - retries on 408/429/5xx and on 200-with-error replies;\n - an optional per-run budget (`BudgetExceeded`).\n- `tests/test_openrouter.py`: 7 tests with a mocked HTTP session. All 35 embedding tests pass.\n\n**Changes to existing files:**\n- `config.py`: new fields `api_key_env`, `routing`, `served_provider`.\n- `runner.pack`: `solo_above` sends texts above 6,000 guard tokens alone. The provider then checks each one's\n reported token count against 8,192.\n- `costs.py`: `api_row` (`provider_reported` rows, `billing_unit=tokens`) and `ledger_total`.\n- `embed.py`:\n - the API usage of `check`, `parity`, `corpus` and `queries` goes to the ledger;\n - `--budget` is **required** for token-priced models. It is a cap on the `embeddings/costs.csv` total; the\n run refuses to start if the ledger plus the estimate is over it;\n - token-priced dry runs;\n - `parity` for API models is a **determinism check**: the sample is embedded twice and compared, and\n `parity.json` is written with the server fingerprint, so the parity gate works unchanged.\n- `models.yaml`: entry `gemini-emb-2`:\n - model `google/gemini-embedding-2`, pinned to `google-ai-studio`, no fallbacks, `data_collection: deny`;\n - 3,072 dimensions;\n - templates `task: search result | query: {text}` and `title: none | text: {text}`, as on Google's\n embeddings page, checked on 2026-11-08: gemini-embedding-2 takes no `task_type`;\n - price $0.20 / M tokens;\n - batches of ≤ 50 inputs / 20,000 tokens, 8 concurrent.\n\n**Facts measured on 2026-11-08:**\n- **The API truncates over-long inputs silently.** A 17,386-token input was accepted (200) and billed. Google's\n page says the same.\n- **Gemini counts fewer tokens than Qwen3.** On the 40 longest texts (with the prefix), Gemini `countTokens`\n is 0.83–0.91 × the Qwen3 count, max 7,259. So the Qwen3 guard (max 8,110 with the prefix, limit 8,192) is a\n safe upper bound.\n- Over the whole corpus the provider billed 25.18 M tokens, against 28.59 M by the Qwen3 count (0.88 ×).\n- **The output is deterministic.** Two runs of the parity sample are bit-identical (max |diff| 0), unit-norm,\n 3,072 dimensions, and give the same top-1 for 16/16 queries.\n\n**New parity sample: `scripts/embedding/parity_sample_20261108.json`.**\n- Reason: the 2026-09-25 sample (`parity_sample.json`) names texts that the 2026-10-09 re-segmentation\n changed.\n- The new one was built with the same rule (`embed.py parity --make-sample --sample …`).\n- The jua file was left untouched, since it is jua's provenance.\n\n## 3. Step 3: embedding (`embeddings/gemini-emb-2/`)\n\n```bash\nE=scripts/embedding/embed.py; P=.venv/bin/python\n$P $E check --model gemini-emb-2\n$P $E parity --model gemini-emb-2 --sample scripts/embedding/parity_sample_20261108.json --budget 0.2\n$P $E corpus --model gemini-emb-2 --budget 9.77 --no-progress # ledger $2.90 + 1.2 × $5.72\n$P $E queries --model gemini-emb-2 --budget 9.9 --no-progress\n```\n\n| Store | Shape | Provider tokens | Billed | Requests | Retries / errors | Wall |\n|---|---|---:|---:|---:|---|---:|\n| corpus | 101,943 × 3,072 | 25,179,092 | $5.036 | 2,186 | 0 / 0 | 11.7 min |\n| queries (`irpf`) | 715 × 3,072 | 25,318 | $0.005 | 15 | 0 / 0 | 5 s |\n\n**Inputs:**\n- Same corpus as jua: `chunks_all.csv.gz`, SHA `a6087b7f…`, all 101,943 unique texts.\n- Same question file: SHA `097abfc4…`.\n- The query folder is called `irpf` so that the paths match jua's. Gemini's template has no free instruction;\n the fixed task prefix replaces it.\n\n## 4. Step 4: retrieval and the legal-provision test\n\n```bash\nR=scripts/rag/rag.py; G=runs/retrieval/gemini-emb-2/irpf\n$P $R retrieve --embedding gemini-emb-2\n$P $R evaluate --retrieval $G # either_containment_merge_skip (main)\n$P $R evaluate --retrieval $G --dedup containment --strategies S1,S2,S3 --comparisons S1:S2,S2:S3 --eval-id either_containment_skip\n$P $R evaluate --retrieval $G --dedup containment --comparisons S1:S2,S2:S3,S2:S2c,S3:S4,S1:S2c --eval-id v2c_either_containment_skip\n$P $R evaluate --retrieval $G --dedup containment --eval-id v2d_either_containment_skip\n```\n\n- The parameters of all four evaluations are identical to jua's (checked in their manifests).\n- Corpus exclusions: the same (RIR/1999).\n\n### 4.1 Main evaluation, recall within the token budget (what the generator gets; gold = all)\n\n| Strategy | Article 2k jua / gem | **Article 4k jua / gem** | Article 8k jua / gem | Provision 4k jua / gem | Document 4k jua / gem |\n|---|---|---|---|---|---|\n| S1 | 0.296 / 0.318 | **0.398 / 0.413** | 0.492 / 0.515 | 0.369 / 0.380 | 0.621 / 0.598 |\n| S2 | 0.425 / 0.451 | **0.503 / 0.515** | 0.600 / 0.597 | 0.420 / 0.435 | 0.700 / 0.682 |\n| S2c | 0.391 / 0.451 | 0.480 / 0.511 | 0.579 / 0.592 | 0.417 / 0.438 | 0.686 / 0.664 |\n| S3 | 0.424 / 0.451 | 0.507 / 0.517 | 0.606 / 0.609 | 0.429 / 0.454 | 0.691 / 0.671 |\n| S4 | 0.397 / 0.453 | 0.487 / 0.517 | 0.593 / 0.607 | 0.427 / 0.454 | 0.680 / 0.660 |\n\n### 4.2 Ranking quality (unit view: the first k distinct articles, no token budget)\n\n| Strategy | MRR jua / gem | nDCG@10 jua / gem | recall@1 jua / gem | recall@10 jua / gem | recall@20 jua / gem |\n|---|---|---|---|---|---|\n| S1 | 0.524 / **0.614** | 0.441 / **0.525** | 0.186 / 0.252 | 0.529 / **0.610** | 0.622 / 0.676 |\n| S2 | 0.555 / **0.638** | 0.478 / **0.546** | 0.206 / 0.254 | 0.581 / **0.630** | 0.661 / 0.702 |\n| S2c | 0.545 / 0.642 | 0.473 / 0.548 | 0.192 / 0.259 | 0.577 / 0.625 | 0.658 / 0.696 |\n| S3 | 0.552 / 0.630 | 0.474 / 0.537 | 0.206 / 0.249 | 0.574 / 0.618 | 0.648 / 0.685 |\n| S4 | 0.543 / 0.634 | 0.464 / 0.537 | 0.190 / 0.254 | 0.559 / 0.608 | 0.633 / 0.680 |\n\n### 4.3 Paired tests, Gemini − jua\n\nPer question, article level, gold = all. 5,000 bootstrap resamples (95 % CI) and a sign-flip permutation test.\n\n| Metric | Strategy | Diff | 95 % CI | p | Questions better / worse |\n|---|---|---:|---|---:|---|\n| article recall, 4k budget | S1 | +0.015 | (−0.011, +0.041) | .27 | 101 / 86 |\n| | S2 | +0.012 | (−0.014, +0.037) | .37 | 100 / 82 |\n| | S2c | **+0.031** | (+0.006, +0.054) | .017 | 102 / 69 |\n| | S3 | +0.009 | (−0.014, +0.034) | .45 | 97 / 82 |\n| | S4 | **+0.030** | (+0.006, +0.054) | .014 | 109 / 75 |\n| provision recall, 4k | S1 / S2 | +0.011 / +0.016 | n.s. | .42 / .22 | |\n| document recall, 4k | S1 / S2 | −0.024 / −0.018 | (−0.050, +0.001) / (−0.040, +0.002) | .06 / .10 | |\n| article recall@10, unit view | S1 | **+0.081** | (+0.059, +0.105) | < .001 | 132 / 41 |\n| | S2 | **+0.049** | (+0.027, +0.070) | < .001 | 104 / 40 |\n\nThese tests are ad hoc, run for this note. `rag.py compare` works within one retrieval run, not across\nembeddings.\n\n### 4.4 Why the ranking gain mostly disappears within 4k tokens\n\n*Corrected on 2026-11-08 after the user's question.* The first version blamed mainly the longer texts. A\nper-article decomposition shows that is only part of the cause. Inputs: `per_item.csv.gz` of the main evaluation\nand the 4k `contexts.jsonl.gz`, ad hoc script.\n\n**1. Most of Gemini's rank gains do not cross the context boundary.**\n\nA 4k context holds the first ≈ 10 texts of the ranking, plus a few short texts further down that fit in the\nbudget left (`overflow: skip`). Recall changes only when a gold article crosses that boundary.\n\n| What Gemini does to the gold article (1,944 reachable gold articles, 553 questions) | S1 | S2 |\n|---|---:|---:|\n| ranks it higher, already in jua's 4k context (median text rank S1 5 → 2, S2 8 → 2) | 187 | 243 |\n| ranks it higher, still outside Gemini's 4k context (median S1 206 → 66, S2 308 → 110) | 593 | 421 |\n| ranks it higher and **brings it into** the 4k context | 140 | 155 |\n| ranks it lower and **pushes it out** of the 4k context | 109 | 117 |\n| in the 4k context: both / only Gemini / only jua / neither | 432 / 143 / 115 / 1,254 | 573 / 163 / 126 / 1,082 |\n\n- Net: +28 (S1) and +37 (S2) gold articles, which is the +0.012–0.015 of §4.1.\n- MRR and the unit-view recall@k reward the first two rows: moves inside the context and moves in the deep\n tail.\n- The unit view counts *distinct articles*, so its top 10 reaches deeper than the ≈ 10 texts of a 4k context.\n At a fixed number of **texts** (raw view) the gain is smaller:\n\n | | raw@1 | raw@5 | raw@10 | raw@20 |\n |---|---:|---:|---:|---:|\n | S1 | +0.043 | +0.028 | +0.044 | +0.052 |\n | S2 | +0.034 | +0.046 | +0.038 | +0.031 |\n\n Unit@10 gives +0.081 / +0.049.\n\n**2. Longer texts cost about half of what is left.**\n- Gemini's top-ranked texts are longer: the mean length of the top 10 is 535 tokens against jua's 454 (S1),\n and 411 against 341 (S2). That is +18–21 %; the medians are 450 / 345 and 269 / 232.\n- In S1, the unbroken block of top-ranked texts in the 4k context is 7.6 texts for Gemini and 9.4 for jua.\n- Recall from that block alone:\n\n | | Recall |\n |---|---:|\n | jua | 0.389 |\n | Gemini | 0.400 |\n | Gemini with jua's block size | 0.423 |\n\n- So the better ranking is worth ≈ +0.03 at an equal number of texts, and the shorter block costs ≈ −0.02.\n- Of the 115 articles Gemini loses in S1, 18 fall between the two block sizes. The other 97 are ranked deeper\n than jua's whole block, so they are true ranking losses.\n- **S2 cannot be split this way.** `containment_merge` drops or merges sub-units of articles already in the\n context, so the unbroken top block is only 2.5–3.2 texts there.\n\n**3. Two things that 4k recall does not see, and that may still help the answers:**\n- **Position:** where both contexts hold the gold article, Gemini puts it near the top (median text rank 2\n against 5–8). Recall ignores order.\n- **Non-gold content:** the contexts share only 25–29 % of their texts (§4.5). Recall counts only the\n provisions the P&R cites. Context support (nuggets) measures the rest.\n\n**Other results:**\n- The caput variants S2c and S4 gain +0.03 at 4k (significant) and reach S2's level with Gemini.\n- Document recall is slightly lower with Gemini (−0.02, p .06–.10).\n- **S1 → S2 still holds with Gemini** at 4k: +0.10 article recall (jua +0.105).\n\n### 4.5 Step 5: generator contexts (`runs/contexts/gemini-emb-2/irpf/`, $0)\n\n`rag.py context --retrieval runs/retrieval/gemini-emb-2/irpf --sets S1@budget=4000,S2@budget=4000` builds the two\nsets with the same parameters as jua's: `containment_merge`, `skip`, `score`, `context_v2`, annex rule\n`either`.\n\n| Set | Texts | Article recall | Document recall | Provision recall | Item Jaccard with jua's context (mean / median) | Contexts identical to jua's |\n|---|---:|---:|---:|---:|---|---:|\n| S1 4k | 9.4 (jua 11.2) | 0.413 (0.398) | 0.598 (0.621) | 0.380 (0.369) | 0.29 / 0.28 | 5 / 715 |\n| S2 4k | 10.5 (jua 12.6) | 0.515 (0.503) | 0.682 (0.700) | 0.435 (0.420) | 0.25 / 0.23 | 2 / 715 |\n\n**The contexts are mostly different texts, but the gold coverage is about the same.** Whether the new texts\nhold more of the answers' content (nuggets) cannot be measured by gold-article recall. Context support\n(plan §4.2, ≈ $6.3 for both sets) measures exactly that.\n\n## 5. Gate: what was found and the options\n\n**Result:**\n- Gemini ranks the cited provisions clearly better than jua: MRR +0.08–0.10 and top-10 article recall +0.05 /\n +0.08, p < .001.\n- Inside the 4k budget the advantage is small and not significant for S1 and S2 (+0.01–0.015).\n- The S1 → S2 gain is the same under both embeddings.\n\n**Options** (costs from plan §4.2; OpenRouter key: $50.14 left):\n\n| Option | What it answers | Cost |\n|---|---|---:|\n| **A. Core grid as planned** (context support, then Luna + Sabiá-4 × S1 / S2 4k, scoring) | does S2 > S1 hold for the answers under a second embedding? Do Gemini's different contexts change answer quality? | ≈ $23 (≈ $13.6 OpenRouter + $9.2 Maritaca) |\n| **B. Context support first** (S1 and S2 4k), then decide on generation | do Gemini's contexts hold more nugget content than jua's? | ≈ $6.3 OpenRouter, part of A |\n| C. Stop here | the paper reports the retrieval comparison only | $0 |\n\n**Recommendation: B, then A.**\n- B is part of A anyway, so doing it first costs nothing extra.\n- The contexts are mostly different texts, so their nugget support can differ even though gold-article recall\n does not.\n- The S1 → S2 answer comparison under a second embedding is the robustness result the paper needs, whatever\n B shows.\n\n## 6. B: context support of the Gemini contexts (2026-11-08)\n\n```bash\nC=runs/contexts/gemini-emb-2/irpf\n$P scripts/nuggets/nuggets.py --out nuggets/scoring --sample all --workers 24 --budget 67.8 \\\n ctxsupport --contexts $C/S1_budget4000 $C/S2_budget4000 # ledger $59.82 before\n$P scripts/nuggets/nuggets.py --out nuggets/scoring --sample all scoretable\n```\n\n**Cost:**\n- **$6.42** billed: 1,363 judge calls (Gemini 3.8 Flash, `google-ai-studio`), plus 67 cache hits, 0 failed.\n- `nuggets/scoring/costs.csv` total: $66.24.\n\n**Setup fixes:**\n- **Missing input copy.** `nuggets/full/input/questions.jsonl` is gitignored and was not released. It was\n rewritten with the pipeline's own loader (`data.load_questions(dataset/questions.jsonl)`, the code of `sample`),\n without rerunning `sample`, which would rewrite the tracked `sample.json`.\n- `dataset/questions.jsonl` matches the `dataset_sha256` in `sample.json`.\n\n**Code change (no LLM): keys for the second embedding.**\n- Before, `scoretable` and `analysis.nugget_labels` named a run or context set by the last path component, so\n `S2_budget4000` of both embeddings would collide.\n- `scoring.context_key` keeps the bare id for `jua-4b-mixed` and gives other embeddings `S2_budget4000@gemini-emb-2`.\n- `scoring.PAIRS` gains:\n - jua vs Gemini for S1 and for S2;\n - Gemini S1 → S2.\n- **Check:** the regenerated `runs.csv`, `comparisons.csv` and `per_question.csv.gz` are identical to git. The\n jua rows of `ctxsupport_per_question.csv.gz` are identical too.\n- The table also gains the jua `oracle_budget16000` (57 questions) and `wrong-S2` (70) context sets of the\n §10 audit of the phase 5 note. They had never been tabulated.\n\n### 6.1 Result: Gemini's contexts hold more of the answers' content\n\nVital nuggets fully supported by the 4k context (Flash judge with `assign_ctx_v1`), 714 paired questions,\npaired bootstrap / permutation / chapter-cluster CI:\n\n| Context | jua | Gemini | Gemini − jua (95 % CI) | p | cluster CI |\n|---|---:|---:|---|---:|---|\n| S1 4k, V_strict | 0.397 | 0.439 | **+0.042** (0.024, 0.061) | < .001 | (0.026, 0.061) |\n| S2 4k, V_strict | 0.411 | 0.458 | **+0.047** (0.029, 0.065) | < .001 | (0.028, 0.062) |\n| S1 4k, V | 0.509 | 0.550 | +0.041 | < .001 | |\n| S2 4k, V | 0.524 | 0.569 | +0.046 | < .001 | |\n| contradicts at least one nugget, S1 / S2 | 0.025 / 0.027 | 0.025 / 0.022 | 0.000 / −0.004 | 1.0 / .65 | |\n\n| S1 → S2 within an embedding (V_strict) | Diff | 95 % CI | p |\n|---|---:|---|---:|\n| jua | +0.014 | (0.002, 0.026) | .027 |\n| Gemini | +0.018 | (0.006, 0.031) | .005 |\n\n**Reading:**\n- Measured against the gold nuggets, the Gemini contexts are clearly better: about +0.045 V_strict. That is\n three times the S1 → S2 effect.\n- Their recall of the provisions the P&R cites is about the same as jua's (§4.1).\n- So the extra support comes from what §4.4 point 3 could not see: texts other than the cited articles that\n state the answer's facts, and the longer texts Gemini prefers.\n- For reference, the oracle 4k context (the cited articles only) reaches 0.483. Gemini S2 4k (0.458) closes\n about two thirds of jua S2's gap to it (0.411 → 0.483: 0.047 of 0.072). This compares 596 oracle questions\n with 715; the comparison is indicative only.\n- S2 still beats S1 under Gemini, by a margin like jua's.\n\n## 7. A: generation and scoring of the core grid (2026-11-08)\n\n```bash\n$P scripts/rag/rag.py run --experiment scripts/rag/experiments/gemini_core.yaml --budget 63 # runs/costs.csv $47.54 before\n$P scripts/nuggets/nuggets.py --out nuggets/scoring --sample all --workers 24 --budget 73.2 \\\n score --runs \"runs/answers/gemini-emb-2/irpf/*/*/*\" # ledger $66.24 before\n$P scripts/nuggets/nuggets.py --out nuggets/scoring --sample all scoretable\n```\n\n**Generation:**\n- 4 runs × 715 answers, 0 errors, 26 min.\n- 2,726 new calls; 67 per generator were cache hits. For 67 questions Gemini's S1 and S2 contexts are\n identical (jua: 36), so the S2 request reused the S1 response.\n- Billed **$9.98**: Sabiá-4 $9.04 (Maritaca, list price at R$ 5.08/US$), Luna $0.95.\n\n**Scoring:**\n- 2,369 new judge calls (the rest were abstentions, which are not judged, or cache hits), 0 failed.\n- Billed **$5.43**.\n\n**Tables:**\n- The regenerated `tables/gold-v0-auto/gemini-3.8-flash/all/` add 4 rows to `runs.csv` and 42 to\n `comparisons.csv`.\n- No jua row changed.\n\n### 7.1 Answer scores (715 questions; jua rows from the phase 5 note)\n\n| Generator | Context | V_strict | V | A_strict | W | contra. | abstained | chars |\n|---|---|---:|---:|---:|---:|---:|---:|---:|\n| Luna | closed book | 0.259 | 0.420 | 0.220 | 0.378 | 0.266 | 0.003 | 672 |\n| Luna | S1 4k jua | 0.271 | 0.387 | 0.235 | 0.351 | 0.080 | 0.241 | 624 |\n| Luna | **S1 4k Gemini** | **0.296** | 0.418 | 0.259 | 0.382 | 0.066 | 0.197 | 672 |\n| Luna | S2 4k jua | 0.299 | 0.424 | 0.261 | 0.388 | 0.085 | 0.168 | 692 |\n| Luna | **S2 4k Gemini** | **0.327** | 0.466 | 0.286 | 0.427 | 0.091 | 0.133 | 743 |\n| Luna | oracle 4k (596) | 0.338 | 0.475 | 0.299 | 0.435 | 0.065 | 0.128 | 673 |\n| Sabiá-4 | closed book | 0.239 | 0.379 | 0.213 | 0.350 | 0.382 | 0.013 | 1,016 |\n| Sabiá-4 | S1 4k jua | 0.290 | 0.446 | 0.257 | 0.409 | 0.115 | 0.054 | 787 |\n| Sabiá-4 | **S1 4k Gemini** | **0.320** | 0.478 | 0.283 | 0.439 | 0.112 | 0.050 | 822 |\n| Sabiá-4 | S2 4k jua | 0.317 | 0.470 | 0.285 | 0.433 | 0.112 | 0.034 | 822 |\n| Sabiá-4 | **S2 4k Gemini** | **0.328** | 0.491 | 0.287 | 0.449 | 0.105 | 0.042 | 828 |\n| Sabiá-4 | oracle 4k (596) | 0.319 | 0.462 | 0.278 | 0.422 | 0.091 | 0.121 | 706 |\n\n### 7.2 Paired comparisons (V_strict, b − a, 714 questions)\n\n95 % paired-bootstrap CI, paired permutation p, chapter-cluster CI.\n\n| Comparison | Luna | Sabiá-4 |\n|---|---|---|\n| **S1 jua → S1 Gemini** | **+0.025** (0.002, 0.048) p .030; cluster (0.003, 0.047) | **+0.029** (0.007, 0.052) p .011; cluster (0.007, 0.050) |\n| **S2 jua → S2 Gemini** | **+0.027** (0.005, 0.050) p .018; cluster (0.003, 0.048) | +0.011 (−0.010, 0.034) p .31 |\n| **S1 → S2, Gemini** | **+0.030** (0.008, 0.053) p .007; cluster (0.005, 0.052) | +0.009 (−0.011, 0.029) p .39 |\n| S1 → S2, jua (phase 5 note) | **+0.028** (0.008, 0.049) p .007 | **+0.027** (0.007, 0.047) p .009 |\n| contradictions, S1 → S2 Gemini | +0.025 p .018 | −0.007 p .62 |\n| contradictions, jua → Gemini (S1 / S2) | −0.014 / +0.006, n.s. | −0.003 / −0.007, n.s. |\n\n**Reading:**\n- **The stronger embedding gives better answers.**\n - Three of the four jua → Gemini comparisons are significant: +0.025 to +0.029 V_strict, robust to\n chapter clustering. That is about the size of the S1 → S2 effect with jua.\n - Sabiá-4 on S2 gains less (+0.011, n.s.).\n - It follows the context support of §6: +0.042 (S1), +0.047 (S2).\n - Retrieval does not raise contradictions.\n - Luna abstains less (S1 24 % → 20 %, S2 17 % → 13 %).\n- **Best scores so far:**\n - Luna: S2 Gemini 0.327, close to its oracle 4k (0.338, on 596 questions).\n - Sabiá-4: S2 Gemini 0.328, above its oracle 4k (0.319) and its jua S2 (0.317).\n - Terra's jua S2 4k (0.341) is still higher. Terra was not rerun (user decision).\n- **S1 → S2 under Gemini: holds for Luna, not for Sabiá-4.**\n - Luna: +0.030, p .007, the same as with jua (+0.028).\n - Sabiá-4: +0.009, p .39, against +0.027 with jua. Sabiá-4's S1 score rises more with Gemini (+0.029) than\n its S2 score (+0.011), so the gap closes.\n - So the segmentation effect is **not** embedding-independent for every generator. With the stronger\n retriever, S1 contexts already carry much of what S2 added for Sabiá-4.\n - The context-level S1 → S2 gain is similar under both embeddings (+0.014 jua, +0.018 Gemini, §6.1). So the\n difference is in how Sabiá-4 uses the two Gemini contexts.\n- Luna's contradiction share rises from S1 to S2 under Gemini (+0.025, p .018). It did not with jua (+0.005).\n This is worth a look before it is reported.\n\n### 7.3 Costs of the Gemini comparison (2026-11-08)\n\n| Step | Ledger | Billed |\n|---|---|---:|\n| embedding: smoke, determinism, queries, corpus | `embeddings/costs.csv` | $5.08 |\n| context support, S1 / S2 4k | `nuggets/scoring/costs.csv` | $6.42 |\n| generation, 4 runs | `runs/costs.csv` | $9.98 (Maritaca $9.04, OpenRouter $0.95) |\n| scoring, 4 runs | `nuggets/scoring/costs.csv` | $5.43 |\n| **Total** | | **$26.91** (OpenRouter $17.87, Maritaca $9.04) |\n\n- Plan estimate (§4.2 update): ≈ $28.8.\n- OpenRouter key: usage $162.66 of $200, **$37.34 left**.\n\n### 7.4 Not done\n\n- **`nuggets.py analyze`** (linkage, utilisation, citations, slices, perturbation) for the Gemini runs:\n - `analysis.py` reads jua's contexts and retrieval through fixed paths (`RETRIEVAL`, `contexts_root /\n context_id`), so the citation and linkage analyses would skip or misread the `@gemini-emb-2` runs;\n - it needs a small change first. The tracked outputs in `analysis/` were not regenerated.\n- **Robustness checks of phase 5 §7:** cross-sets (Gemini 3.1 Pro and Qwen3.8-Max nugget sets, ≈ $3 for the 4\n runs) and the perturbation of the Sabiá-4 S1 → S2 result.\n- Extensions E1 (Terra), E2 (Sabiazinho-4) and E4 (Luna S2c) of the plan.\n","20261108_224913_results_overview_segmentation_and_embedding.md":"# Results so far: legal-text segmentation and embedding for RAG on Brazilian income-tax questions\n\n**Generated:** 2026-11-08 22:49:13 (local time, from `date +%Y%m%d_%H%M%S`).\n**Audience:** readers who do not know this project. It explains what was compared, how it was measured,\nwhat holds, and how sure we are. Details and commands are in the notes listed at the end.\n**Figures:** `docs/figures/20261108_224913_results_overview/`. They are drawn from the result tables by\n`scripts/report/make_results_overview_figures.py`, with no LLM calls. Run it with `python3` from the repo\nroot: it needs matplotlib, which the `.venv` does not have.\n\n---\n\n## 1. In short\n\nThe system answers questions about the Brazilian personal income tax (IRPF) in four steps:\n1. it searches the legislation;\n2. it puts the best passages, up to **4,000 tokens**, in front of a language model;\n3. the model writes the answer;\n4. the answer is scored against the official answer.\n\nThe official answers come from the Receita Federal's *Perguntas e Respostas IRPF 2024*: 715 questions, each with a\nwritten answer and the legal provisions it cites.\n\nTwo results are solid so far:\n\n| | Retrieval stage (finding the cited law) | Answer stage (is the answer right?) |\n|---|---|---|\n| **S2 beats S1.** Indexing articles *and* their paragraphs and incisos beats indexing whole articles only. | **Large:** +0.10 of the cited articles fit in the 4k context (0.40 → 0.50). | **Small but significant:** +0.027–0.028 V_strict for 2 of 4 generators; positive for all 4. Holds under several robustness checks. |\n| **Gemini beats jua.** gemini-embedding-2 beats jua-4b-mixed. | **Better ranking:** MRR +0.08–0.09. But almost the same share of cited articles fits in 4k (+0.01, not significant). | **Significant in 3 of 4 comparisons:** +0.025–0.029 V_strict. The context holds +0.04–0.05 more of the answer's facts. |\n\n- **The gains are small** because answers are capped by two things that neither segmentation nor embedding\n changes:\n - **the cited law does not hold everything the official answers say:** about one key fact in six is the tax\n authority's own interpretation or a filing-program instruction (§4.3);\n - **the language models use only half to two thirds** of the facts their context gives them.\n- **One caveat:** with Gemini, S2's advantage holds for one generator (Luna, +0.030) but disappears for Sabiá-4\n (+0.009, not significant). The segmentation effect is therefore **generator-dependent** under a stronger\n retriever.\n\n![Pipeline](figures/20261108_224913_results_overview/fig1_pipeline.png)\n\n---\n\n## 2. The main results\n\n### 2.1 What was compared, and how it is measured\n\n**Data:**\n- 715 prose questions from the P&R IRPF 2024.\n- They cite 1,916 legal references to 453 documents (laws, decrees, normative instructions, rulings), all\n converted to structured LexML XML.\n- 596 questions cite at least one provision; the other 119 answer without citing any.\n- The revoked 1999 income-tax regulation (RIR/1999) is left out of the search corpus.\n\n**The two factors compared:**\n- **Segmentation:** S1 against S2 (§3).\n- **Embedding model** (the model that turns text into vectors for the search):\n - `jua-4b-mixed`: an open 4B-parameter model, run on our own endpoint, the reference so far;\n - Google's `gemini-embedding-2`, a commercial API model.\n\n**Held fixed:**\n- the 4,000-token context budget;\n- the prompt;\n- the way the context is filled: the best-ranked passages first, without repeating text already included.\n\n**Generators** (the models that write the answers):\n- two size pairs from the same vendor: GPT-5.6 Terra (larger) / Luna (smaller), and Maritaca's Sabiá-4 /\n Sabiazinho-4 (Brazilian models);\n- Gemini was run with Luna and Sabiá-4 only, the two generators where S2 > S1 was significant with jua (cost\n choice).\n\n**Controls:**\n- *closed book*: no context;\n- *oracle*: only the cited articles as context;\n- *wrong context*: another question's passages. It scores 0, as expected.\n\n**The criteria:**\n\n| Stage | Main criterion | What it means |\n|---|---|---|\n| Retrieval | **article recall within the 4k budget** | Share of the articles cited by the official answer that end up in the context the generator sees. |\n| Retrieval | **MRR** (mean reciprocal rank) | How high the first cited article ranks: 1 = first place, 0.5 = second, … |\n| Context | **context support** (V_strict of the context) | Share of the official answer's *vital* facts that the context fully states (an LLM judge reads the context). Unlike recall, it also credits passages the P&R did not cite. |\n| Answer | **V_strict** (headline) | Share of the official answer's *vital* facts (\"nuggets\", §4) that the system answer **fully** states, as judged by an LLM. |\n| Answer | contradictions, abstentions | Share of answers that contradict at least one fact; share of answers that decline to answer. |\n\n**Statistics:**\n- every comparison is **paired**: same questions, only one factor changes;\n- 95 % paired-bootstrap confidence intervals and a paired permutation test (p);\n- a **chapter-cluster bootstrap**, so that no single topic of the P&R carries the result.\n\n### 2.2 Retrieval stage\n\n![Retrieval](figures/20261108_224913_results_overview/fig4_retrieval.png)\n\n**S2 > S1, at every budget and with both embeddings:**\n- At 4k tokens, S2 contexts hold **0.50–0.52** of the cited articles, against **0.40–0.41** for S1.\n- The reason: an S2 hit can be a short inciso instead of a whole long article, so more distinct relevant\n provisions fit in the same budget.\n\n**Gemini ranks much better, but the 4k contexts barely change:**\n\n| 4k budget | S1 jua → Gemini | S2 jua → Gemini |\n|---|---|---|\n| MRR | 0.52 → **0.61** | 0.55 → **0.64** |\n| Recall of cited articles in the top 10 distinct articles | 0.53 → **0.61** (p < .001) | 0.58 → **0.63** (p < .001) |\n| **Recall of cited articles in the 4k context** | 0.398 → 0.413 (+0.015, p .27) | 0.503 → 0.515 (+0.012, p .37) |\n\nWhy the ranking gain mostly vanishes within 4k tokens (measured per article):\n- most of Gemini's rank improvements happen either **inside** the context (from rank ≈ 5 to rank 2) or **deep\n outside** it (from rank ≈ 200 to ≈ 70), so they do not change what the context holds;\n- Gemini prefers longer passages (+18–21 %), so fewer of them fit in 4k.\n\n### 2.3 Answer stage\n\n![Answers](figures/20261108_224913_results_overview/fig5_answers.png)\n\n![Effects](figures/20261108_224913_results_overview/fig6_effects.png)\n\n**S2 vs S1** (jua, all four generators):\n\n| Generator | Result |\n|---|---|\n| Luna | **+0.028** (p .007) |\n| Sabiá-4 | **+0.027** (p .009) |\n| Terra | +0.016 (p .11) |\n| Sabiazinho-4 | +0.005 (n.s.) |\n\n- The gain is positive for every generator and significant for two.\n- In relative terms, +0.028 is a **10 % improvement** over S1 (0.271 → 0.299).\n- **The richer variants add nothing over S2:** S3 (S2 + chapter/section chunks), S2c and S4 (paragraphs that\n repeat the article's opening sentence) all differ from S2 by |Δ| ≤ 0.014, n.s.\n\n**Gemini vs jua** (Luna and Sabiá-4, same strategy):\n\n| | S1 | S2 |\n|---|---|---|\n| Luna | **+0.025** (p .030) | **+0.027** (p .018) |\n| Sabiá-4 | **+0.029** (p .011) | +0.011 (n.s.) |\n\n- The gain is about as large as the S2 > S1 effect.\n- Contradictions do not increase.\n- Luna declines to answer less often: 24 % → 20 % (S1) and 17 % → 13 % (S2).\n\n**Why Gemini helps answers although recall barely moved:**\n- Gemini's contexts are mostly *different* passages: only 25–29 % overlap with jua's.\n- They state more of the official answer's vital facts (context support +0.042 for S1, +0.047 for S2,\n p < .001).\n- Gemini S2 closes about two thirds of jua S2's gap to the cited-articles-only oracle (0.411 → 0.458, against\n 0.483).\n\n![Context support](figures/20261108_224913_results_overview/fig7_context_support.png)\n\n**Best scores so far:**\n- Sabiá-4 with Gemini S2: **0.328**, above its own oracle (0.319).\n- Luna with Gemini S2: **0.327**, close to its oracle (0.338).\n- The highest RAG score is still Terra with jua S2 (0.341), which was not rerun with Gemini.\n- Terra without any context scores **0.351**: the largest generator already knows much of this material.\n Retrieval mainly cuts its contradictions: **27–38 % of closed-book answers contradict a fact, against 8–14 %\n with retrieval**, for all generators.\n\n**Generator-dependent result:**\n- Under Gemini, S2 > S1 holds for Luna (+0.030, p .007) but not for Sabiá-4 (+0.009, p .39).\n- Gemini lifts Sabiá-4's S1 answers so much (+0.029) that S2 adds little on top.\n- At the context level, S2 > S1 still holds under Gemini (+0.018, p .005). The difference is in how Sabiá-4\n uses the two contexts.\n\n### 2.4 How robust are these results?\n\n**S2 > S1, checked thoroughly on jua:**\n\n| Check | Result |\n|---|---|\n| Chapter-cluster bootstrap | CIs stay above 0 for Luna and Sabiá-4. No single chapter carries the gain: S2 wins in 19–24 of 48 chapters per generator. |\n| Nugget subsets (without filing-program facts; only facts all three nugget-making models agree on; without audit-flagged facts) | Same size, still significant. |\n| Two other nugget sets, made by Gemini 3.1 Pro and Qwen3.8-Max | Significant for Terra **and** Sabiá-4 under both. The 4 runs rank in the same order under all three sets (Kendall τ = 1). The primary set is the most conservative. |\n| A second judge (Gemini 3.1 Pro instead of 3.8 Flash), 70 questions | 94.7 % label agreement (κ 0.90). Both judges give the same S1 → S2 difference on that sample. |\n| Randomly damaged nugget sets (below) | Still significant in most replicates at 15–20 % damage, the bar set in the plan beforehand. The sign never flips. |\n\n![Perturbation](figures/20261108_224913_results_overview/fig8_perturbation.png)\n\n**Gemini > jua: checked less, so far.**\n- Paired bootstrap, permutation and chapter-cluster CIs all agree.\n- The judge-on-context result (+0.04–0.05, p < .001) gives an independent, mechanistic explanation.\n- **Not yet run:**\n - the other two nugget sets (≈ $3);\n - the perturbation test;\n - Terra and Sabiazinho-4 with Gemini.\n\n**Pre-registration:**\n- The hypotheses (S2 > S1; S3, S2c and S4 > S2; gains on time-specific facts and on conditions) were written\n down before any answer was scored.\n- The last four were **not** supported. They are reported as such.\n\n---\n\n## 3. Segmentation\n\n### 3.1 The strategies\n\nBrazilian legislation is hierarchical:\n- an **article** (*artigo*) has a *caput* (its opening sentence);\n- it may also have **paragraphs** (§), **incisos** (I, II, …), **alíneas** (a, b, …) and **itens**;\n- articles are grouped into chapters, sections, etc.\n\nAll strategies are cut from **one** table of chunks (one embedding run per model); a strategy is a filter\nover it.\n\n| ID | What is indexed | Chunks (RIR/1999 excluded) | Status |\n|---|---|---:|---|\n| **S1** | each article (or article part, §3.2) and each non-statutory text unit | 20,461 | baseline |\n| **S2** | S1 **plus** every caput, §, inciso, alínea and item as its own chunk. Each carries its *ancestor path* (e.g. \"Art. 35, caput, inciso VI\") but not its siblings. | 68,656 | main hypothesis |\n| S3 | S2 plus grouping chunks (chapter, section, title…) | 72,061 | no gain over S2 |\n| S2c / S4 | S2 / S3 with the caput's opening sentence repeated in paragraph-level chunks | 68,656 / 72,061 | no gain over S2 |\n\n- **Prefix:** every chunk starts with a metadata prefix: `[ document title | ementa (summary, ≤ 128 tokens) ]`.\n This follows the \"Core chunks + metadata\" setting that earlier work on Brazilian legal retrieval found best.\n- **Annexes and non-statutory documents:** they are segmented by content. Rulings and *soluções de consulta*\n are cut into text pieces, and tables are kept as table chunks.\n\n![Segmentation example](figures/20261108_224913_results_overview/fig2_segmentation_example.png)\n\nThis article (who counts as a dependant) is cited by several P&R answers. With S1, a question about a parent\nor a parent-in-law retrieves one 723-token chunk. With S2, it can retrieve just inciso VI (≈ 140 tokens),\nleaving the rest of the budget for other provisions.\n\n### 3.2 Maximum segment length, and what happens to longer units\n\n**The cap is 1,024 tokens per basic chunk.**\n- This applies to articles, top-level provisions, non-statutory text pieces and tables.\n- It includes the metadata prefix.\n- The cap is about **chunk size, not model limits**: the models accept 8k–32k tokens. Non-statutory texts\n and long articles compete with ordinary articles in the same index and the same context budget, so they\n should be about the size of a typical article. 1,024 tokens is about the 97th percentile of article length.\n- Tokens are counted with the larger of two tokenizers (OpenAI `cl100k` and Qwen3). Gemini counts ≈ 12 % fewer,\n so nothing is cut off by the embedding API.\n\n**Units over the cap:**\n\n| Unit over the cap | Handling |\n|---|---|\n| Article (3.8 % of articles: 597 of ≈ 15.8k) | **Split along its structure.** Caput and paragraphs are packed in order into parts up to the cap. A unit too large by itself is replaced by its children (incisos → alíneas → itens). Each part repeats the article label and caput sentence, so \"§§ 3–5\" still reads \"Art. 8º <caput> § 3º …\". Result: 1,626 parts. The largest article, Lei 10.865/2004 art. 8º (16k tokens), became 26 parts. |\n| Non-statutory text (11 % of units) | Cut at the last sentence or numbered-paragraph boundary before the cap; no overlap. |\n| Table | Cut into groups of rows; the caption and header are repeated in every part. |\n| S2 sub-article units (caput, §, inciso…) | Not capped. They are short (median ≈ 160 tokens), and the few long ones are kept as they are (all below 8,192). |\n| Groupings (S3: chapters, sections…) | Separate limit of 8,192 tokens, the model limit. The 193 larger groupings are left out. |\n\n**Checks:**\n- after splitting, ≥ 99.8 % of each file's text is covered;\n- one table row (1,163 tokens) cannot be cut and is flagged.\n\n![Chunk lengths](figures/20261108_224913_results_overview/fig3_chunk_lengths.png)\n\n**Within the 4k context:**\n- when an article and some of its own sub-units are both retrieved, the text is not repeated;\n- the article replaces its already-selected sub-units;\n- a passage that does not fit in the remaining budget is skipped, and filling continues with the next ones.\n\n---\n\n## 4. Nuggetization: how answers are scored\n\n### 4.1 What a nugget is\n\nEach official answer is broken into **nuggets**: short, self-contained facts that a correct answer must state.\nEach nugget is labelled **vital** (needed for a correct answer) or **okay** (useful detail), as in the TREC RAG\nevaluations.\n\nAn LLM judge then reads a system answer and labels every nugget:\n- *support*;\n- *partial support*;\n- *not support*;\n- *contradicts*.\n\n**V_strict** is the share of vital nuggets with full *support*.\n\nExample (Q350, parent-in-law as a dependant): \"a parent-in-law can be a dependant only when the spouse files a\njoint return\" (vital), with the income limit of R$ 24.511,92.\n\n**The gold set (`nuggets/gold/v0-auto/`):**\n- **3,175 nuggets** for the 715 questions, **2,262 vital**;\n- median 3 per question (1 to 115);\n- 65 % carry a time-specific fact (a year, a value or a deadline);\n- 26 % are filing-program (PGD) instructions.\n\n![Nuggets](figures/20261108_224913_results_overview/fig9_nuggets.png)\n\n### 4.2 Safeguards built into the nugget set\n\nThe nuggets were made and checked by LLMs, with safeguards against their errors:\n\n| Safeguard | Result |\n|---|---|\n| **Three independent nugget makers** (GPT-6.1 Sol as primary; Gemini 3.1 Pro, Qwen3.8-Max) | 95 % of the primary nuggets are also found by both other models. The two other sets are used to re-score the results (§2.4). |\n| **Automatic validator** (every enumerated item covered, verdict present, values kept, no duplicates) | Errors went back to the maker for repair. 3 borderline items are left, in 3 questions, and are listed. |\n| **Round trip**: answer rewritten from the nuggets only, then compared with the original | 69 omissions or alterations found, then handed to the auditors. |\n| **Two independent LLM auditors** (Gemini 3.1 Pro, Qwen3.8-Max), two repair rounds | Nuggets flagged by both: 1.3 % before repair, **0.03 % (1 nugget) after**. |\n| **Planted-error test**: one nugget damaged on purpose in each of 70 questions | Auditors caught **96 %** and **93 %**. |\n| **Self-score**: the judge applied to the official answer itself | **99.9 %** support. |\n| **Judge selection by 3,354 known-answer tests**: changed values, changed years, flipped verdicts, deleted conditions, another question's answer, empty answer | Gemini 3.8 Flash: **balanced accuracy 99.0 %**; value/year changes caught 97–100 %, verdict flips 96 %. |\n| **Second judge on real answers** (Gemini 3.1 Pro) | 94.7 % agreement, κ 0.90. |\n| **Frozen before scoring** | The set was fixed on 2026-10-21, before any RAG answer was scored. |\n\n**Still needed:** a sample checked by a tax-law expert. Every check above is automatic or done by an LLM.\n\n### 4.3 How much of the official answers is not in the cited law\n\nThe judge can also read a **context** instead of an answer. Even the ideal context (only the provisions the\nanswer cites, 4k tokens) fully states only **48 %** of the vital nuggets. To see why, 57 questions (212 vital\nnuggets) were audited in five steps:\n\n1. **Larger oracle:** a 16k-token oracle, so that nearly all cited articles fit.\n2. **Second judge:** a check with another judge (the two agree, κ 0.79).\n3. **Judge tests:** the context judge's own known-answer tests (balanced accuracy 98.5 %).\n4. **Corpus search:** the whole corpus was searched for each unsupported nugget.\n5. **Classification:** each cause was classified by a strong model, and the classification was re-checked\n against the evidence.\n\n**Results** (panel b above):\n- **About half (50.5 %)** of the vital facts are fully stated by the cited provisions, and **a fifth (20.8 %)\n partly**.\n- **About one in six (15.6 %, 95 % CI 8–26 %) is not stated in any legal text of the corpus:**\n - the tax authority's interpretation or application of the law to the case (9.4 %). For example, the law\n lists \"parents\" as dependants; the P&R adds parents-in-law through the joint return;\n - filing-program instructions (3.8 %);\n - administrative positions (2.4 %).\n- **About one in fourteen (7.1 %)** is stated in legislation the answer does **not** cite.\n- **5.7 %** were our oracle's own fault: questions citing many documents overflow even 16k tokens.\n\nThis caps every RAG system on this dataset, whatever the segmentation or the embedding. It also explains why\nthe gains of §2 are a few points. Caveats:\n- 57 questions only, so the confidence intervals are wide;\n- the legal classification still needs a tax-law reader.\n\n---\n\n## 5. What is next\n\n**Before reporting the Gemini result:**\n- re-score with the two other nugget sets (≈ $3);\n- run the nugget perturbation test;\n- check why Luna contradicts more on Gemini S2 than on S1 (+0.025, p .018).\n\n**Optional:**\n- Terra and Sabiazinho-4 with Gemini;\n- the 16k oracle on all 596 questions;\n- a tax-law expert's review of the nugget audit.\n\n**Cost so far:**\n- ≈ $211 in LLM and embedding calls, all recorded in the cost ledgers;\n- of which $26.91 for the whole Gemini comparison.\n\n## Sources\n\n| Topic | Note in `docs/` |\n|---|---|\n| Strategies and design | `20260923_193852_segmentation_strategies_for_rag_experiments.md`, `20261005_184116_segmentation_s3_vs_lima_ementa_and_caput_strategy_plan.md` |\n| Length cap and splitting | `20261013_105850_segmentation_token_cap_summary.md` |\n| Nuggets: plan, execution, safeguards | `20261011_224049_gold_answer_nuggetization_plan_v2.md`, `20261021_155704_nuggetization_phases_2_to_4_execution.md` |\n| First full evaluation (jua, 4 generators, robustness, ceiling audit) | `20261023_210727_rag_phase5_scoring_and_analysis.md` |\n| Gemini comparison | `20261108_153258_gemini_embedding_2_comparison_plan.md`, `20261108_175117_gemini_embedding_2_setup_embedding_and_retrieval_gate.md` |\n","20261108_231904_hugging_face_update_gemini_embedding_2.md":"# Hugging Face update: the gemini-embedding-2 comparison added to the evaluation repo\n\n**Generated:** 2026-11-08 23:19:04 (local time, from `date +%Y%m%d_%H%M%S`).\n**Follows:**\n- `20261024_180016_hugging_face_release_plan.md`: its rule for later updates (§5.4) and the first staging (§9);\n- `20261108_175117_gemini_embedding_2_setup_embedding_and_retrieval_gate.md`: the outputs released here.\n\n**Result:**\n- Repo B (`eduseiti/BR-TaxQA-R-RAG-eval`, still private) has a new commit with every Gemini output, built and\n checked by the release tooling.\n- Repo A (`eduseiti/BR-TaxQA-R`) needed no change.\n\n**Cost:** $0. No LLM or embedding calls were made.\n\n## 1. What changed where, and why\n\nThe plan's update rule (§5.4):\n- new evaluation outputs go to **B** as new commits, under new paths;\n- **A** changes only if the benchmark changes;\n- no history is rewritten.\n\n| Repo | Before | After | Change |\n|---|---|---|---|\n| A `eduseiti/BR-TaxQA-R` | `2b10e0f` | `2b10e0f` (unchanged) | None needed. A rebuild from this checkout matches the Hub file for file (`push_release.py --dry-run`: 0 new, 0 changed, 0 only on the remote). The Gemini work used the same questions, chunks and nuggets. |\n| B `eduseiti/BR-TaxQA-R-RAG-eval` | `af37fda` | **`0a69ef9`** (`0a69ef96537c06149a2e8ccb76d7588d1ce90ca7`), recorded in `release/hf_release.json` | 81 new files, 19 changed, 0 deleted. 973 files, 3.0 GB, of which the Gemini corpus vectors are 1.25 GB. |\n\n**New in B, all under the `gemini-emb-2` paths that mirror the git repo:**\n\n| Path | Content |\n|---|---|\n| `embeddings/gemini-emb-2/` | `corpus/` (`vectors.npy` 101,943 × 3,072, `texts.csv`, `chunk_map.csv.gz`, `manifest.json`), `queries/irpf/`, `check.json`, `parity.json` (the determinism check) |\n| `runs/retrieval/gemini-emb-2/irpf/` | rankings of the five strategies; the four evaluations, with the same parameters as jua's |\n| `runs/contexts/gemini-emb-2/irpf/` | `S1_budget4000`, `S2_budget4000`, `summary.csv` |\n| `runs/answers/gemini-emb-2/irpf/answer_v1/{sabia-4,gpt-5.6-luna}/{S1,S2}_budget4000/` | the 4 core-grid runs × 715 answers |\n| `nuggets/scoring/score/…/gemini-emb-2/…`, `nuggets/scoring/ctxsupport/…/gemini-emb-2/…` | the judge's labels on the 4 runs and on the 2 context sets |\n| `docs/` | the Gemini plan and results notes |\n\n**Changed in B. Every change only adds rows; nothing published was altered (checks in §3):**\n- ledgers: `embeddings/costs.csv`, `runs/costs.csv`, `nuggets/scoring/costs.csv`;\n- the scoring tables in `nuggets/scoring/tables/gold-v0-auto/gemini-3.8-flash/all/`, where Gemini runs are named\n `<context_id>@gemini-emb-2`;\n- the six Parquet viewer tables;\n- the two cache archives that grew:\n - `raw/runs_answers_cache.tar.gz`: 15,874 → 18,600 requests;\n - `raw/nuggets_scoring_cache.tar.gz`: 22,688 → 26,420 requests;\n- the card `README.md`, and `SHA256SUMS` / `release_manifest.json`.\n\n## 2. Viewer configs (row counts after the update)\n\n| Config | Before | After | Note |\n|---|---:|---:|---|\n| `run_metrics` | 56 | 60 | + 4 Gemini runs |\n| `answers` | 18,805 | 21,665 | + 4 × 715. It already had an `embedding` column. |\n| `nugget_labels` | 82,186 | 94,886 | |\n| `per_question_scores` | 18,309 | 21,169 | |\n| `comparisons` | 336 | 378 | + the jua ↔ Gemini and Gemini S1 → S2 pairs |\n| `retrieval_metrics` | 11,255 | 22,510 | **New `embedding` column (first)**: the two embeddings' main evaluations are stacked, 11,255 rows each. |\n\n`retrieval_metrics` is the only schema change. Adding a column keeps one config per kind of table, the same\nchoice as `answers` and `nugget_labels`. A split per embedding was the alternative, but split names cannot hold `-`.\n\n## 3. How it was built and checked\n\n```bash\nuv pip install -r scripts/release/requirements.txt # pyarrow was missing on this computer (pip into .venv)\n# the six unchanged cache archives are not on this computer (nuggets/full/cache is empty): downloaded from af37fda,\n# SHA-256 checked against the Hub's LFS hashes, into ../br-taxqa-r_hf_release/BR-TaxQA-R-RAG-eval/raw/\n.venv/bin/python scripts/release/build_release.py --repos b --keep-raw # repacks only the two grown caches\n.venv/bin/python scripts/release/build_release.py --repos a # then push_release --dry-run: in sync\n.venv/bin/python scripts/release/push_release.py --tree ../br-taxqa-r_hf_release/BR-TaxQA-R-RAG-eval \\\n --repo-id eduseiti/BR-TaxQA-R-RAG-eval --message \"Add the gemini-embedding-2 comparison: …\"\n```\n\n**Checks against the published revision `af37fda` (done before the upload):**\n- **Ledgers:** each old ledger is a byte prefix of the new one (embedding 10 → 14 lines, generation\n 15,877 → 18,603, scoring 22,714 → 26,446).\n- **Scoring tables:** every old row is still present. The one exception is described under \"Known differences\"\n below.\n- **Parquet tables:**\n - `answers` starts with the old rows, equal in Arrow;\n - `nugget_labels` and `comparisons` start with the old rows, equal value for value;\n - `run_metrics` and `per_question_scores` contain every old row;\n - the jua part of `retrieval_metrics` equals the old table;\n - all Arrow schemas are unchanged, except the new `embedding` column.\n- **Cache archives:** all 15,874 and 22,688 old members are present with the same SHA-256.\n- **Build checks** (secrets, local paths, row counts) pass.\n\n**Known differences from the published state:**\n- **`ctxsupport_runs.csv`, row `oracle_budget16000`:** n 25 → 57 (V_strict 0.576 → 0.460).\n - The published table was built before the §10 audit of the phase 5 note was tabulated. That audit scored\n `oracle_budget16000` on the 57 questions of `stratified_70`, and the table now uses all of them.\n - The row `wrong-S2_budget4000` (70 questions) is new for the same reason.\n - The labels behind both rows were already published.\n- **Gemini contexts and answers have `rendered_tokens_qwen3` = null.**\n - This is the optional Qwen3 count of the rendered context. `rag.py context` skips it, with only a warning,\n when the tokenizer is not in the local HF cache, which was the case on this computer.\n - `context_tokens_qwen3`, the count the budget uses, is filled, and the answers are not affected.\n - The card says so. In the Parquet table the column stays `int64`, with nulls for Gemini.\n - Rebuilding the contexts with the tokenizer and replaying the generation from the cache would fill it at no\n cost. It was not done, because it would rewrite run outputs after scoring.\n\n**After the upload:**\n- `push_release.py` compared the Hub with the tree again: \"in sync\" at `0a69ef9`. Every file is present, and LFS\n files match by SHA-256.\n- The repo is still private.\n- **Wrong label in the commit message:** the Hub commit message says \"git 83b3f55\". The tree was built from\n `4f85083` plus the uncommitted release-tooling changes of §4, as `release_manifest.json` and\n `release/hf_release.json` record. Hub history was not rewritten for this (§5.4).\n\n## 4. Changes to the release tooling (uncommitted)\n\n**`scripts/release/build_release.py`:**\n- The answers and labels tables read every embedding folder, jua first, so the old rows keep their order.\n- A `flat` entry can stack several CSVs with a key column (`csvs:` + `key:`).\n- `rendered_tokens_qwen3` is kept as a nullable integer.\n- `pack` keeps an existing archive *before* checking that its cache folder exists. So a computer without a cache\n can reuse the published archive.\n- **`OTHER_REPO_ROOTS`:** the tracked jua embedding manifests hold the other computer's checkout path\n (`/work/unicamp/articles/…`). The build there rewrote it automatically, as its own repo path. It is now\n rewritten on any computer, so the copies are identical to the published ones.\n\n**`scripts/release/repo_b.yaml`:**\n- adds the Gemini embedding, answer and doc paths;\n- the stacked `retrieval_metrics`;\n- the new counts;\n- excludes the per-question tables of two old jua evaluations (`either_containment_skip` of 2026-09-27 and\n `v2c_…` of 2026-10-08). They are gitignored leftovers on this computer, made from older chunk files, and were\n not in the release. Their `metrics.csv` and `report.md` are released, as before.\n\n**`scripts/release/cards/repo_b.md`:**\n- the second embedding in \"The experiment\";\n- a Gemini results table;\n- the `@gemini-emb-2` naming;\n- the new row counts and archive sizes;\n- the Gemini cost ($26.91);\n- the limitations line.\n\n## 5. Not done\n\n- **No tag.** The plan tags a paper version (§5.4), and none is fixed yet.\n- **Viewer check:** the viewer still cannot run on the private repo (non-PRO account).\n- **`datasets.load_dataset` check:** not repeated in a clean venv. The Parquet files were read back with pyarrow\n and compared with the published ones instead.\n- **Not uploaded:** the overview report `20261108_224913_results_overview_segmentation_and_embedding.md` and its\n figures. The user has not reviewed them yet.\n- **Unchanged next steps** of the plan (publication under `unicamp-dl`, checks C5–C7): they still wait for the\n user.\n","20261109_123355_results_dashboard.md":"# Results dashboard: an interactive explorer of the retrieval and answer results\n\n**Generated:** 2026-11-09 12:33:55 (local time, from `date +%Y%m%d_%H%M%S`).\n**Purpose:** records why and how the results dashboard (`docs/dashboard/index.html`) was built, what each tab\nshows, where its numbers come from, and how it was checked. It decides nothing about the experiments, and\nit made no LLM or API calls ($0).\n**Request (user, 2026-11-09):** an interactive visualizer of all executed experiments, built from\n`20261108_224913_results_overview_segmentation_and_embedding.md`. It should say exactly what each result shows and\ncompares, so the execution can be validated. It should explain how strategies that cut the text differently\n(S1 vs S2) are compared, which the report's §2.2 does not say, and link to the notes in `docs/` where each choice\nwas made.\n\n## 1. How to open and rebuild it\n\n```bash\n.venv/bin/python scripts/report/build_dashboard_data.py # ≈ 70 s, reads result tables only\nxdg-open docs/dashboard/index.html # or open it in any browser; works from file://\n```\n\n- **Static page, no server.** The data are JavaScript files loaded with `<script>` tags. `fetch()` would be\n blocked under `file://`; script tags are not.\n- **External dependency:** `marked` 12.0.2 from cdnjs renders the notes in the side reader. Offline, the notes\n are shown as plain text. Everything else is inline: the charts are hand-written SVG, with no chart library.\n- **Theme:** light/dark, from the OS or the toggle button.\n\n| File (`docs/dashboard/data/`) | Content | Size | In git |\n|---|---|---:|---|\n| `core.js` | retrieval metrics, comparisons and reachability for both embeddings; nugget runs, comparisons and robustness tables; strategy chunk counts; run index | 2.5 MB | yes |\n| `docs.js` | every `docs/*.md` plus `scripts/{rag,nuggets}/README.md`, for the in-page reader | 1.2 MB | yes |\n| `questions.js` | per question: text, official answer, references, nuggets, the judge's labels in every run and context, and the ranks of every gold item for every strategy × embedding | 6.2 MB | no (gitignored) |\n| `contexts.js` | per question, the chunks of 13 generator contexts (rank, type, source, tokens, gold-hit mark) | 6.5 MB | no |\n| `answers/*.js` | one file per scored run with its answers, loaded when a cell is clicked | 17 MB | no |\n\nThe per-question files follow the repo rule that per-question tables stay out of git (`runs/**` in `.gitignore`).\nThe page says so and names the build command when they are missing.\n\n## 2. Inputs\n\nAll read by `scripts/report/build_dashboard_data.py`:\n\n- **Retrieval evaluation:** `runs/retrieval/{jua-4b-mixed,gemini-emb-2}/irpf/eval/either_containment_merge_skip/`\n (`metrics.csv`, `comparisons.csv`, `reachability.csv`, `per_question.csv.gz`, `per_item.csv.gz`, `manifest.json`).\n This is the main evaluation, the one the results-overview figures use. The older `v2c_`/`v2d_` and `containment`\n evaluations are not shown.\n- **Contexts:** `runs/contexts/<emb>/irpf/<context_id>/contexts.jsonl.gz`. Each chunk is linked to its article\n through `segmented/chunks_all.csv.gz`.\n- **Answers:** `runs/answers/<emb>/irpf/<prompt>/<llm>/<context_id>/answers.jsonl`.\n- **Nugget scoring:** `nuggets/scoring/tables/gold-v0-auto/gemini-3.8-flash/all/` (`runs.csv`, `comparisons.csv`,\n `ctxsupport_runs.csv`), `nuggets/scoring/analysis/…/all/*.csv` (cross-set, perturbation, slices, chapters,\n judge agreement, utilisation, linkage) and the labels in `nuggets/scoring/{score,ctxsupport}/gold-v0-auto/gemini-3.8-flash/…/labels.jsonl`.\n- **Gold nuggets:** `nuggets/gold/v0-auto/nuggets.jsonl`.\n- **Dataset:** `dataset/{questions,references}.jsonl` and `scripts/rag/data/pr_irpf_2024_chapters.csv`.\n\n**Computed by the script.** Everything else is copied as stored.\n- **Strategy chunk counts.** Computed with `ragpipe.strategies.member_mask` minus the excluded RIR/1999 files.\n Result: 20,461 / 68,656 / 72,061 / 68,656 / 72,061 for S1 / S2 / S3 / S2c / S4, the same as the results overview.\n- **Gemini − jua retrieval comparisons.** `rag.py compare` works within one retrieval run only, so these are\n computed from the two `per_question.csv.gz`, paired over the same questions. They use the same\n `ragpipe.metrics` functions (bootstrap 10,000, seed 13; sign-flip permutation) and count the questions that are\n better and worse.\n - They reproduce the ad hoc table of `20261108_175117_…` §4.3. Article recall at 4k: S1 +0.015, p .27, 101/86\n questions better/worse; S2 +0.012, p .37. Unit recall@10: +0.081 (S1) and +0.049 (S2).\n - The CIs differ in the third decimal, because the note used 5,000 resamples.\n - The script resamples once per group of metrics that share the same questions. A first per-metric version gave\n identical numbers (max |Δ| = 0) and took 3.7 min; the build now takes 1.1 min.\n\n## 3. What each tab shows\n\n| Tab | What it answers | Main elements |\n|---|---|---|\n| 1 · Map | What was run, and on which questions? | Clickable pipeline. Each stage shows what was varied, what was held fixed, and the notes where it was decided. Experiment grid: context set × generator, V_strict and n. Full (715), oracle (596) and pilot (30) runs are badged, so pilot runs are not compared with full runs by mistake. Headline KPIs. |\n| 2 · Segmentation | What does each index contain? | Toggle S1…S4 on one article (Lei 9.250 art. 35) to see the chunks it produces: ancestor path, caput variant, grouping chunk. Chunk counts by type, and the strategy table. |\n| 3 · Retrieval: how scored | How are S1 and S2 compared when they cut the text differently? | The answer to the user's question (§4 below). An interactive worked example that re-implements the matcher, the context selection (`containment_merge`, overflow skip) and RR/nDCG/recall in the browser, with the level, budget and dedup mode adjustable. A table of all rules with their code locations. |\n| 4 · Retrieval: results | Retrieval metrics, filtered by embedding, strategy, level, gold set and item slice | Budget-view curves (1k–16k), unit-view recall@k, MRR/nDCG@10, raw view (labelled diagnostic), and a \"What is shown\" box rewritten for each selection. Paired-comparison forest plots per view and cutoff, including Gemini − jua. Reachability table. |\n| 5 · Nuggets: how scored | What do V_strict, V, A_strict, A, W and contradictions mean? | A calculator: toggle the labels and the vital/okay importance of toy nuggets, or simulate an abstention, and see every metric with its formula. Notes on macro averaging, n = 714 vs 715, abstentions, oracle n, and context support vs answer scores. |\n| 6 · Answers: results | Answer and context scores | Heatmap of runs × generators for any metric. Forest plots grouped by comparison family (S1 → S2, jua → Gemini, variants, controls, pilot budgets), with bootstrap and chapter-cluster CIs. Context V_strict vs answer V_strict. Utilisation. Robustness: three nugget sets, random and targeted nugget damage, nugget subsets, per-chapter differences, second judge. |\n| 7 · Question explorer | Validate single cases end to end | Search or filter questions (e.g. \"S1 4k recall > S2\"). For each question: the gold items with their 4k membership, unit position and raw rank for all 10 strategy × embedding runs; two contexts side by side with gold-article chunks marked; a nuggets × runs label grid (plus \"ctx:\" columns for the judge on the context). Clicking a cell loads the answer. |\n| 8 · Notes | All design and execution notes | A list of `docs/*.md`; the ¶ links across the page open the reader at the relevant section. |\n\n## 4. The S1 vs S2 comparison, as the dashboard explains it\n\nThis is the point the user found unclear in the results overview §2.2. Read from `scripts/rag/ragpipe/relevance.py`\nand `evaluation.py`, and already written down in `20261013_111626_retrieval_metrics_views_and_position_metrics.md`:\n\n- **Matching happens at the level of the gold, not of the chunk** (rule G2). An article-level gold item\n `(document, art N)` is hit by **any** chunk of article N: the whole article, a split part, the caput, any §,\n inciso, alínea or item. In S3/S4 a grouping chunk also hits every article it contains.\n- **MRR and nDCG@10 use the unit projection.** The chunk ranking is turned into a ranking of distinct articles, in\n the order in which *any* of their chunks first appears.\n - The MRR is 1 / (that position of the first gold article). It is the position of **any part** of the article,\n not of the whole-article chunk.\n - nDCG@10 uses binary gain over the first 10 distinct articles.\n - Positions beyond 1,000 count as not retrieved.\n - Both exist only at the document and article levels.\n- **Recall within the 4k budget** (the headline) is a yes/no test per gold item: is any of its chunks in the context\n the generator saw? Position in the context does not count. It is the only view that charges each strategy for\n the length of its chunks.\n- **Consequences shown on the page:**\n - S2 gets article credit when only one inciso of the article is in the context. The provision level, with\n full/partial hits, is the stricter test.\n - There is no provision-level MRR.\n - The means are over 553 (article), 596 (document) and 558 (provision) questions. The 119 questions without\n citations are in the answer scores only.\n\n## 5. Checks done\n\n- **The rendered numbers match the stored tables and the results overview.**\n - Article recall at 4k: 0.398 / 0.503 (jua S1/S2) and 0.413 / 0.515 (Gemini).\n - MRR: 0.524 / 0.555 / 0.614 / 0.638.\n - Answer V_strict: Luna S1 → S2 +0.028, p .007; Gemini vs jua as in the report.\n - Strategy chunk counts as in §2.\n- **Gemini − jua comparisons:** reproduce the Gemini note's §4.3 (§2 above).\n- **Every tab was rendered** with headless Chrome (1,300 px wide), and the screenshots were looked at. Fixed after\n that review:\n - the perturbation chart mixed random and targeted settings on one rate axis; the targeted settings are now a\n table;\n - the chapter labels were clipped;\n - the doc-link glyph did not render;\n - a sentence of the worked example did not follow the budget slider.\n- **The worked example's selection logic** follows `ragpipe/context.py select`:\n - a text inside a selected one is dropped;\n - a parent replaces its already-selected children at the first child's place and costs its tokens minus theirs;\n - a text that does not fit is skipped.\n\n It is a re-implementation for teaching, on made-up rankings. The real per-question behaviour is in tab 7.\n\n## 6. Limits and possible next steps\n\n- **No test suite for the page.** It was checked visually and against the tables, not by automated tests.\n- **Answer text is not compared with the context text.** The question explorer shows chunk labels, not chunk\n text, to keep the files small. The full context text is in `runs/contexts/…/contexts.jsonl.gz`.\n *Update 2026-11-10:* the question-trace tab (now tab 8; the notes are tab 9) shows the chunk texts, the full\n prompt and the answer's claims with their quotes (`20261110_194056_question_trace_dashboard_implementation.md`).\n- **Missing runs are shown as empty cells.** The 30-question pilot runs, the Terra/Sabiazinho-4 Gemini runs (not\n run) and the `irpf_with_rir1999` side run are visible only through these gaps or the run badges.\n- **Rebuild after new runs.** New runs (e.g. Gemini with the other two nugget sets) appear after\n `build_dashboard_data.py` is rerun, as long as they write to the same table layouts.\n","20261110_155548_question_trace_dashboard_feasibility_and_plan.md":"# Question trace view for the results dashboard: feasibility analysis and implementation plan\n\n**Generated:** 2026-11-10 15:55:48 (local time, from `date +%Y%m%d_%H%M%S`).\n**Purpose:** checks whether the data needed to follow one question through every stage of the pipeline\n(gold answer → nuggets → gold documents → segmentation → retrieval → context → answer → nugget labels) is\navailable, records the gaps, and plans how to add this view to the results dashboard\n(`20261109_123355_results_dashboard.md`). It changes no experiment and plans no LLM calls ($0).\n**Request (user, 2026-11-10):** extend the dashboard so that each data instance can be inspected across the\nprocessing stages:\n- from a question, see its gold-answer nuggets and, from each nugget, reach the gold document that contains it;\n- from a question, see its referred documents and, from each document, its segmentation under every strategy;\n- at retrieval, see the order of the returned segments, linked to their documents, with a mark when a segment\n belongs to the question's gold set;\n- at answer time, see the final list of texts that fit in the token budget, and the nuggets of the generated\n answer compared with the gold set.\n\nThe user expected all of this to be in the Hugging Face repo `eduseiti/BR-TaxQA-R-RAG-eval`.\n**Decisions (user, 2026-11-10, §7):** D1 top 100 + every gold hit, and show the prompt with its parts marked;\nD2 no pilot runs; D3 and D4 not done (no extra cost); D5 build from the local files. Sections 3–6 below already\napply these decisions. §8 adds how the trace view shows the vital/okay importance of the nuggets.\n\n## 1. Summary\n\n**Feasible, with three corrections to the request:**\n\n1. **Repo B alone is not enough; repos A + B together are.** `BR-TaxQA-R-RAG-eval` (repo B) has the rankings,\n contexts, answers and judge labels. The questions, gold answers, references, gold nuggets, chunk texts, LexML\n and original files are in `eduseiti/BR-TaxQA-R` (repo A). Both repos mirror this git repo's paths, so the\n builder can read either the local working copy or a download of the two repos (§2).\n2. **No data links a nugget to a gold document.** Nuggets are extracted from the gold answer text. The citations\n (`references.jsonl`) belong to the question, not to the nugget. Three partial signals exist and can be shown\n together, each labelled for what it is (§3.1). A precise per-nugget link would need a new LLM step, which is\n not planned here (§7, D3).\n3. **No nuggets are extracted from the generated answers.** Phase 5 scores in the opposite direction\n (`assign_v2`). The judge reads the answer and labels **each gold nugget** as `support`, `partial_support`,\n `not_support` or `contradicts`, and justifies each label. So the comparison with the gold set exists nugget by\n nugget. The generators did, however, write their answers as a list of **claims** (`afirmacoes`), each with\n the documents it cites and a quoted excerpt, checked at generation time (`answers.jsonl`: `claims`, `checks`,\n `cited_chunk_ids`). These claims can be shown and linked to the context ($0), but no data matches them to the\n gold nuggets (§3.5).\n\nEverything else is in the data: segmentation by strategy, the full rankings (1,000 per question), the gold\nmatch per ranked chunk, the in-budget text list with its rendered prompt, the answers, and the labels.\n\n## 2. Where each piece lives\n\nChecked on 2026-11-10 with a listing of both repos (`HfApi.list_repo_tree`) and the local files.\n\n| Data | Repo | Path (same in git and on the Hub) | Notes |\n|---|---|---|---|\n| Questions, gold answers | A | `dataset/questions.jsonl` | 715 |\n| References (gold documents, articles, provisions) | A | `dataset/references.jsonl` | 1,916 rows; 596 questions have at least one |\n| Documents (title, URN, files) | A | `dataset/documents.jsonl` | 453 |\n| Gold nuggets | A | `nuggets/v0-auto/nuggets.jsonl` (git: `nuggets/gold/v0-auto/`) | 3,175; `source_span`, `legal_basis`, `importance`, `values` |\n| Chunks of every strategy, with text | A | `segmented/chunks_all.csv.gz` | 104,574 rows, 85 M characters; `artigo_id`, `cobre_ids`, `parcial_ids`, `agrupadores_ids`, `variante`, `n_tokens_qwen3` |\n| LexML / original files | A | `lexml/…`, `original/…` | for links, not needed to render chunks |\n| Rankings | B | `runs/retrieval/<emb>/irpf/<S>/rankings.csv.gz` | top 1,000 per question; 5 strategies × 2 embeddings (Gemini: S1, S2) |\n| Gold match per item | B | `runs/retrieval/<emb>/irpf/eval/either_containment_merge_skip/per_item.csv.gz` | `rank_full`, `rank_any`, `unit_pos`, `budget_{full,any}_<k>` per gold item |\n| Generator contexts | B | `runs/contexts/<emb>/irpf/<context_id>/contexts.jsonl.gz` | in-budget `items` (rank, chunk, aliases, tokens, source), `gold` hits, rendered `context` text |\n| Answers | B | `runs/answers/<emb>/irpf/<prompt>/<llm>/<context_id>/answers.jsonl` | 60 runs locally (full, oracle, closed-book, pilot) |\n| Answer labels per gold nugget | B | `nuggets/scoring/score/gold-v0-auto/gemini-3.8-flash/…/labels.jsonl` | label + justification per nugget; also the second judges `gemini-3.1-pro.rep0`, `qwen3.8-max.rep0` on subsets |\n| Context labels per gold nugget | B | `nuggets/scoring/ctxsupport/gold-v0-auto/gemini-3.8-flash/…/labels.jsonl` | 12 jua contexts + 2 Gemini contexts (list in §3.1) |\n| Value hits, citations per answer | B | `nuggets/scoring/analysis/gold-v0-auto/gemini-3.8-flash/all/{values_per_nugget,citations_per_answer}.csv.gz` | per run × question (× nugget) |\n\n**Reading from the Hub in the browser is not an option.** Both repos are private (staging), the dashboard opens\nfrom `file://`, and a browser would need the token and CORS access. The builder therefore downloads or reads the\nfiles and writes static data files, as the current dashboard does.\n\n**Machine state.** The gitignored per-question files of the current dashboard (`questions.js`, `contexts.js`,\n`answers/`) are not on this computer; `runs/` and `nuggets/scoring/` are. On a computer without them, the builder\ncan fetch the needed paths from both repos with `snapshot_download(allow_patterns=…)` (≈ 300 MB without the\nembeddings and the `raw/` caches).\n\n## 3. Feasibility per interaction\n\n### 3.1 Question → nuggets → gold document\n\n- **Question → nuggets:** direct (`question_number`). `source_span` locates each nugget in the gold answer\n (`span_match`: exact or fuzzy), so the nuggets can be highlighted in the answer text.\n- **Nugget → gold document:** not recorded. Three signals, shown in this order:\n 1. **Explicit legal basis.** 478 of 3,175 nuggets (15 %, in 183 questions) carry `legal_basis` strings copied\n from the answer, e.g. `art. 39 da Lei nº 11.196, de 21 de novembro de 2005`. They can be resolved to the\n question's references by matching them with `citation_text` and the article numbers. Resolution rate to be\n measured in step 2 (§5); unresolved strings are shown as text.\n 2. **Support by the gold articles.** The judge labelled every nugget against the oracle context\n (`ctxsupport`, `oracle_budget4000`, 596 questions; `oracle_budget16000` for 57). This says whether the gold\n articles, as packed in 4k tokens, support the nugget. The justification sometimes names the article. It is\n a label on the whole oracle context, not on one document.\n 3. **Lexical candidate (computed, $0).** Rank the question's gold-article texts by word overlap (BM25) with the\n nugget text and show the best match and its score, marked \"heuristic\". It is a pointer to where to look,\n not a gold link.\n- **Limits.** The 119 questions without references have no gold documents; for them the view stops at the\n nuggets. Nuggets that restate PGD procedure or the Q&A's own wording may have no legal source at all.\n\n### 3.2 Question → referred documents → segmentation under every strategy\n\n- **Feasible from repo A alone.** `references.jsonl` gives the documents and articles; `chunks_all.csv.gz` gives\n every chunk with its document, article, ancestors, groupings and variant.\n- **Strategy membership** is computed with `ragpipe.strategies.member_mask`, as the dashboard already does for\n the chunk counts (S1 / S2 / S3 / S2c / S4 = 20,461 / 68,656 / 72,061 / 68,656 / 72,061 after the RIR/1999\n exclusion). A chunk can belong to several strategies.\n- **View:** the document's articles in order; for each article, the chunks each strategy makes of it (S1: the\n article, in parts if split; S2: + caput-less paragraphs and sub-units with the ancestor path; S3: + groupings;\n S2c/S4: the caput variants). Gold articles of the current question are marked. Annexes and non-statutory\n documents are shown with their own chunk types (`TXT`, `TAB`, orphan dispositivos).\n- **Excluded document.** The RIR/1999 is referenced by questions but excluded from the `irpf` indexes. It is\n shown with a note \"not indexed in the main run\".\n- **Links** to the LexML and original files on the Hub (repo A paths) for the full source.\n\n### 3.3 Retrieval: ranked segments with gold marks\n\n- **Rankings** are complete (1,000 per question) for 10 strategy × embedding runs. Each row has `chunk_id`, which\n joins to `chunks_all` for the document, article and label.\n- **Gold mark per chunk.** Not stored per chunk, but computable with the evaluation's own matcher\n (`ragpipe.relevance`, rule G2: any chunk of a gold article hits it; a grouping chunk hits every article it\n contains). It will be computed at the document, article and provision levels, with full and partial hits, and\n shown as such.\n- **Check:** the first gold hit per item must equal `rank_any` / `rank_full` in `per_item.csv.gz`, and the\n unit-projection position `unit_pos`.\n- **Size.** All 1,000 rows × 10 runs × 715 questions is 7.15 M rows: too much for static files. Keep the top\n *K* (proposed *K* = 100, decision D1) plus every gold-hit row below *K*, so every gold item's rank is visible.\n- **Cross-stage marks:** each ranked chunk also shows whether it entered the context of that strategy at 2k / 4k\n / 8k, and in what form (kept, merged into a parent, skipped for budget).\n\n### 3.4 Answer stage: the texts that fit in the budget\n\n- **Feasible directly.** `contexts.jsonl.gz` holds, per question and context, the ordered `items` (`n`, rank,\n `chunk_id`, `alias_chunk_ids` for merged children, `tokens_qwen3`, `fonte`), the `gold` hits at each level, and\n the exact rendered `context` text the generator saw.\n- **View:** a token bar of the budget filled item by item; each item linked back to its ranking row and to the\n document view; gold items marked; a toggle to show the full prompt (below).\n- **Contexts available:** 13 jua contexts (S1 / S2 at 2k–8k, S2c, S3, S4 at 4k, oracle 4k / 16k, the\n `wrong-S2` control, `S2_budget4000_context_v1`) and 2 Gemini contexts. The `irpf_with_rir1999` side run is a\n pilot-scale run and is left out (D2). Closed-book has no context.\n\n**The prompt, with its parts marked (D1).** The prompt is not stored as one text per answer, but it can be\nrebuilt exactly from three stored parts:\n\n| Part | Source | Shown as |\n|---|---|---|\n| Instructions (system message) | the prompt template, `scripts/rag/prompts/<prompt>.pt.md` before `<<<USER>>>` (`answer_v1`, `answer_closed_v1`; the run's `run.json` names it) | grey block, labelled \"instructions — template `answer_v1`\" |\n| User frame | the template after `<<<USER>>>` (`Disposições:` … `Pergunta:`) | plain text |\n| Inserted context | the `context` field of `contexts.jsonl.gz` (the `{context}` slot) | each `[Documento n]` block coloured as a context item, gold items marked, linked to panel D |\n| Inserted question | `question_text` (the `{question}` slot) | highlighted |\n\n- **Verified at build time.** The LLM cache keeps the request that was sent (`runs/answers/cache/<cache_key>.json`,\n fields `request.system` and `request.user`). The builder rebuilds each prompt and compares it with the cache,\n byte for byte. Tried on Q001, Luna, S2 4k: both messages are identical.\n- **Only the parts are stored.** The template is stored once per prompt version, and the context once per\n question and context, so the page assembles the prompt in the browser and adds nothing to the file size. Each\n answer carries a flag: *verified against the request sent*, *not verifiable (no local cache)* or *differs*\n (the build fails if any answer differs).\n- **Local cache coverage** (2026-11-10): 17,393 of the 20,735 answers of the 29 full runs. Missing: the four\n Gemini runs (2,860; generated on the other computer, see `two_machine_state`), the 4 × 119 oracle rows of\n questions without references (no call was made, so nothing to verify) and 6 single answers. The Gemini requests\n are in repo B's `raw/runs_answers_cache.tar.gz` (59 MB) if that archive was packed after the Gemini runs.\n Downloading it for this check only costs nothing, and the build stays local (D5). Otherwise, those answers\n show \"not verifiable\".\n\n### 3.5 Answer stage: answer nuggets vs. gold set\n\n- **What exists:** per run and question, the label of each gold nugget in the answer with the judge's\n justification (`score`), and the same label against the context (`ctxsupport`) for the 14 scored contexts.\n- **The view this enables, per nugget:** *in the gold articles?* (oracle ctxsupport) → *in the retrieved context?*\n (ctxsupport of the run's context) → *in the answer?* (score label) → *contradicted?* This separates\n retrieval failures from generation failures, which a per-answer score cannot do.\n- **Extra signals:** numeric value hits per nugget (`values_per_nugget`: `value_hit`, `conflict`,\n `temporal_substitution`), the documents the answer cites vs. the gold and the context (`citations_per_answer`),\n and the second judges' labels where they ran.\n- **The answer's own claims ($0).** Each answer is stored as claims (`claims[].texto`), each with its grounds\n (`fundamentos`: document number in the context + quoted excerpt + a `status` from the generation-time quote\n check), plus `checks` (`quotes_ok`, `quotes_bad_document`, `claims_without_quote`, `values_not_in_context`)\n and `cited_chunk_ids`. The view lists the claims, links each ground to its context item (and so to its rank and\n its document), and marks quotes that failed the check.\n- **Not available (D3: not done):** a match between the claims and the gold nuggets. The view shows the two lists\n side by side: the gold nuggets with the judge's labels, and the claims with their grounds. It does not claim\n which claim covers which nugget.\n\n## 4. Design\n\n### 4.1 Where it goes in the page\n\nA new tab **\"9 · Question trace\"** (implemented as tab 8, before the notes, which became tab 9: `20261110_194056_question_trace_dashboard_implementation.md`), reachable from tab 7 (question explorer: a \"trace\" button per question) and\nby URL hash (`#trace/<question>/<emb>/<strategy>/<budget>/<llm>`), so a case can be linked from notes. Tab 7\nstays as the overview across runs; the trace tab follows one question through one run at a time, with a run\npicker.\n\nLayout: five stage panels in pipeline order, each collapsible, with a shared selection:\n\n| Panel | Content | Links out |\n|---|---|---|\n| A · Question | text, chapter, gold answer with nugget spans highlighted, references | nugget → B, D, E; reference → B |\n| B · Gold documents | per referred document, the article tree with the strategy toggle (S1 … S4) and chunk texts; gold articles marked; for a selected nugget, the three signals of §3.1 | chunk → C (its rank in each run) |\n| C · Retrieval | run picker (embedding × strategy); ranked list (rank, score, document, label, gold mark, in-context mark); a \"first gold hit\" summary per gold item, compared across the 10 runs | row → B (chunk in its document), → D |\n| D · Context | budget picker; token bar; items with merge / alias info and gold marks; rendered prompt toggle | item → C, B |\n| E · Answer and nuggets | generator picker; answer claims with their grounds; nugget table (with the vital/okay badge, §8): oracle support → context support → answer label → values / contradiction, with justifications on hover; cited vs. gold documents | nugget → A, B; ground → D |\n\n### 4.2 Data files\n\nThe static page loads data through `<script>` tags (no `fetch()` under `file://`). New files are loaded on\ndemand by injecting a script tag. All are gitignored (per-question data, `runs/**` rule).\n\n| File | Content | Estimated size |\n|---|---|---|\n| `data/trace/index.js` | per question: chapter, number of nuggets / references, available runs | < 0.5 MB |\n| `data/trace/q/<qid>.js` | question, gold answer, nugget spans, references, the three nugget→document signals; rankings top-*K* + gold rows for 10 runs with gold and in-context marks; contexts (items, gold, rendered text) for all contexts; answers and labels (score, ctxsupport, values, citations) for all scored runs | ≈ 150–250 kB each, ≈ 150 MB total (rendered contexts and answers dominate) |\n| `data/trace/doc/<document_id>.js` | per document: articles in order; per chunk: id, type, label, article, ancestors, variant, tokens, strategy bitmask, text | 85 M characters over ≈ 625 files (main + annexes); median 16 kB, RIR/1999 8.5 MB |\n\nShared chunk lookups (chunk → document / article / label) go in the question file for the chunks it uses, so the\nranking view does not need the document files. Document files load only when a document is opened.\n\nThe prompt adds only the templates (a few kB in `index.js`); the context text is already in the question\nfiles (§3.4).\n\n### 4.3 Builder\n\nNew script `scripts/report/build_trace_data.py`, separate from `build_dashboard_data.py` so the main build stays\nat ≈ 70 s.\n\n- Reads the local files (D5): everything the view needs is on this computer. A `--source hf` option is left for\n later; it is not built now. The only Hub download is the optional answer-cache archive for the prompt check\n (§3.4).\n- Runs: the 29 full runs (25 jua, 4 Gemini), the oracle and closed-book runs; pilot-only runs are skipped (D2).\n- Reuses `ragpipe.strategies.member_mask`, `ragpipe.relevance` (gold matching) and the context-reading code, so\n nothing is reimplemented in a way that could drift from the evaluation.\n- Nugget → document resolution (§3.1 signals 1 and 3) in a small module, with a report of how many `legal_basis`\n strings resolve.\n- `--questions 001,028,…` for quick partial builds while developing the page.\n\n## 5. Steps\n\n| # | Step | Output | Check |\n|---|---|---|---|\n| 1 | Builder skeleton: local readers, question index, prompt templates | `index.js` | 715 questions; counts of references, nuggets as in the dataset card |\n| 2 | Nugget → document signals | in `q/*.js` | share of `legal_basis` resolved, reported; oracle ctxsupport present for the 596 questions with references |\n| 3 | Document files with strategy membership | `doc/*.js` | per-strategy chunk totals equal the counts in §3.2 |\n| 4 | Rankings with gold and in-context marks | in `q/*.js` | first gold hit per item = `rank_any` / `rank_full` / `unit_pos` of `per_item.csv.gz`, for all items; in-context marks = `budget_any_4000` |\n| 5 | Contexts, answers with claims, labels, values, citations; prompt check | in `q/*.js` | label counts per run equal `tables/nugget_labels.parquet`; context gold hits equal the context `gold` field; every rebuilt prompt equal to the cached request (count of verified / not verifiable reported) |\n| 6 | Page: tab 9, panels A–E, hash links, button in tab 7 | `index.html` | rendered with headless Chrome at 1,300 px and phone width; light and dark |\n| 7 | Walk-through of chosen cases (e.g. a question where S2 finds the gold article and S1 does not; a nugget supported by the context but missed by the answer; a contradiction) | screenshots in the results note | the trace agrees with tab 7 and the tables |\n| 8 | Results note in `docs/`, `CLAUDE.md` pointer, update of `20261109_123355_…` §6 | | |\n\nSteps 1–5 are data work (≈ 1 day); step 6 is the bulk of the work (≈ 1–2 days); 7–8 are short. No API calls.\n\n## 6. Risks\n\n- **Size and load time.** One question file of ≈ 200 kB and one document file load fast. The RIR/1999 file\n (8.5 MB) is slow; it can be split by book/title, or shown with only the articles the question cites.\n- **Gold mark semantics.** The view must show the same rule as the metrics (any part of a gold article counts at\n the article level; partial vs. full at the provision level). Otherwise a reader will see \"gold\" chunks that the\n provision metric does not count. The panel names the level in use.\n- **Heuristic link mistaken for gold.** Signal 3 of §3.1 is labelled as a heuristic everywhere it appears.\n- **Data drift.** If the corpus or the runs are rebuilt, the trace must be rebuilt too. The builder writes the git\n commit and the input file hashes into `index.js`, and the page shows them.\n\n## 7. Decisions\n\nAsked in the first version of this note; answered by the user on 2026-11-10.\n\n| | Question | Decision |\n|---|---|---|\n| D1 | Ranking depth; rendered context in the files | Top 100 + every gold hit. Keep the prompt, with its parts marked (§3.4) |\n| D2 | Pilot-only runs and `irpf_with_rir1999` | Not now |\n| D3 | Extract nuggets from the generated answers (LLM) | Not done: no extra cost. The generators' own claims are shown instead (§3.5) |\n| D4 | LLM link from each nugget to a gold article | Not done: no extra cost. The three $0 signals of §3.1 only |\n| D5 | Local files or Hub download | Local files. The local data are complete for the view; only the prompt check of the Gemini answers may need the Hub cache archive (§3.4) |\n\n## 8. Nugget importance (vital / okay) in the view\n\nAsked by the user on 2026-11-10: what the vital / okay distinction is, where it comes from, and whether the\ndashboard shows it.\n\n- **What it is.** \"Gold nuggets\" are all the nuggets of the official (gold) answers: 3,175 in\n `nuggets/gold/v0-auto/`. Each one has an importance: **vital** (2,262) or **okay** (913). The test, check C4 of\n plan v1 §3.1 (`20260926_112714_gold_answer_nuggetization_plan.md`): *would an answer to this question without\n this fact be wrong or misleading?* Yes = vital, no = okay. The `create_v4` prompt says: `vital` if a correct\n answer to this question must contain the fact; `okay` if it is useful but not essential. Project rules on top:\n every question has at least one vital nugget, except pointer answers such as Q316; \"Atenção\" notes are\n usually okay.\n- **Where it comes from.** The vital / okay split is from the literature; the C4 test, the categories and the\n rules above are this project's own. References (links and contents checked 2026-11-10):\n - **[AN]** R. Pradeep, N. Thakur, S. Upadhyay, D. Campos, N. Craswell, J. Lin. *Initial Nugget Evaluation\n Results for the TREC 2024 RAG Track with the AutoNuggetizer Framework*. arXiv:2411.09607, 2024.\n <https://arxiv.org/abs/2411.09607>. Labels nuggets `vital` / `okay` and defines the scores used here: A,\n A_strict, V, V_strict (the primary metric), and W, with vital weighted 1 and okay 0.5. Its definition of\n vital is a quotation of Voorhees (2003).\n - **[V03a]** E. M. Voorhees. *Evaluating Answers to Definition Questions*. HLT-NAACL 2003, short papers.\n <https://aclanthology.org/N03-2037/> (PDF: <https://aclanthology.org/N03-2037.pdf>). The origin: the assessor\n marks the nuggets that must appear in a good answer as vital; the others are a \"don't care\" condition, and\n recall counts vital nuggets only.\n - **[V03b]** E. M. Voorhees. *Overview of the TREC 2003 Question Answering Track*. TREC 2003 (NIST SP 500-255).\n <https://trec.nist.gov/pubs/trec12/papers/QA.OVERVIEW.pdf>. The same method as used in the track.\n - **[LD06]** J. Lin, D. Demner-Fushman. *Will Pyramids Built of Nuggets Topple Over?* HLT-NAACL 2006.\n <https://aclanthology.org/N06-1049/> (PDF: <https://aclanthology.org/N06-1049.pdf>). The critique: the binary\n vital / okay split is a source of evaluation instability, since systems get credit only for vital nuggets.\n It proposes nugget pyramids, which weight nuggets by how many assessors marked them vital. This is relevant\n to our single-model labels and the flip test below.\n- **How the labels were made.** The creator model (GPT-6.1 Sol, `create_v4`, one call per question; frozen from\n `gpt-6.1-sol.rep2`) labelled them. No person labelled them. Checks\n (`20261021_155704_nuggetization_phases_2_to_4_execution.md` §2.4 and later):\n - Gemini 3.1 Pro and Qwen 3.8 Max created nuggets independently. Where all three families produced the same\n nugget, they gave it the same importance 81 % of the time.\n - The audit found most planted importance errors but missed three vital → okay relabels.\n - In the phase 5 robustness test (`20261023_210727_…`), S2 − S1 stayed significant in 95 / 79 / 65 % of\n replicates (Luna) with 10 / 20 / 30 % of the labels flipped at random.\n- **What the current dashboard shows.** Tab 5 says that nuggets are vital or okay, has a calculator for the\n metrics, and has a robustness chart with random vital ↔ okay flips (tab 6). Tab 7 shows each nugget's\n importance only as small grey text (`id · vital · category`). The dashboard does not show the C4 test, who\n assigned the labels, or the agreement across model families.\n- **Added in the trace view:**\n - a vital / okay badge on every nugget, with the C4 test and the label's source (creator model, prompt) on\n hover;\n - the per-nugget `stability` (how many of the three families produced the nugget);\n - where the cross-family alignment links the frozen nugget to a nugget of another family, the importance that\n family gave it. The frozen set comes from `rep2` and the alignment from `rep0`, so this link is checked in\n step 2 before it is shown.\n - The same short explanation, with the references, is added to tab 5's text.\n","20261110_194056_question_trace_dashboard_implementation.md":"# Question trace tab: implementation and checks\n\n**Generated:** 2026-11-10 19:40:56 (local time, from `date +%Y%m%d_%H%M%S`).\n**Purpose:** records how the question-trace tab of the results dashboard was built, what it shows, where each\npiece comes from, the files fetched from the Hub to complete this computer's data, and the checks run.\nIt decides nothing about the experiments, and it made no LLM calls ($0).\n**Plan:** `20261110_155548_question_trace_dashboard_feasibility_and_plan.md` (decisions D1–D5 there, §7).\n**Request (user, 2026-11-10):** implement that plan.\n\n## 1. How to open and rebuild it\n\n```bash\n.venv/bin/python scripts/report/build_trace_data.py # ≈ 7 min, reads local files only, no API calls\n# or, on another computer: download raw/dashboard_trace.tar.gz from the HF eval repo and `tar -xzf` it from the repo\n# root (docs/20261115_141728_hugging_face_update_dashboard_trace.md)\nxdg-open \"docs/dashboard/index.html#trace/350/jua-4b-mixed/S2/4000/gpt-5.6-luna\"\n```\n\n- **Tab \"8 · Question trace\"**, between the question explorer (7) and the notes, which became tab 9. Tab 7 has a\n \"Trace this question\" button.\n- **Link to a case:** the URL hash `#trace/<question>/<embedding>/<strategy>/<budget>/<generator>` opens it, so a\n case can be cited in a note.\n- **`--questions 001,350`** builds only those question files, for quick work on the page; `--no-docs` skips the\n document files.\n\n| Folder (`docs/dashboard/data/trace/`, gitignored) | Content | Size |\n|---|---|---:|\n| `index.js` | question list, runs, contexts, prompt templates, document list, build checks | 0.2 MB |\n| `q/<question>.js` (715) | one question through every stage (§2) | 325 MB (median ≈ 450 kB; largest 1.1 MB) |\n| `doc/dNNN.js` (453) | one document: every chunk of every strategy, with text and a strategy bitmask | 112 MB (largest 12.5 MB) |\n\nMost of a question file is the rendered context text of its 16 generator contexts (≈ 180 kB), kept so the prompt\ncan be shown (D1).\n\n## 2. What the tab shows\n\n| Panel | Content | Source |\n|---|---|---|\n| Bar | question (number, ◀ ▶), embedding, strategy, budget, context (follows the strategy and budget by default, or any context incl. oracle, wrong-context control, closed book), generator | — |\n| A · Question | text, official answer with each nugget's `source_span` highlighted (click selects the nugget), references with links to B, nugget table: vital/okay badge (hover: the C4 test, who labelled it, the references), the three nugget → document signals of plan §3.1, stability and the other families' importance | `dataset/`, `nuggets/gold/v0-auto/`, ctxsupport labels of `oracle_budget4000` / `16000`, alignment `nuggets/full/align/gpt-6.1-sol.rep0__*` |\n| B · Gold documents | per referred document (or any document opened from C/D/A), the chunks of the selected strategy in file order, the gold article(s) and the groupings that contain them (or the whole document), with type, label, tokens, caput variant, split part, the strategies that index the chunk, its rank in the current run, and the text | `segmented/chunks_all.csv.gz`, `ragpipe.strategies.member_mask` |\n| C · Retrieval | first rank at which each gold item is hit in all 10 strategy × embedding runs; the ranking of the selected run (top 30 / 100, plus every lower row that hits a gold article or provision), with gold marks at the chosen level and the in-context mark for the chosen budget | `runs/retrieval/<emb>/irpf/<S>/rankings.csv.gz`, matched with `ragpipe.relevance.Matcher` |\n| D · Context | the texts of the generator context in context order, token bar (gold in green), rank links to C; the prompt sent, with its parts marked (system instructions, user frame, each inserted context text, the inserted question) and the result of the prompt check | `runs/contexts/<emb>/irpf/<context>/contexts.jsonl.gz`, `scripts/rag/prompts/*.pt.md`, `runs/answers/cache/` |\n| E · Answer | the generator's claims with their grounds (context text number, quote, quote check), the generation-time checks, citations vs. gold; per gold nugget: oracle support → context support → answer label, value check, with the judge's justifications | `runs/answers/.../answers.jsonl`, `nuggets/scoring/{score,ctxsupport}/gold-v0-auto/gemini-3.8-flash/`, `nuggets/scoring/analysis/.../{values_per_nugget,citations_per_answer}.csv.gz` |\n\n**Runs included:** the 29 full runs (25 jua, 4 Gemini), with the oracle and closed-book runs among them. The\npilot-only runs are left out (D2). 16 contexts: 14 jua (incl. `wrong-S2_budget4000` and\n`S2_budget4000_context_v1`) and 2 Gemini.\n\n**In-context marks (C).** For each ranked text and each budget (1k–16k), the builder runs the evaluation's own\n`ragpipe.context.select` (`containment_merge`, overflow `skip`): `#n` = text n of the context; `in #n` = inside\ntext n (a parent that contains it was selected); no mark = not in the context.\n\n**Tab 5** now has a \"Vital or okay\" box: the C4 test, who assigned the labels, the agreement and robustness\nnumbers, and the references with links (plan §8).\n\n## 3. Data fetched from the Hub (this computer)\n\nThe plan's D5 assumed the local files were complete. They were not: the Gemini runs were made on the other\ncomputer (memory `two_machine_state`). Missing here, and fetched from repo B (`eduseiti/BR-TaxQA-R-RAG-eval`,\nstaging commit `0a69ef9`, free):\n\n| Files | Check | Placed in |\n|---|---|---|\n| `runs/retrieval/gemini-emb-2/irpf/{S1,S2,S3,S2c,S4}/rankings.csv.gz` | sha256 = the retrieval run's `manifest.json` outputs (5/5) | `runs/` |\n| `…/eval/either_containment_merge_skip/{per_item,per_question,metrics_by_chapter}.csv.gz` | sha256 = the eval `manifest.json` (3/3) | `runs/` |\n| `runs/contexts/gemini-emb-2/irpf/{S1,S2}_budget4000/contexts.jsonl.gz` | sha256 = the context `manifest.json` (2/2) | `runs/` |\n| `raw/runs_answers_cache.tar.gz` | holds the cache files of all 2,860 Gemini answers | 2,726 missing files added to `runs/answers/cache/` (the others were already here, same request) |\n\nThe downloaded copy stays in `../br-taxqa-r_hf_cache/` (outside the repo).\n\n## 4. Checks\n\nRun by the builder on every build and shown at the bottom of the tab:\n\n| Check | Result |\n|---|---|\n| Strategy chunk counts (S1/S2/S3/S2c/S4, RIR/1999 excluded) | 20,461 / 68,656 / 72,061 / 68,656 / 72,061, as in the results overview |\n| First full and first any hit of every gold item, recomputed with the evaluation's matcher, vs. `per_item.csv.gz` (both embeddings, all strategies, all levels) | 59,120 / 59,120 equal |\n| Budget hits (1k–16k) of every gold item vs. `per_item.csv.gz` | 295,600 / 295,600 equal |\n| Recomputed context selections vs. the stored generator contexts (same strategy and budget) | 7,865 / 7,865 equal |\n| Rebuilt prompt (template + context + question) vs. the request in the LLM cache, byte for byte | 20,253 verified, 0 differ; not verifiable: 476 `skipped` rows (no context, no call) and 6 `error` rows |\n| Judge label count per run vs. `runs.csv` `n` | 29 / 29 equal |\n| Prompt templates unchanged since the runs (sha256 vs. `run.json`) | `answer_v1`, `answer_closed_v1`: unchanged |\n| Nugget `legal_basis` strings resolved to a document | 625 of 677 (92 %), all to a document the question cites; 29 name a document not in the corpus; 23 have no document number |\n\n**Rendering:** headless Chromium (Playwright, from the scratchpad, not a repo dependency) at 1,300 px light and\n390 px dark, on Q350 (jua S2 4k Luna), Q001 (Gemini S1 4k Sabiá-4), Q316 (jua S1 2k, no Sabiazinho-4 run) and\nQ005 (jua S3 4k Terra), clicking a nugget, the prompt button, a ranked row and a justification; phone width also\non Q442 and Q120. Final run: no JavaScript errors, no horizontal page scroll (1,300 and 390 px). Screenshots\nlooked at. Fixed after that review:\n- the \"inside a selected parent\" mark used the colour of a partial provision hit;\n- B called a non-gold focused article \"gold\";\n- B opened in S2 when the link asked for S1;\n- a pasted trace link did not reload the case (no `hashchange` handler);\n- legal-basis citations with the article after the document (\"Lei nº 9.250, …, art. 35\") lost the article, and\n \"Ato Declaratório PGFN nº 2, de 2016\" resolved to the RFB ADE nº 2 of 2024. The resolver now also checks the\n year and the document type prefix (`ad_`, `adi_`, `lei_comp_`, `mp_`…). Resolved strings went from 496 to 625\n of 677;\n- a long URN in B's document header widened the page at phone width (390 px → 564 px).\n\n## 5. Limits\n\n- **The nugget → document link is a set of signals, not a gold link** (plan §3.1; D4: no LLM attribution). The\n BM25 candidate is labelled as a heuristic. Legal-basis strings with no document number (e.g. \"art. 8º\" alone,\n which refers to the document the answer cites elsewhere) stay unresolved.\n- **No nuggets are extracted from the answers** (D3). E shows the generator's claims next to the judged gold\n nuggets; it does not say which claim covers which nugget.\n- **Gold marks for oracle and other non-strategy contexts in D** come from the chunk's own article, not from the\n matcher (a grouping chunk there is marked only at the document level).\n- **Size:** ≈ 440 MB of gitignored files. A question file loads in well under a second from disk; the largest\n document file (12.5 MB) takes a moment.\n- **Tab 7's per-question files** were also missing on this computer; `build_dashboard_data.py` was rerun\n (`core.js` changed only in its build time; `docs.js` now holds this note and the plan).\n- **No automated test suite for the page**; the checks above cover the data, the screenshots the rendering.\n","20261115_141728_hugging_face_update_dashboard_trace.md":"# Hugging Face update: the dashboard question-trace data added to the evaluation repo\n\n**Generated:** 2026-11-15 14:17:28 (local time, from `date +%Y%m%d_%H%M%S`).\n**Follows:**\n- `20261110_194056_question_trace_dashboard_implementation.md`: the trace tab and its builder;\n- `20261108_231904_hugging_face_update_gemini_embedding_2.md`: the previous update of repo B (same procedure).\n\n**Why:** the trace tab (tab 8 of `docs/dashboard/index.html`) reads `docs/dashboard/data/trace/`. That folder is\ngitignored (≈ 440 MB) and was not on the Hub, so on any other clone the tab showed \"Trace data not found\".\n\n**Result:** repo B (`eduseiti/BR-TaxQA-R-RAG-eval`) `0a69ef9` → **`4ddc246`**\n(`4ddc246f0ee7915ad0106c9660d6d90425126c92`), recorded in `release/hf_release.json`. Repo A is unchanged.\n\n**Cost:** $0. No LLM or embedding calls were made.\n\n## 1. What changed\n\n| Path in B | Change |\n|---|---|\n| `raw/dashboard_trace.tar.gz` | **new**, 42.9 MB: 1,169 files = `index.js` + 715 `q/*.js` + 453 `doc/*.js`, stored under `docs/dashboard/data/trace/` |\n| `docs/20261109_123355_results_dashboard.md`, `docs/20261110_194056_question_trace_dashboard_implementation.md` | new |\n| `README.md` (card), `SHA256SUMS`, `release_manifest.json` | changed: the card describes the archive and how to restore it |\n\nNothing else changed (`push_release.py --dry-run`: 3 new, 3 changed, 0 only on the remote).\n\nIn git:\n- `scripts/release/repo_b.yaml`: the archive is a `pack` entry, built deterministically like the cache archives.\n- `scripts/release/cards/repo_b.md`: a paragraph on the archive.\n- `docs/dashboard/index.html`: the \"Trace data not found\" message now gives the download command as well as the\n rebuild command.\n\n## 2. Using it on another computer\n\nFrom the root of a clone of the git repo (the dashboard pages and its other data are in git):\n\n```bash\nhf auth login # the repo is gated: request access on its Hub page first\nhf download eduseiti/BR-TaxQA-R-RAG-eval raw/dashboard_trace.tar.gz --repo-type dataset --local-dir .\ntar -xzf raw/dashboard_trace.tar.gz # -> docs/dashboard/data/trace/\nxdg-open docs/dashboard/index.html # works from file://, no server\n```\n\nThe data must match the dashboard's other data (built from the same results). If the results change, rebuild\nwith `scripts/report/build_trace_data.py` and repack (`build_release.py --repos b --keep-raw` after removing\n`raw/dashboard_trace.tar.gz` from the release tree, since `--keep-raw` keeps an existing archive).\n\n## 3. Build and checks\n\n```bash\n.venv/bin/python scripts/report/build_trace_data.py # 234 s\n.venv/bin/python scripts/release/build_release.py --repos b --keep-raw # packs only the new archive\n.venv/bin/python scripts/release/push_release.py --tree ../br-taxqa-r_hf_release/BR-TaxQA-R-RAG-eval \\\n --repo-id eduseiti/BR-TaxQA-R-RAG-eval --dry-run # then without --dry-run\n```\n\n- **Builder checks:** the same values as in the implementation note §4. Chunk counts 20,461 / 68,656 / 72,061 /\n 68,656 / 72,061; per-item ranks 59,120 and budget hits 295,600 all equal; context selections 7,865 equal;\n prompts 20,253 verified, with 476 skipped and 6 error rows not verifiable; label counts 29 / 29;\n `legal_basis` 625 / 29 / 23.\n- **No local paths** in the trace files: a grep for `/work/`, `/root/`, `/home/` and `file:///` found nothing.\n The page loads them with relative `<script>` paths.\n- **Round trip:** the archive was downloaded from the Hub at `4ddc246` and extracted into an empty folder.\n `diff -rq` against the local `docs/dashboard/data/trace/` found no differences.\n\n## 4. Repo visibility (found during this update)\n\n`release/hf_release.json` and the release plan §9 describe both repos as \"staging (private)\". On 2026-11-15 the\nHub reports both `eduseiti/BR-TaxQA-R` and `eduseiti/BR-TaxQA-R-RAG-eval` as **public and gated**. An anonymous\ndownload returns 401 \"restricted\". `push_release.py` never changes visibility, so the change was made on the Hub\nbefore this update. The new record in `hf_release.json` says \"staging\" without \"(private)\".\n","20261115_145149_corpus_and_question_explorer.md":"# Corpus & question explorer: a second dashboard, built on the question-trace data\n\n**Generated:** 2026-11-15 14:51:49 (local time, from `date +%Y%m%d_%H%M%S`).\n**Page:** `docs/explorer/index.html` (static, opens from `file://`).\n**Data:** `scripts/report/build_explorer_data.py` (≈ 20 s, no API calls) → `docs/explorer/data/` (gitignored, ≈ 17 MB).\n**Reuses:** the question-trace data `docs/dashboard/data/trace/` (`scripts/report/build_trace_data.py`;\n`20261110_194056_question_trace_dashboard_implementation.md`) and the trace tab's rendering code, copied into the new\npage. The results dashboard `docs/dashboard/index.html` is unchanged and kept as a reference, so its views can be\npulled into the explorer later. The explorer links to it from the header.\n\n## 1. What it shows\n\nTwo entry points, each a searchable and sortable list:\n\n**Questions** (`#/q`): all 715 questions, with chapter, explicit and embedded references, documents, nuggets, the\nmean V_strict over the scored runs, and the article recall of jua S2 at 4k. One question (`#/q/<n>`) has six\ncollapsible sections:\n\n| Section | Content |\n|---|---|\n| Official answer | with each nugget's source span highlighted; a click opens that nugget |\n| Gold nuggets | one collapsible row per nugget, with a strip of its label in every scored answer. Open: id, category, values, oracle 4k/16k support with the judge's justification, the legal basis in the nugget (linked to the corpus), the closest gold text (BM25), other model families |\n| Referred documents | the references grouped by document, each marked explicit or embedded. Open: citation, articles, provisions, and links to the document or article in the corpus |\n| Gold segments by strategy | for each gold article or provision, the chunks of each strategy (S1, S2, S3, S2c, S4) that the evaluation's matcher counts as a hit, full or partial: an item × strategy matrix, then one collapsible item per strategy with the chunk texts |\n| Retrieval | per-question metrics of the 10 runs (5 strategies × 2 embeddings) for the chosen gold level: recall at the 5 budgets, R@1/5/10/100, MRR, nDCG@10, context precision; the first rank of each gold item in each run; each run's ranking with gold and in-context marks |\n| Answer generation | V_strict, V, W, A_strict and the label counts of every scored run (29); a nugget × run label grid; per run the context (token bar and items), the prompt as sent (with the LLM-cache check), the answer's claims and their quotes, and each nugget's label against the oracle context, the run's context and the answer |\n\n**Corpus** (`#/d`): the 453 documents, with kind, date, files, articles, chunks per strategy, the questions that\ncite each one, and its explicit and embedded references. One document (`#/d/<id>`) has four sections:\n\n| Section | Content |\n|---|---|\n| Questions that cite this document | one row per reference, filterable by origin (explicit, embedded), with the articles and provisions cited; a row opens the question |\n| Segmentation overview | per strategy: chunks, tokens (total, median, max), chunks per type |\n| Structure: articles compared across strategies | one collapsible row per article (main text, then annexes), with the chunk count of each strategy and the number of questions that cite it. Open: the citing questions, then per strategy its chunks and, in S3/S4, the groupings that contain it. Filter by label, or show only the cited articles. Chunks outside articles and grouping chunks are listed apart. A document without articles gets one list per strategy. |\n| Chunks of one strategy, in file order | the index as the retriever sees it, 300 at a time |\n\n**Navigation:**\n- Every page is a URL hash, so the browser's Back and Forward buttons work, and so does the \"◀ Back\" button.\n- A trail of recent pages sits in the header. Returning to a page restores its scroll position.\n- Links between the two explorers:\n - a document, article or nugget legal basis → the corpus page, opened at that article;\n - a ranked row, context item, cited `[Documento n]` or gold segment → the corpus page, opened at that chunk, with\n the chunk outlined;\n - a citing question → the question page.\n\n**Collapsing:**\n- Every block is a `<details>` section whose content is built only when it is first opened. This keeps the long\n documents fast; the RIR/1999 has more than 1,000 articles.\n- Each section remembers whether it was open, in this browser (`localStorage`, optional). Open \"Retrieval\" on one\n question and it stays open on the next.\n- \"Expand all\" and \"Collapse all\" act on the top-level sections.\n\n## 2. Data added by `build_explorer_data.py`\n\nThe trace data had no per-document list of citing questions, no chunk ↔ gold mapping beyond the ranked rows, and\nno per-question metric tables. The builder reads local files only:\n- the dataset;\n- `segmented/chunks_all.csv.gz`;\n- the evaluation's `per_question.csv.gz` of both embeddings (`either_containment_merge_skip`);\n- `nuggets/scoring/tables/gold-v0-auto/gemini-3.8-flash/all/per_question.csv.gz`;\n- the trace's `index.js`, for its run list and as a consistency check.\n\nIt writes:\n- `index.js` (0.37 MB): the documents with their citing references `[question, reference, origin, articles,\n provisions]`, chunk and token counts per strategy, and a summary row per question;\n- `q/<n>.js` (715, 16 MB): the gold segments of each gold item per strategy. These come from\n `ragpipe.relevance.Matcher`, the evaluation's own matcher: full and partial chunk ids, with the excluded documents\n removed as in the indexes. Also the per-question retrieval metrics (`gold = all`, `slice = all`) and the nugget\n scores of the 29 runs in the trace data.\n\n**Check:** the builder stops if its strategy chunk counts differ from the trace data's (20,461 / 68,656 / 72,061 /\n68,656 / 72,061). Gold segments over all questions:\n- article × strategy: 9,720 with a hit, 70 without;\n- provision × strategy: 10,905 with a hit, 245 without.\n\nThe cases without a hit are excluded documents, and provisions that no chunk of that strategy holds in full or in\npart.\n\n## 3. Use on another computer\n\nBoth data sets are on the HF eval repo since 2026-11-15 (commit `ccba6d5`, recorded in `release/hf_release.json`).\nFrom the repo root:\n\n```bash\nhf auth login # the repo is gated\nhf download eduseiti/BR-TaxQA-R-RAG-eval raw/dashboard_trace.tar.gz raw/dashboard_explorer.tar.gz --repo-type dataset --local-dir .\ntar -xzf raw/dashboard_trace.tar.gz && tar -xzf raw/dashboard_explorer.tar.gz\nxdg-open docs/explorer/index.html\n```\n\nOr rebuild them: `scripts/report/build_trace_data.py`, then `scripts/report/build_explorer_data.py`. The explorer\nbuilder needs the evaluation's `per_question.csv.gz`, which is under `runs/` in the HF eval repo.\n\n**Upload (2026-11-15):** `build_release.py --repos b --keep-raw`, then `push_release.py` gave `4ddc246` →\n`ccba6d5`. Changes:\n- new: `raw/dashboard_explorer.tar.gz` (1.2 MB, 716 files) and this note;\n- changed: the card, `SHA256SUMS`, `release_manifest.json`, and the trace implementation note (a pointer to the\n archive).\n\nNothing else changed. The archive was downloaded back from the Hub and is identical to `docs/explorer/data/`.\n\n## 4. Checks\n\nHeadless Chrome (Playwright, from the scratchpad, not a repo dependency):\n- **Pages:** at 1,300 px light and 390 px dark: the question list, Q350, Q001 (many embedded references), Q442 (the\n largest question file), the corpus list, `lei_9250_19951226`, and its art. 8 (cited by 21 questions). Every\n section was opened.\n- **Navigation:** a ranked row → its chunk in the corpus (outlined) → Back returns to Q350; a citing-question row →\n the question.\n- **Sweep:** 7 more questions with every section opened, and every 25th document plus the RIR/1999.\n\nResults:\n- no JavaScript errors;\n- no horizontal page scroll at 390 px, after two fixes (the chapter select, the nugget detail table).\n\nScreenshots looked at. Fixed after that review:\n- the chevron of a long section title wrapped onto its own line;\n- nugget texts were all bold;\n- the split-article note was worded wrong.\n","20261115_172140_gold_matcher_annex_rule_and_misparsed_articles.md":"# Gold matcher: the annex rule and misparsed article chunks — audit and fix plan\n\n**Generated:** 2026-11-15 17:21:40 (local time, from `date +%Y%m%d_%H%M%S`).\n**Status:**\n- **Fix A** (matcher + chunk exclusions + reruns, §4): **done on 2026-11-15**. Results, costs and two deviations\n from §4 are in `20261115_181838_fix_a_gold_matcher_results.md`: only 4 chunks were pure junk and are excluded; a\n second instance is no longer resolved by a first-instance rule, but reported.\n- **Fix B** (corpus revision, §5): **pending**, deferred to a planned corpus revision. Recorded in `CLAUDE.md`\n under \"Pending corpus revision\" so that it is not missed.\n\n**Found:** in the corpus & question explorer (`20261115_145149_corpus_and_question_explorer.md`). On Q006, the \"Gold\nsegments by strategy\" of RIR/2018 art. 1º listed three chunks. Only one is right: art. 1º of the annex (the\nRegulamento). The other two are art. 1º of the Decreto itself (\"Fica aprovado o Regulamento…\") and a citation line\ninside the annex, parsed as an article.\n\n**Not a dashboard bug:** the explorer calls the evaluation's own matcher (`ragpipe.relevance.Matcher`). The same\nmatcher is used by:\n- the retrieval evaluation;\n- the oracle-context builder;\n- the legal-provision (citation) score of the answers.\n\n## 1. The two causes\n\n### 1.1 Annex rule `either` ignores the file the reference names (G3)\n\n`annex_rule = \"either\"` (retrieval plan §4.2, G3) counts article N of the main file **or of any annex** of the\ndocument as the gold article. It was chosen for citations such as \"RIR/2018, art. X\", which do not say whether they\nmean the decree or its annex.\n\nTwo places drop the file:\n- `Matcher._match_provision` adds the files of `article_files()` to `item.lexml_file`, even when the reference's\n provision names the file explicitly (here `lexml/articulados/decreto_9580_20181122.anexo1.xml`).\n- Article-level gold items carry no file at all (key `(document_id, article_id)`), so they always take every file\n that has the article id.\n\nThe 2026-09-27 audit (`20260927_222210_retrieval_legal_provision_test_jua.md` §4) counted 3 article items affected\nand judged `either` vs `main_first` negligible. That count is unchanged. The matcher still lets the main file in\nwhen the reference names the annex.\n\n### 1.2 Misparsed \"articles\": citation lines turned into `Art. N` (G4 gap)\n\nThe statutory parser turned some lines that cite other laws into articles with their own id. In RIR/2018 annex\n(`decreto_9580_20181122.anexo1.xml`), the line before art. 211, \"Art. 1º, art. 2º e art. 4º ao art. 71 da Lei nº\n12.973, de 13 de maio de 2014\", became chunk `decreto_9580_20181122.anexo1#2754`, with `artigo_id = art1`.\n\nThe matcher groups chunks by `(arquivo, artigo_id)`, so that chunk counts as art. 1º of the annex. G4 flags only\nitems reachable **only** through `id_ambiguo = 1` chunks, and the real art. 1º is also there. So nothing was reported.\n\n## 2. Corpus-wide check (2026-11-15)\n\nScripts kept in the session scratchpad; the method is reproducible from this description.\n\n**Annex rule.** Over all gold items (1,958 article, 2,230 provision), the matcher adds chunks from a file other than\nthe one the reference names for:\n- 3 article items: **Q006 art. 1º, Q220 art. 5º, Q264 art. 4º**;\n- 4 provision items: the same 3 questions; Q220 has two provisions.\n\nAll are RIR/2018 (`decreto_9580_20181122`): the annex is cited, and the decree's art. 1º, 4º and 5º are added.\n\n**Misparsed articles.** The check flags any `ART` chunk whose number breaks the sequence of its neighbours (the\nneighbours are consecutive and it is not between them), plus duplicated `(file, article id)` instances. It found 9\nsuspect chunks.\n\n| Chunk | Text (start) | Verdict |\n|---|---|---|\n| `decreto_9580_20181122.anexo1#2754` | \"Art. 1º , art. 2º e art. 4º ao art. 71 da Lei nº 12.973, de 13 de maio de 2014\" | **misparse** (citation line) |\n| `lei_12350_20101220#179` | \"Art. 19. DA LEI Nº 10.973, DE 2 DE DEZEMBRO DE 2004, E O ART. 21 DA LEI Nº 11.196…\" | **misparse** (heading) |\n| `port_conj_tse_srf_74_20060110#23` | \"Art. 81. da Lei nº 9.504/1997 revogado pelo art. 15 da Lei nº 13.165/2015.\" | **misparse** (note) |\n| `in_rfb_1131_20110221#172` | \"Art. 31. ; II – as doações ou patrocínios…\" | **misparse** (fragment) |\n| `circ_bc_3432_20090203#30` | \"Art. 16. da Lei nº 11.795, de 2008, pressupõe a:\" | **misparse** (citation) |\n| `decreto_lei_5844_19430923#391` | \"Da exploração de películas cinematográficas estrangeiras Art. 93. Considera‑se…\" | **misparse** (heading glued on; duplicate art93 out of sequence) |\n| `mp_497_20100727#81` | \"Art. 31. O disposto no art. 22 produz efeitos…\" | to check against the source (duplicate art31) |\n| `decreto_71733_19730118#49` | \"Art. 2º A competência estabelecida neste Decreto…\" | to check (out of sequence, not duplicated) |\n| `port_conj_tse_srf_74_20060110#24` | \"Art. 5º Esta portaria entra em vigor…\" | real: flagged only because of the misparsed art. 81 before it |\n\n**Duplicates.** 96 `(file, article id)` pairs in 23 files have more than one separate instance. 21 are at article\nlevel:\n- Lei 12.715 arts. 69–78;\n- Decreto-Lei 58/1937 arts. 1º–4º;\n- MP 2.228-1 annex art. 33 (three times);\n- Circular BC 3.432 art. 16;\n- Decreto 71.733 art. 22;\n- plus the misparses above.\n\nThe rest are alíneas, items and paragraphs repeated in treaty annexes and forms. Most look like text repeated in the\nsource documents, not parser errors; check each one in the corpus revision. **Only Q006 has a gold item on a\nduplicated id.**\n\n## 3. Effect on the results\n\n- **Retrieval:**\n - No suspect chunk is in any retrieved generator context: S1, S2, S3, S2c, S4, every budget, both embeddings, and\n the wrong-context control.\n - For the affected gold items, the first-hit ranks and the context hits at 1k–16k are the same in all 10 runs\n whether or not the wrong chunks count. The right annex chunk is always reached first or at the same budget.\n - **No retrieval metric changes.**\n- **Oracle contexts** (built with the matcher), 4k and 16k:\n - Q006, Q220 and Q264 also hold the decree article (88–108 tokens). Q006 also holds the misparsed `#2754`\n (128 tokens).\n - Q438 cites the whole portaria, so its oracle context also holds the misparsed \"Art. 81\" line.\n - Through the oracle contexts, this reaches the oracle answers (4 generators × oracle 4k) and the oracle\n nugget-support labels of these **4 questions out of 715**.\n- **Legal-provision score of answers:** the same matcher, so an answer citing the decree article instead of the\n annex counts as correct for Q006, Q220 and Q264. Not yet checked whether any answer did. Check it in step 6 of §4.\n\n## 4. Fix A — matcher, chunk exclusions, reruns (done 2026-11-15; see the results note)\n\n**Code changes:**\n1. **Annex rule, provision level:** `Matcher._match_provision` matches only `item.lexml_file` when the reference\n names one. `either` applies only to provisions without a file.\n2. **Annex rule, article level:** article gold items carry the file(s) their reference's provisions name, when every\n provision of the reference names the same file. They match only that file. Otherwise `either` stays as it is.\n3. **Duplicated ids (G4):**\n - a chunk in a separate instance of the article id does not hit the gold article;\n - the evaluation report lists every gold item that matches more than one instance, not only the items\n reachable solely through `id_ambiguo = 1` chunks.\n\n Picking the right instance: the one that holds the fragment the reference names. Otherwise the first instance in\n file order. The misparses are all later ones.\n4. **Chunk-level exclusions:**\n - `scripts/rag/corpus_exclusions.yaml` gets a `chunks:` section with the 6 misparsed chunk ids (§2), each with\n its reason, and with the chunk ids of the S2/S2c/S3/S4 sub-units of the same misparsed articles.\n - `ragpipe.exclusions.Exclusions.row_mask` handles it.\n - Retrieval drops them; no re-embedding is needed.\n - Check the two \"to check\" rows of §2 against the source before adding them.\n\n**Reruns:**\n\n| Step | Command (see the phase notes) | Cost |\n|---|---|---|\n| 5. Retrieval with the new exclusions | `rag.py retrieve`, both embeddings (≈ 30 s each). Rankings lose only the excluded chunks. | $0 |\n| 6. Evaluation | `rag.py evaluate` main eval `either_containment_merge_skip`, both embeddings. Then compare `metrics.csv` and `per_item.csv.gz` with the current ones; expected: only the affected items' rows. Check the legal-provision score of the answers of Q006/220/264 (§3). | $0 |\n| 7. Generator contexts | `rag.py context` (≈ 70 s). Expected: only the oracle 4k/16k contexts of Q006, Q220, Q264, Q438 change; verify that every retrieved context is byte-identical. | $0 |\n| 8. Oracle answers | the 4 generators × oracle 4k for those 4 questions = 16 calls (the rest come from the LLM cache). Check whether pilot runs with oracle 16k include them. | ≈ $0.07 |\n| 9. Judge | rescore the 16 answers (`nuggets.py score`), oracle context support 4k/16k for the 4 questions (`ctxsupport`, 8 calls). Then `scoretable`, `analyze`. | ≈ $0.15 |\n| 10. Dashboards | `build_dashboard_data.py`, `build_trace_data.py`, `build_explorer_data.py` | $0 |\n| 11. Hugging Face | repo B update (`build_release.py --repos b --keep-raw`, `push_release.py`). Repo A does not change: no corpus file changes. | $0 |\n\n**Total:** ≈ $0.25 of the $150 OpenRouter budget. Pass `--budget` on every LLM run (CLAUDE.md) and record the\ncosts in the ledgers.\n\n**Expected change in the headline numbers:**\n- retrieved-context runs: none;\n- oracle runs: 4 of 715 questions.\n\nReport the before/after values of `runs.csv` and the retrieval `metrics.csv` in the results note of this fix.\n\n## 5. Fix B — corpus revision (pending; do not lose)\n\nThe parser output itself is wrong for at least the 6 documents of §2. Chunk exclusions (A.4) hide the bad chunks\nfrom retrieval, but:\n- the LexML files and `segmented/` still hold them;\n- their text is missing from the article it belongs to, where it was a heading or a citation note;\n- the benchmark on Hugging Face (repo A) ships them.\n\n**To do in the next corpus revision:**\n1. Repair the parse of the 6 documents (and the 2 \"to check\" ones if confirmed). The fix belongs in the sibling\n parser `../lexml-parser-projeto-lei/` (statutory) or in a `.docx` repair under `scripts/lexml/`, as for the\n earlier repairs (`20261007_180833_corpus_fixes_and_full_rebuild_plan.md`). Then re-parse.\n2. Review the 21 article-level duplicate ids (§2) against the sources: Lei 12.715 arts. 69–78, Decreto-Lei 58/1937\n arts. 1º–4º, MP 2.228-1 annex art. 33, etc. Repeated source text is fine; parser duplication is not.\n3. Add both checks of §2 to the article-coverage audit in `scripts/lexml/`:\n - article numbers out of sequence;\n - duplicated `(file, article id)` instances.\n\n The next rebuild then reports them.\n4. Re-segment (the amended XSL in `scripts/`). Chunk ids within the repaired documents are renumbered.\n5. Re-embed only the chunks whose text changed (both embeddings; cents). That includes the S3/S4 grouping chunks\n that contain them.\n6. Rerun retrieval, evaluation and contexts. Answers whose prompt text is unchanged come from the LLM cache at no\n cost; regenerate and rescore only those that changed.\n7. Remove the chunk-level exclusions of A.4 that the repair makes unnecessary.\n8. New release of **repo A** (the benchmark: LexML, chunks) and repo B.\n\nTrigger: the next planned corpus revision, or before the public release (moving the HF repos to `unicamp-dl`),\nwhichever comes first.\n","20261115_181838_fix_a_gold_matcher_results.md":"# Fix A (gold matcher, misparsed chunks): execution and results\n\n**Generated:** 2026-11-15 18:18:38 (local time, from `date +%Y%m%d_%H%M%S`).\n**Plan:** `20261115_172140_gold_matcher_annex_rule_and_misparsed_articles.md` §4 (approved by the user on\n2026-11-15). Fix B (corpus revision, §5 there) is still pending.\n\n**Cost:** $0.168 list, **$0.076 billed**:\n- generation: 16 calls, $0.063 list, $0.023 billed;\n- judge: 15 calls, $0.105 list, $0.052 billed.\n\nThe ledgers are `runs/costs.csv` and `nuggets/scoring/costs.csv` (rows of 2026-11-15).\n\n**Backup** of every output before the fix: `../br-taxqa-r_fixA_backup_20261115/` (outside the repo, 306 MB):\n- retrieval, evaluations, contexts;\n- oracle answers;\n- scoring `score/`, `ctxsupport/`, `tables/`, `analysis/`.\n\n## 1. Code changes\n\n| File | Change |\n|---|---|\n| `scripts/rag/ragpipe/relevance.py` | **G3 only for citations that name no file.** A provision whose `lexml_file` holds the article matches that file only. An article item carries `GoldItem.files`, the files named by its references' provisions, and matches only those when they hold the article. **G4.** `Matcher(ignore_rows=…)` drops the misparsed chunks from article and unit matching. The separate instances of an article id are computed (`article_instances`), the groupings that contain each instance count, and `Match.instances` reports items that match more than one instance. Match cache key includes the named files: the same `(doc, article)` cited by two questions can name different files. |\n| `scripts/rag/ragpipe/exclusions.py`, `retrieval.py` | `corpus_exclusions.yaml` gets a `chunks:` section. `Exclusions.chunk_row_mask()`; `row_mask()` also drops these chunks from retrieval; the manifest records them, and the retrieval params record `excluded_chunks`. That entry is added only when the list is non-empty, so runs without chunk exclusions keep their hash. |\n| `scripts/rag/corpus_exclusions.yaml` | `chunks:` the **4 pure-junk chunks**: RIR/2018 annex `#2754`, Lei 12.350 `#179`, Portaria Conj. 74 `#23`, Circular BC 3.432 `#30`. Each is the only chunk of its misparsed instance. Not listed, because they hold real legal text: IN RFB 1.131 art. 31 (2nd instance), DL 5.844 \"art. 93\" (2nd), MP 497 art. 31 (two wordings). Fix B repairs them. |\n| `ragpipe/evaluation.py` | per-item column `multi_instance`, reachability column `multi_instance_matches`; matcher built with the chunk exclusions |\n| `ragpipe/contexts.py`, `nuggetizer/analysis.py`, `nuggetizer/ctx_audit.py`, `scripts/report/build_trace_data.py`, `build_explorer_data.py` | every matcher is built with the chunk exclusions of the retrieval manifest |\n| `scripts/nuggets/nuggetizer/analysis.py` | **Separate bug found while rerunning `analyze` (§4).** `citation_scores` read every run against the primary embedding's contexts and keyed it by the bare set name. Now it reads the run's own context (`run.json` `context.path`) and keys it with `scoring.context_key`. |\n| `scripts/rag/tests/` | 2 fixture tests updated: Q003 of the fixture names the main file for art. 1, so the annex art. 1 no longer counts. 2 new tests: the G3 rule for named files, and ignored rows / instances. **46 passed.** |\n| `scripts/rag/experiments/fixA_oracle.yaml` | the regeneration of `oracle_budget4000` only (§3) |\n\n**Effect of the new matcher on the gold items**, old vs new matcher over all gold items:\n- **7 items changed**, exactly the planned ones: the article and provision items of Q006 art. 1º, Q220 art. 5º and\n Q264 art. 4º.\n- Removed: the decree's art. 1º, 4º and 5º, and the misparsed `#2754`.\n- Q006 also **gains** two grouping chunks of the annex, TÍTULO I `#3660` and CAPÍTULO I `#3699`. Before, the junk\n instance stretched art. 1º's interval across the whole annex, so no grouping \"contained\" it.\n- No gold item matches more than one article instance.\n\n## 2. Retrieval, evaluation, contexts (no API calls)\n\n```bash\nset -a; . ./.env; set +a # needed: the Qwen3 tokenizer for rendered-context counts\nP=.venv/bin/python; R=scripts/rag/rag.py\n$P $R retrieve --embedding jua-4b-mixed --force ; $P $R retrieve --embedding gemini-emb-2 --force\n$P $R evaluate --retrieval <run> --force # main eval, both embeddings; + v2d for both; + Gemini's\n # either_containment_skip and v2c (same commands as 2026-11-08)\n$P $R context --retrieval runs/retrieval/jua-4b-mixed/irpf --sets \"<the 13 sets>\" --force # + S2 4k context_v1\n$P $R context --retrieval runs/retrieval/gemini-emb-2/irpf --sets S1@budget=4000,S2@budget=4000 --force\n```\n\njua's two older evaluations (`either_containment_skip`, `v2c_…`) belong to an earlier chunk file and were left as\nthey were.\n\n**Retrieval metrics:**\n- **No budget-view metric changes**, for any strategy, level, budget or embedding.\n- 107 rows (jua) and 30 rows (Gemini) of `metrics.csv` change, all in the raw and unit views of S3/S4, by at most\n +0.0038. The causes:\n - Q006's S3/S4 article and provision become reachable (rank 671 / 716) through the groupings above;\n - ranks shift by one where a removed junk chunk used to rank above (Q248, 261, 264, 265, 289, 295);\n - unit positions shift by one in S3/S4, because the groupings that contain RIR art. 1º now also project that\n article as a unit.\n- `multi_instance_matches` = 0.\n- Q006's remaining art. 1º chunks carry the corpus flag `id_ambiguo = 1`, so its item is now `only_ambiguous`. The\n flag will clear when fix B repairs the corpus.\n\n**Contexts:**\n- The **text** of every retrieved context (S1/S2 2k–8k, S2c/S3/S4 4k, context_v1, wrong-context, both embeddings)\n is byte-identical. Only the `rank` of a few items moves by one, where a junk chunk ranked above.\n- Only the oracle contexts changed, for:\n - **Q006, Q220, Q264, Q438 at 4k**;\n - Q006, Q220, Q438 at 16k. Q264 16k keeps its texts, and only its gold record changes.\n- Contexts ↔ evaluation consistency: 0 mismatches.\n\n## 3. Oracle answers and judge\n\n- **Regeneration:** `rag.py run --experiment scripts/rag/experiments/fixA_oracle.yaml --budget 73.33 --force`.\n - 16 new calls: 4 generators × Q006/220/264/438; everything else came from the cache.\n - The other experiments were not rerun: their dry runs showed 6 old `max_tokens` errors that a rerun would retry,\n which is out of the scope of this fix.\n - The answer text changed for Q006, Q220 and Q264 (all generators except Sabiá-4 on Q006) and for Q438\n (Sabiazinho-4 only). The other answers to the new contexts came back with the same text.\n- **Judge:**\n 1. The old labels of the 4 questions were removed from the 4 `score/…/oracle_budget4000` folders and from\n `ctxsupport/…/oracle_budget4000`, since `score` keeps existing labels.\n 2. `nuggets.py --out nuggets/scoring --sample all --budget 143.60 score --runs \".../oracle_budget4000\"`: 11 new\n calls. The 5 answers with unchanged text produced the same request and were cached.\n 3. `ctxsupport --contexts …/oracle_budget4000`: 4 calls.\n\n No other judge, nugget set or oracle 16k label covers these questions.\n- Then `scoretable` and `analyze`.\n\n**`runs.csv` (gold, Gemini 3.8 Flash, all), the only rows that changed:**\n\n| Run | V_strict | V | W | A_strict |\n|---|---|---|---|---|\n| Luna oracle 4k | 0.3384 → 0.3393 | 0.4750 → 0.4754 | 0.4352 → 0.4354 | 0.2993 → 0.2997 |\n| Terra oracle 4k | 0.3682 → 0.3679 | 0.5144 → 0.5143 | 0.4711 → 0.4710 | 0.3248 → 0.3246 |\n| Sabiá-4 oracle 4k | 0.3187 → 0.3185 | 0.4623 → 0.4621 | 0.4219 → 0.4218 | 0.2784 → 0.2783 |\n| Sabiazinho-4 oracle 4k | 0.2935 → 0.2915 | 0.4614 → 0.4596 | 0.4247 → 0.4229 | 0.2630 → 0.2609 |\n\nFor Sabiazinho-4, the abstention rate is 0.057 → 0.059: one of the new answers abstains.\n\n**`comparisons.csv`:**\n- Only the 44 comparisons against oracle 4k changed, with |Δ diff| ≤ 0.002.\n- **No significance flip:** p_perm at 0.05 and CIs excluding 0 are unchanged.\n- S1 vs S2 and every other comparison are unchanged.\n\n## 4. Analysis tables: first regeneration since 2026-10-24, and the citation bug\n\nThe `analysis/` outputs in git dated from 2026-10-24: before the Gemini runs, and before the context-support labels\nof the wrong-context set. Regenerating them for this fix brings in those additions too:\n- 4 Gemini runs in the run-level tables;\n- the wrong-context linkage, `n_ctx0` 0 → 30.\n\nRegenerating them also **exposed a bug** introduced with the Gemini runs (commit 83b3f55). `citation_scores` read\nevery answer run against the jua contexts and keyed it by the bare set name. So:\n- the Gemini answers' `[Documento n]` citations were resolved against the jua contexts;\n- the run-level citation tables pooled jua and Gemini (jua Luna S1 article `n_cited` 2.14 became 1.80).\n\nFixed (§1). With the fix:\n- every jua run-level citation row equals the old one, except the oracle 4k rows (|Δ| ≤ 0.007);\n- per answer, the citation table differs from the old one only for Q006/220/264/438 in the oracle 4k runs. So **no\n answer of a retrieved-context run cited the decree article in place of the annex**: the citation score of those\n runs does not change.\n\n**What fix A changes in the analysis:**\n- utilisation, values and PGD tables: only the oracle 4k rows (|Δ| ≤ 0.007);\n- `slices_comparisons`: only comparisons against oracle 4k (|Δ diff| ≤ 0.003).\n\n`perturbation_s1_s2`'s inputs are unchanged. Its rows moved by Monte Carlo noise: mean diff ≤ 0.0004, and the\nshare of significant draws by up to 0.05. The label table now also holds the Gemini rows, which reorders the seeded\ndraws.\n\n## 5. Dashboards and release\n\n- `build_dashboard_data.py`, `build_trace_data.py` and `build_explorer_data.py` were rerun; their results are in the\n update of the HF eval repo, §6.\n- Repo A is unchanged: no corpus file changed.\n\n## 6. Hugging Face\n\nRepo B updated: `ccba6d5` → **`ea67478`** (`ea67478af8296b61ffe9725ffb0d681f2c5e4b18`), recorded in\n`release/hf_release.json`. 2 new files (the two notes) and 129 changed.\n\n| What changed | Files |\n|---|---|\n| Retrieval runs and evaluations, both embeddings | rankings, manifests, `metrics.csv`, `per_item`, `per_question`, `reachability`, `report.md` |\n| Generator contexts | text unchanged except the oracle contexts; ranks and manifests change |\n| The 4 oracle 4k answer runs, their scores and context support | answers, labels, calls |\n| Scoring tables and the 9 analysis tables | `nuggets/scoring/tables/`, `nuggets/scoring/analysis/` |\n| The 6 Parquet viewer tables | `tables/` |\n| Cost ledgers | `runs/costs.csv`, `nuggets/scoring/costs.csv` |\n| Archives repacked | answer cache 18,600 → 18,616 requests; scoring cache 26,420 → 26,435; trace and explorer data |\n| Release files | card, `SHA256SUMS`, `release_manifest.json` |\n\nBefore pushing, the two cache archives were checked against the local caches: the local caches are the published\narchives plus the new calls only. Repo A is unchanged.\n","20261122_130934_retrieval_scoring_granularity_and_answer_quality.md":"# Retrieval scoring across granularities, and its link to answer quality\n\nDate: 2026-11-22. Discussion note (no code changes, no API calls). Covers:\n\n- how the legal-provision retrieval test (`scripts/rag/ragpipe/relevance.py`, `evaluation.py`) scores\n chunks whose granularity differs from the gold reference's;\n- an ad hoc check of whether citation granularity explains the S1 vs S2 difference in answer quality\n (nugget phase 5 scores);\n- how S3's grouping chunks fare under the same rules.\n\nAll retrieval numbers come from the **main evaluation `either_containment_merge_skip`**, with\nparent/child merging, the setting the generator contexts use. A first version of this note used\n`v2d_either_containment_skip` (containment only, no merge). That overstated S1's lead on whole-article\ncitations. The conclusions do not change. The answer results never depended on the evaluation, since\nthey come from the merged contexts.\n\n## Summary\n\n1. **S1 chunks against sub-article references.** A whole-article S1 chunk is a **full hit** for any\n unit inside the article (G5: its `cobre_ids = [artN]`, an ancestor of every unit in it). The\n exception is an oversize article split into parts: each part fully hits only the units it holds.\n The article itself is then fully hit only when all parts are in the context (`Match.parts`). So S1 is\n not penalised by the hit definition. Its cost shows up through the token budget (fewer distinct\n articles fit) and in context precision.\n2. **S2 at the article level vs the provision level.** The two levels are scored differently.\n - **Article level (G2):** any chunk of the article (ART, caput, paragraph, inciso…) is a full hit.\n - **Provision level (G5):** a full hit needs a chunk that contains the cited unit (the unit, an\n ancestor, a grouping chunk, or all parts of a split article). Descendant chunks are only\n **partial** hits (`budget_any_*`).\n\n So for a **whole-article** citation at the provision level, only the S2 ART chunk (or all its parts)\n counts as full. S2's sub-unit chunks count only as \"any\" hits.\n3. **Retrieval numbers** (jua-4b-mixed, `irpf`, budget 4000):\n\n | Gold items | S1 | S2 |\n |---|---|---|\n | Provision, sub-article (820), full | 0.287 | **0.406** |\n | Provision, whole-article (1377), full | **0.257** | 0.234 |\n | Provision, whole-article, any | 0.266 | **0.295** |\n | Article level (1958) | 0.279 | **0.357** |\n\n The S1/S2 ordering flips between the article level and the strict provision level for\n whole-article citations.\n4. **Effect on answer quality (questions grouped by citation granularity).** Of the 596 questions\n with legal references: 187 cite only whole articles, 130 only sub-article units, 235 a mix, 44\n no statutory provision. The retrieval premise holds in both pure groups. **Only half of the hypothesis holds for answers:**\n - *Sub-article questions:* S2 > S1 for 5 of the 6 generator/embedding pairs. Significant only for\n gpt-5.6-luna with jua (+0.077 V_strict, CI [0.02, 0.14]).\n - *Whole-article questions:* S1 never wins. The answer difference is ≈ 0, although S1 gets the\n whole cited article into the context somewhat more often (+3.3 points per question with jua).\n\n The result is **asymmetric, not a crossover**: finer chunks help when the citation is fine-grained\n and cost nothing when it is coarse. The grouping ignores document-level references. Dropping the\n questions that cite a document without any article (§3 robustness check) gives the same picture,\n with wider CIs.\n5. **Most likely explanation (reason 1, untested):** the gold answer rarely needs the whole article.\n One or two paragraphs suffice, and S2 retrieves them. Supporting this weakly: per question, the strict provision full hit has\n almost no relation to answer gains on whole-article questions (Spearman 0.02). Metrics that also count\n partial retrieval (article level, provision \"any\") give the same weak signal (≈ 0.09). An earlier\n broader claim, that the article level generally predicts answer quality better than the provision\n level, was **checked and is wrong**: across all questions the provision metrics are slightly\n better. All per-question correlations are weak (≤ 0.25).\n6. **S3 (S2 + grouping chunks).** S3 does **not** retrieve better at the document level: ≈ S2 or\n slightly worse at every budget. It gains where a grouping chunk fully contains what was cited:\n - whole-article provision: +0.02 over S2 at 4000, +0.06 at 16000;\n - article level: +0.01 at 4000, +0.03 at 16000.\n\n Grouping chunks seldom fail to fit (9% of those in the top 10 exceed 4000 tokens). The real cost is\n crowding out: when one is in the context (58% of the questions at 4000), it takes 32% of the tokens.\n The hit rule and context precision are both generous to S3. Answers were generated only at 4000,\n where S3 ≈ S2.\n7. **Open next steps:** (a) add the granularity grouping as a slice in `nuggets.py analyze`\n (`slices_comparisons.csv`, with permutation p and cluster CIs); (b) test reason 1 directly. For\n whole-article questions, check whether S2's partial chunks contain the paragraphs that support the\n gold nuggets (`ctxsupport` tables); (c) a token-weighted hit, which would remove the generosity\n towards S1 (§1) and S3 (§5).\n\n## 1. How S1 chunks are scored against sub-article references\n\nMatching rule G5 (`relevance.py`, module docstring and `_match_provision`). A provision-level gold\nitem is a LexML id (`art5`, `art5_par2`, `art5_par2_inc3`…). Every chunk carries `cobre_ids` (units it\nholds whole) and `parcial_ids` (units it holds in part). A chunk is:\n\n- a **full hit** if some `cobre_ids` id equals the gold id or is its ancestor (`_is_prefix(c, frag)`),\n or if it is a grouping chunk whose interval contains the unit;\n- a **partial hit** if the gold id is an ancestor of something in `cobre_ids` (the chunk holds only a\n piece of the unit), or appears in `parcial_ids`.\n\nAn unsplit S1 article chunk has `cobre_ids = [artN]` and so fully hits every unit of the article.\n\n**Split articles** (`scripts/segmentation/split_oversize.py`, `part_provenance`). Each part lists in\n`cobre_ids` only the whole items it holds (e.g. `art1_par2`). The article id and the ancestors of\nitems cut inside the part go to `parcial_ids`. Hence:\n\n- a sub-article unit is fully hit only by the part that contains it;\n- a whole-article citation is only partially hit by each part. It becomes a full hit when **all**\n parts of one file are retrieved (the G5 refinement, `Match.parts`, `rank_cover` in\n `evaluation.evaluate_strategy`). This is the `reachable_by_parts_only` column: 1.2% of S1\n sub-article items, 11.9% of whole-article items in S1/S2, 4.6% in S3/S4 (where grouping chunks can\n also contain the article).\n\nThis is the mirror of S2 against article-level references (G2): neither strategy is penalised for\nits granularity in the hit definition. The differences come from the budget: an S1 article spends\nmany more tokens to deliver the same inciso, so fewer distinct articles fit, and context precision\ndrops.\n\nSub-article slice, provision level (820 items), budget 4000:\n\n| Strategy | reachable | full hit | any hit |\n|---|---|---|---|\n| S1 | 0.994 | 0.287 | 0.293 |\n| S2 | 0.994 | **0.406** | 0.412 |\n| S3 | 0.994 | 0.407 | 0.413 |\n| S2c | 0.994 | 0.380 | 0.387 |\n| S4 | 0.994 | 0.373 | 0.380 |\n\nS1's reachability equals S2's. It loses about 12 points in the budget view because whole articles\ncrowd each other out, and possibly because a long article's embedding is diluted relative to a\nfocused paragraph.\n\nCaveat: \"hit\" means \"the right text is somewhere in the context\", not \"it is easy to find there\".\n`context_precision` (gold tokens / context tokens) captures part of this. A token-weighted\nprovision hit (unit tokens / chunk tokens) would make it explicit but is not implemented.\n\n## 2. How S2 is scored at the article level vs the provision level\n\n**Article level** (G2, `_match_article`). The gold item is `(document_id, article_id)`. Every chunk\nwhose `(arquivo, artigo_id)` matches is a full hit: ART, caput, any paragraph, inciso or alínea. In\nS3/S4, a grouping chunk containing the article also counts. There is no partial hit at this level.\nThe rank is that of the first chunk of the article. This is the only level (with the document level)\nthat has the `unit` view, where the ranking is collapsed to distinct articles.\n\n**Provision level** (G5). For a whole-article citation (`art5`):\n\n- the ART chunk is a full hit;\n- if the article was split, it is a full hit only once **all** parts are in the context;\n- in S3/S4 a grouping chunk containing the article is a full hit;\n- `art5_par2`, `art5_cpt_inc1`… chunks are partial hits only. They count in `hit_any`\n (`budget_any_*`), not in `hit_full`.\n\nSo yes: for the headline (full) metric, only the position of the whole-article chunk (or its full set\nof parts, or a grouping chunk) is scored.\n\nBudget 4000. The whole-article rows use a rough filter (provision items with `sub_article = False`\nwhose key contains \"art\"):\n\n| Strategy | Provision, whole-article: full | Provision, whole-article: any | Article level |\n|---|---|---|---|\n| S1 | **0.257** | 0.266 | 0.279 |\n| S2 | 0.234 | 0.295 | 0.357 |\n| S2c | 0.245 | 0.300 | 0.347 |\n| S3 | 0.253 | 0.307 | **0.365** |\n| S4 | **0.271** | **0.318** | 0.356 |\n\nAt the article level S2 beats S1 by ~8 points. At the provision level, whole-article citations, S2 is\nbelow S1 on full hits (by 2.3 points): its sub-unit chunks often outrank the ART chunk and use up budget\nwithout fully covering the cited unit. On \"any\" hits S2 is ahead again, by 3 points. S3/S4 recover the\nfull-hit gap through grouping chunks that contain the whole article (§5).\n\nThe two levels ask different questions. The article level asks whether the system found the right\narticle. The provision level asks whether it delivered the whole cited unit. For whole-article\ncitations the latter is strict by design and favours S1. Suggested reporting: article level for\narticle-level citations, provision level for sub-article citations, and whole-article\nprovision results with both full and any. A further source of uncertainty: some \"art. 5º\"\nreferences may really point at one paragraph but were annotated at article level.\n\n## 3. Does citation granularity explain the S1 vs S2 answer difference?\n\n**Hypothesis.** Retrieval favours S1 for whole-article citations and S2 for sub-article ones, so\nanswers should follow: S1 better on questions citing only whole articles, S2 on questions citing\nonly sub-article units.\n\n**Method.**\n\n- Questions are grouped by their statutory provision-level gold items (S1 rows of `per_item.csv.gz`;\n the grouping is the same in every evaluation):\n - `whole_only`: all such items have `sub_article = False`;\n - `sub_only`: all have `sub_article = True`;\n - `mixed`: both kinds;\n - `none`: no statutory provision item.\n\n Counts (all / without documents cited with no article): whole_only 187 / 121, sub_only 130 / 98,\n mixed 235 / 130, none 44 / 3. The remaining 119 of the 715 questions have no gold legal reference\n in the eval. The numbers below use the \"all\" grouping.\n- Answer quality: per-question V_strict from\n `nuggets/scoring/tables/gold-v0-auto/gemini-3.8-flash/all/per_question.csv.gz`, contexts\n `S1_budget4000` vs `S2_budget4000` (and `…@gemini-emb-2`). Paired difference per question, mean,\n percentile bootstrap CI (5000 resamples, seed 0; not cluster-aware).\n\n**Retrieval premise** (provision full-hit recall at 4000, per-question mean):\n\n| Group | jua S1 | jua S2 | gemini S1 | gemini S2 |\n|---|---|---|---|---|\n| whole_only | **0.444** | 0.411 | **0.437** | 0.420 |\n| sub_only | 0.410 | **0.580** | 0.450 | **0.597** |\n| mixed | 0.299 | **0.353** | 0.307 | **0.371** |\n\nThe premise holds in both directions, but asymmetrically. S2's lead on sub-article questions\n(+15–17 points) is much larger than S1's on whole-article ones (+2–3 points).\n\n**Answer quality: V_strict difference, S2 − S1, with 95% bootstrap CI.** gemini-emb-2 answers exist only for\ngpt-5.6-luna and sabia-4:\n\n| Generator | whole_only (n=186) | sub_only (n=130) | mixed (n=235) |\n|---|---|---|---|\n| gpt-5.6-luna, jua | −0.009 [−0.05, 0.03] | **+0.077 [0.02, 0.14]** | +0.024 [−0.01, 0.06] |\n| gpt-5.6-terra, jua | −0.003 [−0.04, 0.03] | +0.017 [−0.05, 0.08] | +0.018 [−0.01, 0.05] |\n| sabia-4, jua | −0.004 [−0.05, 0.04] | +0.035 [−0.01, 0.08] | +0.022 [−0.01, 0.05] |\n| sabiazinho-4, jua | −0.004 [−0.04, 0.03] | −0.015 [−0.07, 0.04] | −0.003 [−0.03, 0.03] |\n| gpt-5.6-luna, gemini | +0.031 [−0.02, 0.08] | +0.042 [−0.01, 0.09] | +0.024 [−0.01, 0.06] |\n| sabia-4, gemini | +0.011 [−0.02, 0.05] | +0.015 [−0.04, 0.07] | −0.020 [−0.06, 0.02] |\n\n(`none`, n=44: noisy; sabia-4/jua +0.095 [0.02, 0.18].)\n\n**Reading.**\n\n- Sub-article questions: S2 ahead for 5 of the 6 generator/embedding pairs, significant for one.\n These questions carry a good share of the overall S2 > S1 gain.\n- Whole-article questions: S1 never wins. Its retrieval advantage on full hits there is small\n (+3.3 points with jua), and S2 leads on \"any\" hits.\n- Mixed: in between, near the overall average (+0.02).\n\nPossible reasons for the whole-article result:\n\n1. the gold answer rarely needs the whole article: one or two paragraphs suffice, and S2 retrieves\n them (its \"any\" hit rate there is higher than S1's);\n2. some whole-article annotations really point at a specific paragraph;\n3. a full S1 article uses budget that S2 spends on other relevant material;\n4. S1's full-hit advantage is small to begin with.\n\n**Document-level references.** The grouping uses only statutory provision-level items. Document-level\nreferences are ignored, and so are the 25 non-statutory provision items. Every article citation also\nyields a document item for its document, so the only signal the grouping misses is a document cited\n**without** any article (e.g. a whole IN). A question with such a document plus whole-article\ncitations is still `whole_only`. `none` holds the questions with only whole documents and/or\nnon-statutory references. Such documents occur in 66 whole_only, 32 sub_only and 105 mixed questions.\n\n**Robustness check: without those questions** (the \"pure\" grouping: whole_only 121, sub_only 98,\nmixed 130). Retrieval gaps widen. Provision full hit at 4000, S1 / S2:\n\n| Group | jua S1 | jua S2 | gemini S1 | gemini S2 |\n|---|---|---|---|---|\n| whole_only | **0.534** | 0.490 | **0.538** | 0.510 |\n| sub_only | 0.464 | **0.635** | 0.537 | **0.665** |\n| mixed | 0.382 | **0.433** | 0.383 | **0.438** |\n\nV_strict difference, S2 − S1 [95% CI]:\n\n| Generator | whole_only (n=121) | sub_only (n=98) | mixed (n=130) |\n|---|---|---|---|\n| gpt-5.6-luna, jua | −0.022 [−0.07, 0.02] | +0.058 [−0.00, 0.12] | +0.033 [−0.01, 0.08] |\n| gpt-5.6-terra, jua | +0.002 [−0.04, 0.04] | +0.003 [−0.07, 0.08] | +0.030 [−0.02, 0.08] |\n| sabia-4, jua | −0.011 [−0.06, 0.04] | +0.047 [−0.01, 0.11] | +0.022 [−0.02, 0.06] |\n| sabiazinho-4, jua | −0.021 [−0.07, 0.03] | +0.006 [−0.06, 0.07] | −0.005 [−0.05, 0.04] |\n| gpt-5.6-luna, gemini | +0.044 [−0.02, 0.11] | +0.050 [−0.01, 0.12] | +0.040 [−0.01, 0.09] |\n| sabia-4, gemini | +0.011 [−0.04, 0.06] | +0.028 [−0.04, 0.09] | −0.029 [−0.08, 0.02] |\n\nSame conclusion, with wider CIs:\n- Sub_only: S2 is ahead for all 6 pairs, none clearly above zero (luna/jua is borderline).\n- Whole_only, jua: 3 of the 4 generators lean slightly towards S1 (−0.01 to −0.02), all CIs including\n zero. With gemini-emb-2 the difference is positive again.\n\nReproduce with the appendix script and `--pure`.\n\n**Implication for the paper.** The effect is asymmetric, not a crossover: fine-grained chunks help on\nfine-grained citations and cost nothing on coarse ones. That is a stronger argument for S2 than the\noverall average alone. The subgroups (130–186 questions) are small, so only one cell clears zero.\n\n## 4. Which retrieval metric tracks answer gains? (checking a claim)\n\nIn the discussion, reason 1 led to the claim that \"the article level predicts answer quality better\nthan the strict provision level\". That claim was based only on the aggregate orderings (article level: S2 > S1\nand answers S2 ≥ S1; strict provision, whole-article: S1 > S2 but answers tied). It was then\nchecked per question. For each question: the retrieval gain S2 − S1 under three metrics, against the\nanswer gain S2 − S1 in V_strict. Spearman correlation, jua, budget 4000, mean over the 4 generators:\n\n| Questions | Article | Provision full | Provision any |\n|---|---|---|---|\n| all (551) | 0.077 | 0.124 | 0.114 |\n| whole_only (186) | 0.091 | **0.024** | 0.092 |\n| sub_only (130) | 0.038 | 0.126 | 0.124 |\n| mixed (235) | 0.100 | 0.158 | 0.125 |\n\nPer generator, all (article / prov. full / prov. any): luna 0.076 / 0.150 / 0.108; terra 0.063 /\n0.095 / 0.108; sabia-4 0.073 / 0.144 / 0.110; sabiazinho-4 0.095 / 0.106 / 0.129. Whole_only, provision\nfull: luna 0.235, terra −0.127, sabia-4 −0.022, sabiazinho-4 0.011.\n\n- **The general claim is wrong:** over all questions the article level tracks answer gains worse\n than the provision metrics.\n- **A narrow version holds:** on whole-article questions the strict full hit has almost no relation to\n answer gains, while counting partial retrieval restores the weak signal. This fits reason 1:\n for these questions, part of the article is about as useful as all of it. It is not consistent across\n generators, though: gpt-5.6-luna shows the opposite (0.235).\n- All correlations are weak (≤ 0.25) and vary by generator. Per-question answer differences are noisy:\n many questions have identical retrieval under both strategies but different answers (generator\n variance, judge noise). So this is a hint, not evidence.\n\nCorrected statement: *for whole-article citations, the strict provision hit does not track answer\nquality on average, while metrics that also count partial retrieval do, weakly.*\n\n## 5. S3: grouping chunks under the same rules\n\nS3 = S2 + chunks for each grouping (parte, livro, título, subtítulo, capítulo, seção, subseção),\nholding the whole grouping's text. Groupings above 8,192 tokens were not emitted\n(`groupings_over_limit.csv`). Grouping chunks are never split into parts.\n\n**How they are scored.** A grouping chunk is a hit at every level for everything inside it:\n\n- document level: its document;\n- article level: every article whose interval it contains (G2);\n- provision level: every unit it contains, as a **full** hit (G5).\n\n**Retrieval by level** (jua, budget view, full hit; whole-article = all provision items with\n`sub_article = False`, so these numbers differ slightly from §2's filtered ones):\n\n| Gold items | Budget | S1 | S2 | S3 | S3 − S2 |\n|---|---|---|---|---|---|\n| Document | 1000 / 4000 / 16000 | 0.298 / 0.503 / 0.708 | 0.395 / 0.575 / 0.752 | 0.392 / 0.568 / 0.744 | −0.003 / −0.007 / −0.008 |\n| Article | 1000 / 4000 / 16000 | 0.126 / 0.279 / 0.450 | 0.211 / 0.357 / 0.528 | 0.213 / 0.365 / 0.560 | +0.002 / +0.008 / +0.032 |\n| Provision, whole article | 1000 / 4000 / 16000 | 0.119 / 0.251 / 0.395 | 0.091 / 0.228 / 0.377 | 0.095 / 0.248 / 0.438 | +0.004 / +0.020 / +0.061 |\n| Provision, sub-article | 1000 / 4000 / 16000 | 0.110 / 0.287 / 0.506 | 0.222 / 0.406 / 0.640 | 0.222 / 0.407 / 0.645 | 0 / +0.001 / +0.005 |\n\nAt 2000 and 8000 the pattern is the same (whole-article S3 − S2: +0.010, +0.045; article: +0.002,\n+0.021; document: −0.002, −0.006).\n\n- **Document level:** no gain. Documents are already easy for S2: one of the top 10 distinct\n documents is right for 96% of questions (unit view, hit@10 0.958 for S2 and S3). A grouping chunk\n brings no new document and takes budget from chunks that might. An S3 context at 4000 has 11.6\n texts from 6.1 documents, against S2's 12.6 from 6.3.\n- **Whole-article citations:** this is where the grouping chunks pay off. A chapter or section chunk\n fully contains its articles, so it is a full hit without needing the ART chunk or all the parts of a\n split article (`reachable_by_parts_only` drops from 11.9% to 4.6%). At 4000 S3 ≈ S1. At 16000 it is\n clearly ahead of both S1 and S2.\n- **Article level:** same pattern, small at 4000 and +3 points at 16000. A bigger budget lets more\n chapter-size chunks in, each counting for every article inside it.\n- **Sub-article citations:** no change. S2's paragraph and inciso chunks already deliver them.\n\n**Do grouping chunks fit in the budget?**\n\n- Size: median 692 tokens, 90th percentile 3030, 99th 7194 (other chunks: median 189). By type,\n median CAP 910, SEC 604, SSC 521, TIT 1886.\n- Ranking (S3 rankings, jua): groupings are 6.8% of the top-10 texts. 46% of questions have one in\n the top 10, 20% in the top 3, 7% in first place.\n- Not fitting is a minor issue: 9% of the top-10 groupings are above 4000 tokens (skipped at that\n budget, `overflow = skip`), 16% above 2000.\n- Crowding out is the real cost. 58% of the S3 contexts at 4000 contain at least one grouping chunk\n (S4: 60%), and when they do it takes **32% of the tokens** on average (19% over all questions). The\n parent/child merge softens this: a grouping that ranks below some of its own articles replaces\n them and costs only the extra tokens.\n\n**Caveats.**\n\n1. *The hit rule is generous to S3.* A chapter with 20 articles is a full hit for all of them, even\n when the relevant paragraph is a small part of 3000 tokens: the S1-vs-sub-article issue of §1 one\n level up.\n2. *S3's context precision is inflated.* It looks clearly better than S2's (article level: 0.169 vs\n 0.145 at 4000, 0.124 vs 0.069 at 16000; provision: 0.162 vs 0.136 at 4000). But all the tokens of a\n grouping chunk that holds a gold article count as relevant. This measures the metric's design, not\n cleaner contexts. A token-weighted hit would fix both caveats.\n\n**Answers.** S3 ≈ S2 overall at 4000 (phase 5 note). Generation ran only at 4000, where S3's\nretrieval gain is still small. The +4 to +6 points on whole articles at 8000–16000 are untested on\nanswers.\n\n## 6. Next steps\n\n1. Add the granularity grouping (`whole_only` / `sub_only` / `mixed` / `none`) as a slice in\n `nuggets.py analyze`, so it lands in `slices_comparisons.csv` with permutation p and cluster CIs.\n2. Test reason 1 directly. For whole_only questions, check whether S2's partial chunks contain the\n paragraphs that support the gold nuggets (`ctxsupport` tables).\n3. A token-weighted hit (unit tokens / chunk tokens), which removes the generosity towards S1 (§1) and\n S3 (§5) and the inflation of S3's context precision.\n4. If S3 is to be tested on answers, use a larger budget (8000–16000), where its retrieval gain on\n whole-article citations appears.\n\n## Appendix: reproduction\n\nRun from the repo root, with no API calls (≈ seconds). The grouping and paired-difference script used:\n\n```python\nimport sys, numpy as np, pandas as pd\nargs = [x for x in sys.argv[1:] if not x.startswith(\"--\")]\nemb = args[0] if args else \"jua-4b-mixed\" # or gemini-emb-2; add --pure for the §3 robustness check\nsuffix = \"\" if emb == \"jua-4b-mixed\" else \"@\" + emb\nd = pd.read_csv(f\"runs/retrieval/{emb}/irpf/eval/either_containment_merge_skip/per_item.csv.gz\")\nd[\"question_number\"] = d.question_number.astype(str)\ns1 = d[d.strategy == \"S1\"]\nprov = s1[(s1.level == \"provision\") & s1.statutory]\ng = prov.groupby(\"question_number\").sub_article.agg([\"size\", \"sum\"])\ncls = pd.Series(\"none\", index=sorted(set(s1.question_number)))\ncls[g.index] = np.where(g[\"sum\"] == 0, \"whole_only\", np.where(g[\"sum\"] == g[\"size\"], \"sub_only\", \"mixed\"))\n# \"pure\" grouping (§3 robustness check): drop questions citing a document without any article of it\nart = s1[s1.level == \"article\"]\ndocs_with_art = set(zip(art.question_number, art.item.str.split(\"|\").str[0]))\ndocq = s1[s1.level == \"document\"]\ndoc_only = set(docq.question_number[[(q, i) not in docs_with_art for q, i in zip(docq.question_number, docq.item)]])\nif \"--pure\" in sys.argv:\n cls = cls[~cls.index.isin(doc_only)]\n\n# retrieval premise: provision full-hit recall at 4000 per class\np = d[(d.level == \"provision\") & d.statutory & d.strategy.isin([\"S1\", \"S2\"])]\nr = p.groupby([\"question_number\", \"strategy\"]).budget_full_4000.mean().unstack().join(cls.rename(\"cls\"), how=\"inner\")\nprint(r.groupby(\"cls\")[[\"S1\", \"S2\"]].mean().round(3))\n\npq = pd.read_csv(\"nuggets/scoring/tables/gold-v0-auto/gemini-3.8-flash/all/per_question.csv.gz\")\npq[\"question_number\"] = pq.question_number.astype(str)\na, b = \"S1_budget4000\" + suffix, \"S2_budget4000\" + suffix\nrng = np.random.default_rng(0)\nfor llm, x in pq[pq.context_id.isin([a, b])].groupby(\"llm\"):\n w = x.pivot_table(index=\"question_number\", columns=\"context_id\", values=\"V_strict\").dropna()\n if a not in w or b not in w:\n continue\n w[\"diff\"] = w[b] - w[a]; w[\"cls\"] = cls.reindex(w.index)\n for c, y in w.groupby(\"cls\"):\n bs = rng.choice(y[\"diff\"].to_numpy(), (5000, len(y))).mean(1)\n print(llm, c, len(y), round(y[\"diff\"].mean(), 3), np.percentile(bs, [2.5, 97.5]).round(3))\n```\n\nFor §4: per question, the retrieval gain is the mean over gold items of `budget_full_4000`\n(article level; provision level, statutory) or `budget_any_4000` (provision), S2 minus S1. It is\ncorrelated (Spearman) with the V_strict gain, per generator and per group (`none` excluded).\n\nFor §5: the level × budget table is `per_item.csv.gz` averaged by strategy. The unit view and context\nprecision come from `metrics.csv` (`gold = all`, `slice = all`). The grouping-chunk statistics come from\n`segmented/chunks_all.csv.gz` (`Tipo` in PRT…SSC), `runs/retrieval/jua-4b-mixed/irpf/S3/rankings.csv.gz`\nand `runs/contexts/jua-4b-mixed/irpf/S3_budget4000/contexts.jsonl.gz` (`items[].tipo`, `tokens_qwen3`).\n","20261122_134404_in_text_legal_citation_scoring_plan.md":"# Plan: scoring the legal provisions that generators cite in their answer text\n\nDate: 2026-11-22. Plan note (nothing implemented yet). It extends the phase 5 citation analysis\n(`docs/20261023_210727_rag_phase5_scoring_and_analysis.md` §6.2, open item 3 of §9) to the citations\nthe generators **write in their answers** (\"conforme o art. 8º, inciso II, da Lei nº 9.250, de 1995\").\nIt also records how the closed-book runs were kept free of web search (§1), which is what makes the\nclosed-book answers a test of the models' own (parametric) knowledge.\n\n## Summary\n\n- **Closed book measures parametric knowledge only; web search was blocked at the API level.**\n - No request can carry tools, plugins, web-search options or an `:online` model.\n - Every reply is checked for tool use, URL citations, search sources and extra billing.\n - All 18,618 generation calls ended `stop`, none rejected.\n\n The prompt has no explicit \"do not search\" instruction. None is needed, since the model has no tool to\n call, and adding one would mean regenerating all closed-book answers. Residual limits: provider\n self-reporting (Maritaca), and the P&R 2024 being in the training data.\n- **What is scored today:** for RAG answers, only the context texts each claim links to as its sources\n (`cited_chunk_ids`), with the retrieval matcher. **Not scored:**\n - the in-text citations of the closed-book answers. 39–79% of these answers cite an article, by\n generator (Terra 79%, Sabiá-4 76%, Sabiazinho-4 61%, Luna 39%);\n - the in-text citations of the RAG answers.\n- **Proposed:**\n 1. extract the in-text citations of every answer (`scripts/dataset/citations.py` for the provision\n chains);\n 2. resolve each act to a corpus document (`lexml-linker` for federal acts, plus a regex resolver for Receita\n Federal acts, plus an alias table for names like RIR/2018);\n 3. score against the gold references at the document, article and provision levels;\n 4. flag citations of non-existent articles, acts outside the corpus and acts from after the reference\n date.\n\n For RAG answers, also compare each claim's in-text citations with the sources it links to and with its\n context.\n- **Cost:** no API calls. Effort: roughly 2–3 days of implementation and validation, most of it the act\n resolver and a manual check of 100–150 citations.\n\n## 1. Closed book as a test of parametric knowledge\n\n### 1.1 Web search and tools are blocked at the API level\n\nDesign: `docs/20261021_194457_first_rag_evaluation_readiness_costs_and_grounding.md` §4.1.\nImplementation: `scripts/llm_client/client.py` (`FORBIDDEN_PARAMS`, `tool_use()`, `ToolUseDetected`,\n`BILLED_TOLERANCE_USD`). The same client serves the RAG and closed-book runs.\n\n**Requests.**\n- The client refuses any registry entry (`scripts/rag/llms.yaml`) with `tools`, `tool_choice`,\n `plugins`, `web_search_options`, `web_search` or `functions`, and any OpenRouter model id ending in\n `:online`.\n- On OpenRouter, web search runs only through the `web` plugin or the `:online` suffix. OpenAI and\n Gemini search grounding run only as tools.\n- The OpenRouter calls (GPT-5.6 Terra and Luna) are pinned to one upstream (`only: [openai/flex]`,\n `allow_fallbacks: false`, `require_parameters: true`), and the serving provider is checked on every\n reply.\n\n**Maritaca.** Its built-in tools (web search, page reading, code execution, Data Ocean) run only when\nthe request lists them. Ours never do.\n\n**Replies.** A reply is rejected (not retried; ledger `finish = rejected:<reason>`) when it shows any\nof:\n- `tool_calls`;\n- `url_citation` annotations;\n- `web_search_sources`;\n- `usage.tool_execution_details` (Maritaca's report of a search or page read);\n- `usage.server_tool_use`;\n- a billed cost (OpenRouter `usage.cost`) above the token cost. The web plugin adds $0.01 per request.\n\n**Record.** `runs/costs.csv` has 18,618 generation calls (Luna 5,675; Sabiá-4 5,674; Sabiazinho-4\n4,308; Terra 2,961). All ended `stop`; none was rejected for tool use or billing.\n\n### 1.2 No explicit \"do not search\" instruction in the prompt\n\n`scripts/rag/prompts/answer_closed_v1.pt.md` says to answer \"com base no seu conhecimento da\nlegislação tributária\" (\"based on your knowledge of the tax legislation\") and that no documents are\ngiven. It does not say \"do not search the internet\". Decision: **leave the prompt as it is.**\n\n- The instruction would have no effect: the model has no tool to call.\n- Changing the prompt would mean a new version (`answer_closed_v2`) and regenerating and rescoring\n 4 × 715 closed-book answers, or else the new answers would not be comparable with the existing ones.\n The cost would be small, but the change would buy nothing.\n- If a future prompt revision happens for other reasons, add the sentence then. It documents the\n intent for readers of the prompt.\n\n### 1.3 What \"parametric knowledge\" includes, and the limits to state in the paper\n\n- **Provider self-reporting.** The request guard and the billing check are under our control. The\n reply checks rely on each provider reporting its tool use. For Maritaca, the guarantee is that the\n requests never list tools, plus its own usage report. That is strong, but not independent proof.\n- **The P&R itself is probably in the training data.** The P&R 2024 is public (May 2024). The GPT-5.6\n cutoff is 2026-02-16; Maritaca publishes none. Closed-book scores therefore mix legal knowledge with\n possible memorisation of the gold answers (grounding note §4.2, item 6).\n- **Later years leak in.** Models know rules and acts from after the reference date (exercise 2024,\n calendar year 2023). The value checks of phase 5 catch values from later years. This plan adds the\n same check for cited acts (§3.5).\n\nSuggested wording for the paper: *\"In the closed-book condition no documents were provided; tools and\nweb search were disabled at the API level and every response was verified to contain no tool use, so\nthe answers reflect the models' parametric knowledge (which may include the public Q&A document\nitself).\"*\n\n## 2. Questions this plan answers\n\n1. **Closed book:** when a model cites a provision from memory, is it the provision the P&R cites?\n This is the per-generator recall and precision at the document, article and provision levels.\n2. **Validity:** how often does a model cite an act or article that does not exist (in the corpus),\n or one from after the reference date, or a revoked act (RIR/1999)?\n3. **RAG answers:** do the in-text citations agree with the sources each claim links to? How often do\n they name a provision that is not in the context at all, so it comes from the model's own\n knowledge?\n4. **Link with answer quality:** do answers that cite the right provision score higher (V_strict)?\n\n## 3. Method\n\n### 3.1 Input\n\n- Closed book: `runs/answers/jua-4b-mixed/irpf/answer_closed_v1/<llm>/closed_book/answers.jsonl`,\n 4 generators × 715 questions. These don't depend on the embedding: no retrieval.\n- RAG: the 25 trimmed-grid runs and the gemini-emb-2 runs. The headline runs are `S1_budget4000`,\n `S2_budget4000` and `oracle_budget4000`.\n- Each answer line has `claims` (list of `{texto, fundamentos}`). The claim text is the unit of\n extraction, so each citation is tied to a claim and to that claim's sources.\n- Gold: `dataset/references.jsonl` through `ragpipe.relevance.gold_items` (596 questions with legal\n references). The other 119 questions get only the validity checks (§3.5).\n\n### 3.2 Extraction of provision chains\n\n`scripts/dataset/citations.py` already handles the P&R citation style:\n- `find_chains()` finds the chains of provision tokens;\n- `chain_units()` turns them into nested LexML ids (`art12_par1_inc2`), handling the reverse form\n (\"inciso II do § 1º do art. 162\") and sibling lists (\"art. 26 e parágrafo único\").\n\nGenerator text is close to the P&R's: the prompt asks for \"conforme o art. 8º, inciso II, alínea \"b\",\nda Lei nº 9.250, de 1995\".\n\nExpected gaps, to be checked on a sample before scoring:\n- \"caput\" and \"parágrafo único\" written out;\n- \"art. 8º, II, b\" (bare numerals);\n- \"arts. 1º a 3º\" ranges;\n- citations without an article (\"conforme a Lei nº 9.250, de 1995\"), which are document-level only.\n\n### 3.3 Act resolution (the main work)\n\nEach chain must be attributed to an act, and the act resolved to a `document_id` of\n`dataset/documents.jsonl` (453 documents, 209 statutory). Three resolvers, tried in order:\n\n1. **`lexml-linker`** (`linkertool`, installed locally; run with `LANG=C.UTF-8` and the text on stdin).\n It resolves federal acts with the provision path, including year-only dates and the \"9.250/1995\"\n form:\n - \"art. 39 da Lei nº 11.196, de 2005\" → `urn:lex:br:federal:lei:2005;11196!art39`;\n - \"art. 6º, inciso XIV, da Lei nº 7.713, de 22 de dezembro de 1988\" →\n `…lei:1988-12-22;7713!art6_cpt_inc14`.\n\n It returns **nothing** for Receita Federal acts (\"Instrução Normativa RFB nº 2.179, de 2024\") or for\n \"Regulamento do Imposto sobre a Renda – RIR/2018\". Map the URN to a `document_id` by authority, type,\n number and year (the URNs in `documents.jsonl` have full dates; generators often give only the\n year). The fragment after `!` is a LexML id usable directly.\n2. **Regex resolver for Receita Federal and other acts.** Type + issuing body + number + year, for\n Instrução Normativa (RFB/SRF), Ato Declaratório (Executivo/Interpretativo/Normativo), Solução de\n Consulta (COSIT), Parecer Normativo, Portaria, Nota… These are the `in_`, `ade_`, `adi_`, `sc_`, `pn_`…\n stems of the corpus. Match against the document list by (type, number, year). Then reuse the\n attribution logic of `citations.attribute()` (\"do/da <act>\" binds a chain to the next act mention,\n otherwise to the closest previous one), with the detected acts as `titles`.\n3. **Alias table** for names without a number: RIR/2018 → `decreto_9580_20181122`, RIR/1999 →\n `decreto_3000_19990326`, CTN, Constituição Federal, Lei do IRPF… The table is small, written by hand\n and kept in `scripts/nuggets/` next to the scorer.\n\n**Unresolved acts** are kept with their text, in two categories:\n- `act_not_in_corpus`: well-formed, with a type, number and year, but absent from the corpus. It may\n be real (the P&R never cites it) or invented; this can't be told offline. Sample them by hand, e.g.\n check whether the \"IN RFB nº 2.179, de 2024\" that Sabiá-4 cites exists. The P&R cites IN RFB\n nº 2.178 for that question;\n- `unparsed`: an act mention or chain with no act.\n\nThe resolver's coverage (share of chains attributed to a corpus document) is a reported figure, per\ngenerator.\n\n### 3.4 Scoring against the gold references\n\nFor each answer: the set of cited units at three levels (document; `(document, article)`;\n`(document, LexML id)`). Compare with the question's gold items using the rules of\n`ragpipe/relevance.py`:\n- **document level:** same `document_id`;\n- **article level:** same article in the same file, with the annex rule G3 (`either`), as in the\n retrieval evaluation;\n- **provision level:**\n - full match when the cited unit equals the gold unit or is its ancestor. The answer cites a larger\n unit that contains the gold one, the analogue of G5;\n - partial match when the cited unit is a descendant of the gold unit.\n\nReport the full and partial matches separately, since \"art. 8º\" for a gold \"art. 8º, II, b\" is\nright but coarse.\n\nMetrics per run and level:\n- **cited recall:** the share of gold items the answer cites;\n- **cited precision:** the share of the answer's cited units that match a gold item;\n- **cited@any:** whether the answer cites at least one gold item.\n\nUse the same definitions as `citations_runs.csv`, so closed book, the in-text RAG citations and the\nlinked sources sit in one table. Compute them over answers that cite something, and also over all\nanswers (no citation = zero recall), with the citation rate reported beside them.\n\nCaveat: the gold set is what the P&R cites. A correct provision that the P&R does not cite counts as\nwrong. Precision is a lower bound, as for the linked-source scores.\n\n### 3.5 Validity checks (all 715 questions)\n\n- **Non-existent article.** The act resolves to a corpus document but the article (or unit) id is not\n in its LexML (`lexml/`; the chunk table's `artigo_id` / `unidade_id`). This is a strong hallucination\n signal.\n- **Act outside the corpus** (`act_not_in_corpus`, §3.3), with a manual sample.\n- **After the reference date.** The act is dated after 2024-05 (e.g. the INs that govern the 2025\n return): parametric knowledge from later years, the citation analogue of the phase 5 value checks.\n- **Revoked act.** RIR/1999 (excluded from the main corpus, `scripts/rag/corpus_exclusions.yaml`) or\n other acts revoked before 2024.\n\n### 3.6 RAG answers: in-text citations vs linked sources vs context\n\nFor each claim of a RAG answer, map the resolved in-text citations to chunks of that question's\ncontext: the same document and an article or unit the chunk covers (`cobre_ids` / `artigo_id`).\nThen classify each in-text citation:\n- `in_sources`: it matches one of the claim's own linked sources (`fundamentos` → `cited_chunk_ids`);\n- `in_context_not_sources`: it matches another chunk of the context;\n- `outside_context`: no context chunk holds it. This is parametric knowledge used in a RAG answer, a\n per-citation leakage figure to set beside the nugget-level leakage (phase 5 `utilisation_runs.csv`).\n\nBy strategy: does S2 lower `outside_context` compared with S1, because the cited paragraph is now in\nthe context?\n\n### 3.7 Link with answer quality\n\nPer question, for closed book and for S1/S2 at 4000:\n- V_strict of answers with a correct citation at the article level vs answers with none or only wrong\n ones (paired across generators where possible);\n- a Spearman correlation between cited recall and V_strict.\n\nThis is descriptive: both depend on the question's difficulty.\n\n## 4. Validation\n\n- **Unit tests** for the new pieces: generator-style citation forms, the act regexes, the alias table,\n and the linker-URN → `document_id` mapping. Add them to the existing tests of `citations.py`\n (`scripts/dataset/tests/` if present, otherwise `scripts/nuggets/tests/`).\n- **Manual check** of 100–150 citations, stratified by generator and by closed book vs RAG. For each,\n check the extraction (chain → units), the act attribution and the resolution. Target: ≥ 95%\n correct attribution among resolved citations. Report the error rate in the note.\n- **Sanity check on the oracle runs.** In-text citations of `oracle_budget4000` answers should mostly\n be `in_sources` or `in_context_not_sources`, and their cited precision should come close to the\n linked-source precision (0.77–0.81 at the article level).\n\n## 5. Implementation\n\n- New module `scripts/nuggets/nuggetizer/intext_citations.py`:\n - extraction (`citations.find_chains` / `chain_units`);\n - act detection and resolution (linker via subprocess, batched; regex; alias table);\n - scoring with `ragpipe.relevance.Matcher` / `ProvisionScorer`;\n - context mapping (§3.6).\n- Wired into `nuggets.py analyze` as one more step (no LLM calls), writing to\n `nuggets/scoring/analysis/<gold>/<judge>/<set>/`:\n - `intext_citations.csv.gz` — one row per extracted citation: run, question, claim, raw text,\n act, document_id, unit, resolver, validity flags, match level, §3.6 class;\n - `intext_citations_runs.csv` — per run × level: citation rate, recall, precision, cited@any,\n resolver coverage, invalid / outside-corpus / later-year / revoked shares, §3.6 class shares;\n - `intext_vs_quality.csv` — §3.7.\n- The linker runs once per distinct claim text, with results cached in a gitignored folder. Expect\n tens of thousands of claims; at the linker's speed this should take minutes. Measure it on one run\n first.\n- Results note in `docs/`, then a pointer in `CLAUDE.md` and in `scripts/nuggets/README.md`.\n- Optionally later: an in-text citation panel in the explorer's question trace.\n\n## 6. Steps\n\n1. **Survey** (½ day): extract the claims of the 4 closed-book runs and 2 RAG runs. Run `find_chains`\n and the linker. Count the citation forms that fail, and draft the act regexes and the alias table\n from what generators actually write.\n2. **Resolver + tests** (1 day).\n3. **Scoring + validity + §3.6** (½–1 day). First on closed book and `S1/S2/oracle_budget4000`, then all\n runs.\n4. **Manual check** (§4) and fixes (½ day).\n5. **Results note**, tables, pointer in `CLAUDE.md`.\n\n## 7. Open decisions\n\n1. Whether citations of acts outside the corpus count as wrong in precision (default: yes, reported\n separately so they can be excluded).\n2. Whether a coarse citation (the article, for a gold inciso) counts as correct at the provision level\n (default: full match by the G5 analogy, with the partial/descendant case reported apart).\n3. How far to verify acts outside the corpus: a manual sample only (default), or a lookup in the\n sibling `br-taxqa-document-fetcher` / LexML.\n4. Whether to add the \"do not search\" sentence at the next closed-book prompt revision (§1.2; default:\n only if the prompt changes for another reason).\n","20261122_164407_methodology_additions_plan_token_weighted_citations_sol_and_fix_b.md":"# Plan: methodology additions (token-weighted metric, in-text citations, GPT-6.2 Sol) and the corpus revision\n\nDate: 2026-11-22. Plan note. **Status (2026-11-22):** B done (`docs/20261122_181611_*`); A1 done\n(`docs/20261122_192653_a1_token_weighted_provision_metric_results.md`); A2 done\n(`docs/20261122_194659_a2_in_text_legal_citations_results.md`; manual check 98.3%, stage 3 gate met); A3 done\n(`docs/20261122_205115_a3_gpt_6_2_sol_results.md`; batch route, effort `minimal` since `none` is refused; $18.41);\npending: HF repo B update and dashboards with the Sol runs. It covers four\npieces of work:\n\n- **A1:** a token-weighted provision metric, to measure how much of each strategy's context is noise;\n- **A2:** scoring the legal provisions cited in the answer text (closed book first);\n- **A3:** answer quality and cited provisions of `gpt-6.2-sol`, to test whether it strengthens the trend\n seen with GPT-5.6 Terra;\n- **B:** whether to do the pending corpus revision (fix B) now.\n\n## Summary\n\n**Recommendation: do fix B first, then A1, A2 and A3 on the revised corpus.**\n- Fix B is cheap at this point. Only 0–2 of the 715 contexts per 4k run hold a misparsed chunk or its\n neighbour, plus 1–11 that hold an article to be reviewed for duplication. So at most ≈ 1.5% of the\n answers need regenerating.\n- A1 needs a rerun of the evaluation and a new unit-token table anyway. Building both once, on the\n final corpus, avoids redoing them.\n- Running Sol on the final contexts means its answers never need regenerating.\n- The public release needs fix B regardless.\n- The cost of fix B is time (parser repair, renumbered chunk ids, rebuilding the dashboards), not\n money.\n\n**Costs** (§7). A1 and A2 make no API calls. Fix B ≈ $3–6 across accounts. A3 (Sol: closed book, S1,\nS2 and oracle at 4k, plus scoring) costs ≈ $19–25 at the half-price batch rate, or ≈ $31–42 at list\nprice. **Total ≈ $22–31 with batch, ≈ $35–50 at list price** (all accounts), before a 20% contingency.\n\n**Budget: two blockers before any paid step.**\n1. **The OpenRouter key has expired.** `GET /api/v1/key` on 2026-11-22 returned HTTP 401 \"API key\n expired\". A new key, with a budget cap, is needed.\n2. **Credit left: ≈ $37.3 on the old key's $200 limit.** That is $37.34 after the Gemini comparison on\n 2026-11-08, minus $0.08 of ledger spending since. Whether the account's prepaid credit still covers\n it must be checked with a management key or on the dashboard. At batch prices everything fits in\n ≈ $37 with a small margin. At list price A3 alone nearly uses it up.\n\n**Decisions needed** (§8):\n- D1: the timing of fix B;\n- D2: the Sol endpoint (batch, list price or a direct OpenAI key) and its reasoning setting;\n- D3: Sol's scope (4 conditions, or more);\n- D4: a new OpenRouter key and confirmation of the remaining credit.\n\n## 1. Where things stand\n\n- **Results to extend:** phase 5 (`docs/20261023_210727_rag_phase5_scoring_and_analysis.md`), Gemini\n comparison (`docs/20261108_175117_*`), fix A (`docs/20261115_181838_*`), granularity analysis\n (`docs/20261122_130934_*`), in-text citation plan (`docs/20261122_134404_*`).\n- **The Terra trend** (phase 5 §2–3):\n - Terra answers the P&R questions about as well without retrieval as with it: closed book 0.351\n V_strict, against S1 0.325, S2 0.341 and oracle 0.368. Closed book → S2 is −0.010, p .56.\n - For the smaller or weaker generators, retrieval helps clearly. Closed book → S2: Luna +0.041,\n Sabiá-4 +0.078, Sabiazinho-4 +0.095.\n - What retrieval buys Terra is correctness. Closed-book answers contradict at least one nugget in\n 29.5% of the questions, against 8.0% with S2.\n - Its S1 → S2 gain is the smallest of the GPT models (+0.016, not significant on the primary set).\n\n The hypothesis for A3: a stronger, newer model knows the P&R content better. Retrieval would then\n add even less to recall, or take away from it, while still cutting contradictions.\n\n## 2. Fix B: the corpus revision, now\n\n### 2.1 Scope\n\nThe scope is unchanged from `docs/20261115_172140_gold_matcher_annex_rule_and_misparsed_articles.md`\n§5:\n1. repair the parse of the 6 misparsed documents and confirm the 2 \"to check\" ones;\n2. review the 21 article-level duplicate ids;\n3. add both checks to the article-coverage audit;\n4. re-segment;\n5. re-embed the changed chunks (both embeddings);\n6. rerun retrieval, evaluation and contexts, then regenerate and rescore only the answers whose prompt\n changed;\n7. drop the chunk exclusions that are no longer needed;\n8. release new versions of repos A and B.\n\n### 2.2 Measured impact on the existing runs (2026-11-22)\n\nContexts holding a flagged chunk (§2 of the fix A note) or the chunk next to it, where the moved\nheading or citation text would land; and, separately, contexts holding a chunk of the documents whose\nduplicates must be reviewed (Lei 12.715, Decreto-Lei 58/1937, MP 2.228-1 annex):\n\n| Context set | Flagged ±1 | Duplicate-review documents |\n|---|---:|---:|\n| jua S1 / S2 4k | 2 / 1 | 6 / 11 |\n| jua S2c / S3 / S4 4k | 2 / 0 / 1 | 8 / 11 / 8 |\n| jua S1 / S2 2k | 1 / 1 | 3 / 7 |\n| jua S1 / S2 8k | 10 / 7 | 14 / 19 |\n| gemini S1 / S2 4k | 2 / 1 | 1 / 2 |\n\n- **Upper bound:** ≈ 15 contexts per 4k set and ≈ 30 per 8k set change, out of 715. Only the contexts\n whose rendered text changes produce new requests. All others come from the LLM cache at no cost:\n chunk ids are renumbered, but ids are not in the prompt.\n- **Oracle contexts** change only where a gold article is repaired (Q006 and a few others).\n- **Rankings** of other questions could shift slightly, because changed chunks get new vectors. This\n matters only where a changed chunk crosses a context boundary, and those cases are already in the\n counts above.\n\n### 2.3 Why now\n\n- **It costs about the same now or later**, since later it would also cover Sol's answers in the same\n ≈ 1.5% of contexts. But doing it **after** A1–A3 would change every reported number once more:\n retrieval, nuggets, citations and the token-weighted metric, plus the dashboards and the HF release.\n- **A1 is built on the chunk table and the LexML** (unit token counts, §3.2). Building it on the\n repaired corpus avoids building it twice.\n- **The public release** (moving the HF repos to `unicamp-dl`) is the other trigger for fix B, and the\n additions will have to be released anyway.\n- **Risk:** the parser repair is manual work in a sibling repo, of uncertain size. If it takes longer\n than ≈ 2 days, A1 and A2 (both free) can run on the current corpus, while Sol waits for the repaired\n contexts. Sol is the only paid step that fix B affects.\n\n### 2.4 Fix B steps and costs\n\n| Step | Work | Cost |\n|---|---|---:|\n| B1 | Repair the 6 documents (parser fix or `.docx` repair under `scripts/lexml/`); check the 2 \"to check\" ones and the 21 duplicates against the sources; extend the coverage audit | time (1–2 days) |\n| B2 | Re-parse the affected documents, re-segment all (`segment_all.py`), validate (`validate_segments.py`) | free |\n| B3 | Re-embed changed texts: **gemini-emb-2** (OpenRouter, cents); **jua** (HF Inference Endpoint, TEI, same instance type as the original; ≈ 1 h) | < $0.05 OR; ≈ $1–3 HF |\n| B4 | Parity check: unchanged texts keep their vectors (copied, not re-embedded); re-embed a sample of 20 unchanged texts to confirm the endpoint reproduces them | included |\n| B5 | `rag.py retrieve` + `evaluate` (both embeddings) + `context` | free (minutes) |\n| B6 | Regenerate the answers whose prompt changed: ≤ ≈ 15 per 4k run, ≤ ≈ 30 per 8k run, over the 25 jua runs + 4 Gemini runs + the oracle; dry run first to count them | ≈ $0.5–1.5 (OR + Maritaca) |\n| B7 | Rescore those answers (`nuggets.py score`), context support of the changed contexts (`ctxsupport`), `scoretable`, `analyze` | ≈ $1–2 OR |\n| B8 | Rebuild the dashboard, trace and explorer data; new results note; HF repos A and B (`build_release.py`, `push_release.py`) | free |\n\n**Fix B total ≈ $3–6** (OpenRouter ≈ $2–3.5; Maritaca ≈ $0.5; HF ≈ $1–3).\n\n## 3. A1: token-weighted provision metric (retrieval noise)\n\n### 3.1 What it measures\n\nToday, a chunk that touches a gold unit counts whole:\n- `hit_full` / `hit_any` per gold item;\n- `context_precision` = tokens of the texts that touch any gold unit ÷ context tokens.\n\nSo a 3000-token chapter (S3) or a whole article (S1) that holds a 40-token inciso counts as fully\nrelevant (granularity note §1 and §5). A1 counts only the **gold tokens**.\n\n### 3.2 Building block: token counts per LexML unit\n\nNew table `segmented/unit_tokens.csv.gz`: one row per `(arquivo, unidade_id)` with:\n- `own_tokens`: Qwen3 tokens of the unit's own text, without its children;\n- `subtree_tokens`: the unit with all its children.\n\nThe tokenizer is the same as for `n_tokens_qwen3`, and the text is taken from the LexML with the\nsegmentation's normalisation (`scripts/segmentation/common.py`).\n\nCheck: for each unsplit article, `subtree_tokens(art)` + its prefix (ementa, label) ≈ `n_tokens_qwen3`\nof its ART chunk. Report the deviation.\n\n### 3.3 Overlap of a chunk with a gold unit\n\nFor a chunk `c` and a gold unit `u` (provision level; the article level uses `u = art`):\n- `c` contains `u` (ancestor in `cobre_ids`, or a grouping chunk around it): overlap =\n `subtree_tokens(u)`;\n- `c` holds part of `u` (descendant, or a split-article part): overlap = the sum of `subtree_tokens`\n of the units of `c` that lie inside `u`;\n- otherwise 0.\n\nWithin a context, each gold unit's tokens count once: with merge de-duplication, a unit is never in\ntwo texts. All other tokens are split into two kinds:\n- **scaffold**: ementa, grouping names, article label, ancestor path, and the caput sentence of\n S2c/S4. Computed as the chunk's tokens minus the `own_tokens` of the units it holds;\n- **off-gold content**: everything else.\n\n### 3.4 Metrics\n\nAt the article and provision levels, budget view:\n\n| Metric | Definition | Reads as |\n|---|---|---|\n| `token_recall` | gold tokens in the context ÷ gold tokens of all gold units (per question) | how much of the cited text was delivered; partial credit for S2 fragments and split-article parts |\n| `token_precision` (signal ratio) | gold tokens ÷ context tokens | how much of the context is the cited text |\n| `noise_share` | off-gold content ÷ context tokens | retrieval noise |\n| `scaffold_share` | scaffold ÷ context tokens | the price of self-contained chunks (S2c/S4 caput, S3 headings) |\n| `item_coverage` | per gold item: share of its tokens in the context | a graded `hit_full`; the mean over items is `token_recall` macro-averaged |\n\nThese are added to `metrics.csv` and `per_item.csv.gz` under a **new evaluation id**, e.g.\n`v3_either_containment_merge_skip`. The other metrics are unchanged.\n\n### 3.5 Analyses\n\n1. Noise and signal by strategy × budget × level. Expected: S1 and S3 have high noise; S2 the\n highest signal ratio. S2c/S4 show the cost of their scaffold.\n2. Does token precision explain answer quality or utilisation better than the binary hit?\n Per-question Spearman with V_strict and with utilisation (phase 5 `utilisation_runs.csv`), the same\n design as granularity note §4.\n3. Rerun the whole-article vs sub-article split (granularity note §3) with `item_coverage` in place of\n `hit_full`.\n\n### 3.6 Implementation and cost\n\n- `scripts/segmentation/`: the unit-token builder, run after segmentation.\n- `ragpipe/relevance.py`: per-match token overlaps.\n- `ragpipe/evaluation.py`: the new columns.\n- `ragpipe/metrics.py`: the aggregates.\n- Tests on the conftest corpus.\n- Results note and the dashboard's retrieval tab.\n\n**No API calls.** About 1.5–2 days.\n\n## 4. A2: in-text legal citations (closed book first)\n\nFollow `docs/20261122_134404_in_text_legal_citation_scoring_plan.md`:\n- extraction with `citations.py`;\n- act resolution with `lexml-linker` + a regex resolver for Receita Federal acts + an alias table;\n- scoring at the three levels;\n- validity checks (non-existent article, act outside the corpus, after 2024-05, revoked);\n- for RAG answers, in-text citations vs linked sources vs context.\n\nTwo changes for this plan:\n- **Order:** closed book of the 4 current generators first; then S1/S2/oracle 4k; then Sol (A3), which\n gets the same tables at no extra work.\n- **Sol is the most interesting case:** a later knowledge cutoff makes citations of acts from after\n the reference date more likely (e.g. the INs of the 2025 or 2026 returns). The validity check of\n plan §3.5 is the direct test.\n\n**No API calls.** About 2–3 days.\n\n## 5. A3: GPT-6.2 Sol\n\n### 5.1 The model and its endpoints (OpenRouter catalogue, 2026-11-22)\n\n- `openai/gpt-6.2-sol`: created 2026-11-17; context 1.05 M tokens. Knowledge cutoff not in the\n catalogue (probe it, record it in `llms.yaml`).\n- Endpoints:\n - `openai`, `azure` and `amazon-bedrock` at **$2 / $10 per M tokens** (input / output; cached input\n $0.10);\n - `openai/fast` and `openai/ultrafast` at 2× and 3× that.\n- **No `openai/flex` endpoint**, unlike Terra and Luna (flex is half price).\n- The half-price option is the **`openai/gpt-6.2-sol:batch`** model id: **$1 / $5**, served by\n `openai`. How OpenRouter runs `:batch` (synchronous with a delay, or an asynchronous job) has to be\n probed. Our client's batch support (`llm_client/batch.py`) covers the OpenAI and Gemini batch APIs\n directly, not OpenRouter's.\n- For comparison, Terra is $2 / $12 list, $1 / $6 flex. Per token, Sol costs about the same as Terra.\n\n### 5.2 Design: comparable with Terra\n\n- **Same conditions as Terra:**\n - closed book (`answer_closed_v1`);\n - S1 4k and S2 4k (`answer_v1`, jua contexts);\n - oracle 4k (596 questions with gold).\n\n 715 questions each. These are exactly Terra's four full runs.\n- **Same request shape:**\n - `json_schema` output, `max_tokens 4000`;\n - one pinned upstream (`only: [openai]` or the `:batch` route), `allow_fallbacks: false`,\n `require_parameters: true`, `data_collection: deny`;\n - the same tool and web-search guard (citation plan §1.1).\n- **Reasoning:** Terra ran with effort `none`. Sol lists `reasoning_effort`. Probe whether `none` is\n accepted:\n - if it is, use it (comparable);\n - if the minimum is `minimal` or `low`, record it and report the reasoning tokens. That is a\n confound to state, since the trend could come partly from reasoning.\n- **Optional, cheap controls:**\n - `wrong-S2_budget4000` on `stratified_30` (≈ $0.2): checks that Sol reads the context;\n - Sol S2 with gemini-emb-2 contexts (≈ $5): only if D3 asks for it.\n- **Confound to state:** Sol differs from Terra in both generation (6.2 vs 5.6) and tier (Sol vs\n Terra). The catalogue has `gpt-6.1-terra` but no `gpt-6.2-terra`, so the two cannot be fully\n separated. An optional `gpt-6.1-terra` closed book + S2 run (≈ $4–6 at $1 / $5 list) would separate\n most of it.\n\n### 5.3 Hypotheses and analyses\n\nRun on the primary nugget set, judge Gemini 3.8 Flash, as in phase 5.\n\n- **H1, retrieval adds less recall:** closed book → S2 for Sol ≤ Terra's −0.010. Test the\n difference-in-differences (Sol − Terra) × (S2 − closed book), paired by question, with bootstrap CI\n and permutation p.\n- **H2, retrieval still buys correctness:** the contradiction rate drops from closed book to S2 for\n Sol, as for Terra (29.5% → 8.0%).\n- **H3, more own knowledge used inside RAG answers:**\n - higher leakage, P(answer support | context not support);\n - more \"answer support not in context\" (phase 5 §5, `utilisation_runs.csv`);\n - more in-text citations outside the context (A2 §3.6).\n- **H4, closed-book citations are more accurate, and more often from later years:** A2 cited\n recall/precision against the gold references, and the after-reference-date share. Sol vs Terra vs\n the others.\n- **H5, S1 → S2 gain smaller than Terra's** (+0.016).\n\nAlso report: Sol vs Terra per condition (paired), the values checks, abstention and answer length.\n`analyze` runs as is once the runs are registered.\n\n### 5.4 Steps\n\n1. **Probe (≈ $0.05):**\n - check that `reasoning: none`, `response_format: json_schema` and `require_parameters` are accepted\n on the chosen endpoint;\n - see how `:batch` behaves;\n - check `served_provider` and the billed cost per call;\n - record the knowledge cutoff the model states (as information only).\n2. **Registry entry** `gpt-6.2-sol` in `scripts/rag/llms.yaml` (price, routing, cutoff), plus an\n experiment file `scripts/rag/experiments/sol.yaml` (4 conditions; prompts as in `full_stage1.yaml`).\n3. **Pilot on `stratified_30`** (≈ $0.7): measure input and output tokens per answer to replace the\n assumptions in §7, read some answers, stop if the cost is off by more than 30%.\n4. **Full generation** (`rag.py run --budget`), with the ledger reviewed after each condition.\n5. **Scoring:** `nuggets.py score` (4 runs), `scoretable`, `analyze`; with the pilot, `stratified_30`\n tables too. No `ctxsupport` is needed: the contexts are shared with the other generators.\n6. **Results note,** HF repo B update, dashboard and explorer rebuild.\n\n## 6. Order and gates\n\n| Stage | Content | Paid | Gate before the next stage |\n|---|---|---|---|\n| 0 | New OpenRouter key with a cap; confirm the account credit; D1–D3 answered | — | user |\n| 1 | Fix B (B1–B8) | ≈ $3–6 | results note; numbers that moved are listed; the user reviews |\n| 2 | A1 on the revised corpus | free | noise tables look sane (unit-token check < 5% deviation) |\n| 3 | A2 on closed book of the 4 generators, then their RAG runs | free | manual check of 100–150 citations ≥ 95% correct attribution |\n| 4 | A3 probe + pilot | ≈ $0.8 | per-answer cost within 30% of §7 |\n| 5 | A3 full generation + scoring + A2 for Sol | ≈ $19–41 | ledger within the cap; stop and report on an overrun (CLAUDE.md) |\n| 6 | Analyses (H1–H5, A1 × quality), note, HF release, dashboards | free | — |\n\nStages 2–3 can start before stage 1 ends if the parser repair drags (§2.3). Then only their final\nnumbers are recomputed after fix B, at no cost.\n\n## 7. Cost estimate\n\n### 7.1 A3 (Sol), from Terra's measured tokens\n\nTerra's ledger: mean input / output tokens per answer were closed book 421 / 296, S1 4k 3,715 / 404,\nS2 4k 3,768 / 403, oracle 4k 2,526 / 402.\n\n- **Input:** 7.15 M tokens over the 4 conditions (715 + 715 + 715 + 592 answers).\n- **Output:** 1.03 M tokens at Terra's length. Sol is assumed to write 1× to 2× as much:\n 1.03–2.06 M tokens.\n\n| Item | Batch ($1 / $5) | List ($2 / $10) |\n|---|---:|---:|\n| Input 7.15 M | $7.2 | $14.3 |\n| Output 1.03–2.06 M | $5.2–10.3 | $10.3–20.6 |\n| Generation | **$12.4–17.5** | **$24.6–34.9** |\n| + if the minimum reasoning effort is not `none` (≈ 500 reasoning tokens/answer, 1.37 M) | +$6.8 | +$13.7 |\n| Scoring, 2,737 answers × $0.0023 (phase 5 rate, Flash flex) | $6.3 | $6.3 |\n| Probe + pilot | $0.4 | $0.8 |\n| **A3 total (without reasoning)** | **≈ $19–24** | **≈ $32–42** |\n\nOptional: wrong context $0.2; Sol S2 with gemini contexts ≈ $5–7; `gpt-6.1-terra` closed book + S2\n≈ $4–6 plus scoring $3.3.\n\n### 7.2 Everything\n\n| Work | OpenRouter | Maritaca (BRL billing) | HF endpoint |\n|---|---:|---:|---:|\n| Fix B | $2–3.5 | ≈ $0.5 | $1–3 |\n| A1 token-weighted metric | $0 | — | — |\n| A2 in-text citations | $0 | — | — |\n| A3 Sol (batch / list) | $19–24 / $32–42 | — | — |\n| **Total** | **$21–28 / $34–46** | **≈ $0.5** | **$1–3** |\n| + 20% contingency | $25–33 / $41–55 | | |\n\n### 7.3 Does it fit?\n\n- **OpenRouter:** ≈ $37.3 left on the old key's limit (estimate; the key has expired).\n - **Batch route:** everything fits, contingency included ($25–33).\n - **List route:** fits only without contingency and without reasoning tokens, and not with the\n optional runs.\n\n If batch is not usable, the options are: raise the limit (if the account has the credit), use a\n direct OpenAI key with the Batch API (`llm_client/batch.py` supports it; `OPENAI_API_KEY` is not in\n this machine's `.env`), or drop the oracle condition (≈ −$5–8 at list price, scoring included) and keep closed book,\n S1 and S2.\n- **Maritaca and HF** are billed separately; their amounts are small.\n\n## 8. Open decisions\n\n| # | Decision | Proposal |\n|---|---|---|\n| D1 | Timing of fix B | **Now, before A3** (§2.3); A1/A2 may start in parallel |\n| D2 | Sol route and reasoning | `:batch` if the probe shows it works with our client and honours the parameters; else list price on `openai` with a cap. Effort `none` if accepted, else the lowest, reported as a confound |\n| D3 | Sol scope | The 4 Terra conditions (closed book, S1, S2, oracle 4k); optional wrong-context control ($0.2); no Gemini-context or `gpt-6.1-terra` runs unless asked |\n| D4 | Key and credit | User: create a new OpenRouter key (cap ≈ $40), confirm the account credit, add the key to `.env` |\n| D5 | A1 evaluation id | New id `v3_either_containment_merge_skip`; keep the old ones for provenance |\n| D6 | A2 defaults | As in the citation plan §7 (acts outside the corpus count as wrong but are reported apart; coarse citations are full matches at the provision level) |\n","20261122_181611_fix_b_corpus_revision_results.md":"# Fix B (corpus revision): execution and results\n\n**Generated:** 2026-11-22 18:16:11 (local time, from `date +%Y%m%d_%H%M%S`).\n**Plan:** `20261122_164407_methodology_additions_plan_token_weighted_citations_sol_and_fix_b.md` §2 (stage 1 of §6),\nscope from `20261115_172140_gold_matcher_annex_rule_and_misparsed_articles.md` §5. Executed on the user's request of\n2026-11-22, with a new OpenRouter key (limit $37.30).\n**Status:** **done** (B1–B8). The user reviewed this note on 2026-11-22. After the review:\n- commits pushed: parser `d6e2549` (branch `extensions`) and this repo `bdbdbad` (+ the release record);\n- HF repo A `eduseiti/BR-TaxQA-R` → `5886f9a`, repo B `eduseiti/BR-TaxQA-R-RAG-eval` → `4ea3a09` (§8).\n\n**Cost:** **$0.98 on OpenRouter** (key usage; $36.32 left), plus Maritaca (direct, BRL; $0.28 at list price) and the\nHF endpoint (≈ 4 min up, ≈ $0.05; the ledger books the conservative $0.44 idle-tail estimate). Under the plan's\n$3–6.\n\n| Step | Calls | List | Billed | Ledger |\n|---|---:|---:|---:|---|\n| Embeddings, gemini-emb-2 (377 texts) | 8 | $0.020 | $0.020 | `embeddings/costs.csv` |\n| Embeddings, jua (377 texts) + reproducibility check | 6 + 3 | — | ≈ $0.05 (ledger $0.44 est.) | `embeddings/costs.csv` |\n| Generation, OpenRouter (Luna, Terra) | 53 | $0.247 | $0.141 | `runs/costs.csv` |\n| Generation, Maritaca (Sabiá-4, Sabiazinho-4) | 68 | $0.280 | (BRL) | `runs/costs.csv` |\n| Judge (Gemini 3.8 Flash 217, Gemini 3.1 Pro 10) | 227 | $1.635 | $0.818 | `nuggets/scoring/costs.csv` |\n\n**Backup** of every output before the revision: `../br-taxqa-r_fixB_backup_20261122/` (outside the repo, 2.9 GB):\n`segmented/`, `dataset/`, `runs/` (without the LLM cache), `nuggets/scoring/` (without the cache), both embedding\nstores, and the 2026-10-09 chunk file (`chunks_all_20261008.csv.gz`).\n\n## 1. Summary\n\n- **The 6 misparses are gone.** Two causes, two fixes:\n - **A parser rule** (sibling repo `../lexml-parser-projeto-lei`, `rotuloParser.scala`). A line `Art. N` followed by\n a citation is not an article label. \"Followed by a citation\" means a `;`, a comma before citation words\n (`art.`, `inciso`, `§`, `caput`, …), or \"da/do Lei / Decreto / Medida Provisória / Constituição\". This repairs\n RIR/2018 annex `#2754`, Lei 12.350 `#179`, Portaria Conj. 74 `#23`, Circular BC 3.432 `#30`, IN RFB 1.131 art.\n 31 (2nd instance) and the three \"Art. 33, inciso I:\" headings of the MP 2.228-1 annex.\n - **A `.docx` repair** (`scripts/lexml/repair_docx.py`) where the source itself is wrong:\n - **DL 5.844:** the second \"Art. 93\" is a typo for art. 98 (it sits between arts. 97 and 99, and art. 100 cites\n \"arts. 97 e 98\");\n - **Lei 12.715:** the fetched page holds arts. 69–78 twice; the first copy is garbled and was deleted.\n- **Found by the new audit checks, and fixed too:**\n - **`Art . 1º`** (space before the dot) was not read as an article. Decreto 71.733 lost 37 of its articles this\n way, and Decretos 57.942, 85.306, 87.563 and Lei 4.886 (art. 49) a few each. In Decreto 57.942 the cited treaty\n arts. 1 and 10 (Q152, Q153) now exist and are matchable. They are no longer in `unmatchable_articles.tsv`.\n - **Decreto 85.306:** once the decree's own `Art . 1º/2º` were read, the attached Protocol (printed after the\n signatures) was taken as signature lines. The implicit-annex rule now also knows treaty headings (protocolo,\n acordo, convenção, tratado), so the Protocol is `decreto_85306_19801030.anexo1.xml`, with the same article ids as\n before (art2–art18; Q156 cites art. 7). Decreto 87.563's treaty also becomes an annex (generic: its \"ARTIGO\n I…XXV\" are still not read as articles, so its cited art. 15 stays unmatchable).\n- **The \"to check\" cases and the 21 duplicates** were checked against the sources (§2.3). Except Lei 12.715 (above),\n every duplicate is in the source text. They are listed with their reasons in\n `scripts/lexml/reviewed_duplicate_articles.tsv`.\n- **Effect on the results: negligible.**\n - Retrieval recall at 4k: unchanged at article and provision level, −0.001 at document level (Gemini).\n - Answers: 121 new generation calls, out of ≈ 23,000 answers in all runs.\n - Run-level V_strict: |Δ| ≤ 0.0034 on every full run.\n - The headline comparisons (S1 vs S2, closed book vs S2) keep their significance. Two borderline comparisons\n flip on secondary metrics (§5).\n\n## 2. B1: corpus repair\n\n### 2.1 Parser change (`../lexml-parser-projeto-lei`, uncommitted on top of `4c85e81`)\n\n| File | Change |\n|---|---|\n| `rotulo/rotuloParser.scala` | `artigo`: `not(citacaoAposArtigo)` after the label (see §1); `opt(\" .\")` so `Art . 1º` is a label |\n| `ProjetoLei.scala` | `anexoHeadingKeywordRe` += `protocolo`, `acordo`, `conven[cç][aã]o`, `tratado` (implicit annex after the signatures) |\n| `rotulo/RotuloParserTest.scala` | `citacaoNaoEArtigo`: the 5 citation lines are not labels; real labels still are, including `Art. 2º-A. Da base…`, `Art. 10. Do valor…`, `Art . 1º`, `Art 15.`, `Art. 76, Feita…` (DL 5.844's comma typo) |\n\nThe parser's test suite passes: **42 tests**, 41 before.\n\nA first version rejected any comma after the number. In DL 5.844 that dropped arts. 76, 121 and 205 (\"Art. 76,\nFeita a revisão…\"), and the audit caught it. The comma rule now needs a citation word after the comma.\n\n### 2.2 Re-parse\n\n- **Command:** the same driver as the 2026-10-09 parse (`batch_parse.py --no-justificativa --linker …`), into a\n scratch folder. 209 converted, 0 failed, 388 XML files (+2 annexes). Provenance is in\n `lexml/articulados/PARSER_VERSION`.\n- **Compared with the committed LexML** (text and structure, ignoring links). **Exactly the 14 targeted files\n change** (12 changed, 2 new annexes). The other **54 files differ only in linker output**: `Remissao`/`span`\n links, link comments, `Alteracao/@xml:base`. The linker does not reproduce the committed links (as already seen\n in 2026-10, rebuild note §5.3), so **only the 14 files were installed**, and the 54 keep their committed links.\n- **Source-word coverage** (`.docx` words found in the XML) is the same as before for every changed document; the\n Lei 12.715 text is measured against the repaired `.docx`.\n\n| File | Articles (top level) | What changed |\n|---|---|---|\n| `decreto_9580_20181122.anexo1` | 1050 → 1049 | the citation line before art. 211 is plain text (inside CAPÍTULO II) |\n| `lei_12350_20101220` | 68 → 67 | the CAPÍTULO II title fragment is plain text |\n| `port_conj_tse_srf_74_20060110` | 6 → 5 | the \"Art. 81 … revogado\" note is part of art. 4º, parágrafo único |\n| `circ_bc_3432_20090203` | 43 → 42 | the wrapped \"art. 16 da Lei nº 11.795…\" line is part of art. 7º |\n| `in_rfb_1131_20110221` | 86 → 85 | the wrapped \"art. 31;\" line is part of art. 34, I |\n| `decreto_lei_5844_19430923` | 208 → 208 | `art93` (2nd) → `art98` (.docx repair) |\n| `lei_12715_20120917` | 93 → 83 | the garbled copy of arts. 69–78 is gone (.docx repair) |\n| `mp_2228-1_20010906.anexo1` | 3 → 0 | the three \"Art. 33, inciso I/II/III:\" table headings are text |\n| `decreto_71733_19730118` | 19 → 56 | `Art . N` articles read (with the superseded wordings the source prints) |\n| `decreto_57942_19660310` | 0 → 15 | the treaty's `Art . N` articles read; cited art. 1 and art. 10 exist |\n| `decreto_85306_19801030` (+ `.anexo1`) | 17 → 2 + 17 | decree arts. 1–2; the Protocol becomes annex 1 (art2–art18) |\n| `decreto_87563_19820913` (+ `.anexo1`) | 0 → 2 + 0 | decree arts. 1–2; the treaty becomes a generic annex |\n| `lei_4886_19651209` | 48 → 49 | art. 49 (`Art . 49.`) |\n\nThe RIR/2018 citation line stays a loose paragraph of the chapter. It is not prefixed to art. 211, as the other\nRIR article rubrics are (e.g. art. 212). The text is kept, and the difference is only layout.\n\n### 2.3 The \"to check\" cases and the article-level duplicates\n\n| Case | Verdict |\n|---|---|\n| MP 497 art. 31 (two wordings) | source: the original and the later MP's wording, both printed unstruck |\n| Decreto 71.733 art. 2 \"out of sequence\" | source: two wordings of art. 2 (the first was `Art . 2º`, unread before) |\n| Lei 12.715 arts. 69–78 | **fetch error**: a garbled first copy (removed, §1) |\n| Decreto-Lei 58/1937 arts. 1º–4º | source: the \"Disposições transitórias\" number their own arts. 1º–4º |\n| MP 2.228-1 annex art. 33 (×3) | misparse of \"Art. 33, inciso I:\" table headings (parser fix) |\n| Circular BC 3.432 art. 16 | misparse (parser fix) |\n| Decreto 71.733 art. 22 (and 23, 27, 28, 37) | source: compiled text with superseded wordings unstruck |\n| Decreto 70.951 arts. 15, 21, 23, 32, 35, 40, 48, 79 | source: superseded wordings unstruck (found by the new check; uncited) |\n\nDecretos 70.951 and 71.733 and MP 497 break rule D5 (\"each article once, in its 2023 wording\"): they keep\nsuperseded wordings. All three are uncited, or cited only at document level (Decreto 71.733), so removing the old\nwordings is left for later.\n\n### 2.4 Audit checks (`scripts/lexml/audit_article_coverage.py`)\n\n- **New column \"out of sequence\":** an article whose number breaks the sequence of its neighbours (which are 1–2\n apart).\n- **Duplicate XML ids:** compared with the new `reviewed_duplicate_articles.tsv`; unreviewed ones are marked\n **new**.\n- Both are warnings; the cited-missing gate is unchanged.\n- **Before the repair:** 6 out of sequence and 32 unreviewed duplicates (all the misparses of §2 of the fix A\n note).\n- **After:** **0 out of sequence, 0 unreviewed duplicates, gate OK.**\n\n## 3. B2: segmentation, dataset\n\n- **Segmentation:** `segment_all.py --jobs 16 --overwrite --allow-count-change --variants caput --frozen <2026-10-09\n chunks> --frozen-lexml-rev HEAD`. **Validation OK on all 14 checks.**\n - `diff_vs_frozen`: 612 files with unchanged LexML; 92,112 rows compared; **0 differ**.\n- **`chunks_all.csv.gz`:** 104,574 → **104,625 rows**, SHA-256 `21bf98e5…910a`. Only the 15 changed files have\n different rows: 377 new texts, 308 gone.\n - **Chunk ids are renumbered inside those files**: `decreto_9580_20181122.anexo1#2754` is now the real art. 211.\n - Rows with `id_ambiguo = 1`: 1,415 → 1,343.\n- **`strategies.yaml`** `expected_rows`: S1 21,514; S2/S2c 73,173; S3/S4 77,135.\n- **Dataset** (`build_v2_dataset.py`):\n - Q152 (art. 10) and Q153 (art. 1) of Decreto 57.942 become matchable;\n - cited article ids found: 1,464 + 575 (annex) → 1,465 + 576;\n - `provisions.missing` 13 → 11.\n - `documents.jsonl` lists the two new annex files. Nothing else changes.\n\n## 4. B3–B5: embeddings, retrieval, evaluation, contexts\n\n- **Embeddings** (`embed.py corpus --extend`): 101,635 of 102,012 texts reused, **377 embedded** with each model.\n- **B4, reproducibility:** 20 random unchanged texts were re-embedded on the live endpoints and compared with the\n stored vectors. The cosine is min **0.999991** for jua and **1.000000** for Gemini (script in the session\n scratchpad).\n - The jua `parity` command could not run: `parity_sample.json` dates from the 2026-09 corpus, and 5 of its ids no\n longer exist. Rebuilding the sample needs CPU reference vectors of the 4B model; this check replaces it.\n - The jua endpoint was paused again.\n- **Chunk exclusions (B7 of the plan, done here, before retrieval):** the `chunks:` list of\n `scripts/rag/corpus_exclusions.yaml` is now empty. The 4 misparses no longer exist, and their old ids now name\n other chunks.\n- **Retrieval:** `retrieve --force` for jua `irpf`, Gemini `irpf` and jua `irpf_with_rir1999` (`--exclusions\n none`).\n- **Evaluation:** the same evaluations as fix A, with **identical parameters** (checked against the old\n manifests): main `either_containment_merge_skip` and `v2d` for both embeddings, Gemini's `v2c` and\n `either_containment_skip`, and `irpf_with_rir1999`.\n\n**Recall at a 4k budget, all gold (main evaluation; \"=\" means |Δ| < 0.0005):**\n\n| Level | jua S1 | S2 | S2c | S3 | S4 | Gemini S1 | S2 | S2c | S3 | S4 |\n|---|---|---|---|---|---|---|---|---|---|---|\n| document | 0.621 (=) | 0.700 (=) | 0.686 (=) | 0.691 (=) | 0.680 (=) | 0.598 → 0.597 | 0.682 → 0.681 | 0.664 → 0.663 | 0.671 → 0.670 | 0.660 → 0.659 |\n| article | 0.398 (=) | 0.503 (=) | 0.480 (=) | 0.507 (=) | 0.487 (=) | 0.413 (=) | 0.515 (=) | 0.511 (=) | 0.517 (=) | 0.517 (=) |\n| provision | 0.369 (=) | 0.420 (=) | 0.417 (=) | 0.429 (=) | 0.427 (=) | 0.380 (=) | 0.435 (=) | 0.438 (=) | 0.454 (=) | 0.454 (=) |\n\n- Over all of `metrics.csv` (every view, cutoff and slice): 3,036 rows (jua) and 3,039 rows (Gemini) of 11,255\n move. Recall moves by at most ±0.009 (unit view), and by at most 0.003 in the budget view.\n- **Reachability** (`reachability.csv`):\n - article items reachable 1,944 → **1,946** (Decreto 57.942 arts. 1 and 10);\n - `article_not_in_lexml` 13 → 11;\n - `only_ambiguous_matches` 1 → **0**: Q006's RIR art. 1º no longer has a misparsed twin.\n\n**Contexts:** the same 13 jua sets, S2 4k `context_v1`, Gemini S1/S2 4k, and the 13 `irpf_with_rir1999` sets.\nQuestions whose **rendered context text** changed, per set:\n\n| Set | jua `irpf` | Gemini |\n|---|---|---|\n| S1 2k / 4k / 8k | 5 / 7 / 12 | – / 5 / – |\n| S2 2k / 4k / 8k | 2 / 6 / 12 | – / 4 / – |\n| S2c / S3 / S4 4k | 7 / 5 / 6 | |\n| oracle 4k / 16k | 5 / 10 | |\n| wrong-S2 4k | 7 (with pinned donors, below) | |\n| closed book | 0 | |\n\nThe changed questions are mostly the same few: Q155/156 (Decreto 85.306), Q152/153 (Decreto 57.942), and Q163, 193,\n217, 288, 441, 451. **≈ 1% of the contexts**, as the plan estimated (§2.2).\n\n### 4.1 Wrong-context donors: a new option, `--donors-from`\n\n- **The problem:** the donor draw (`contexts.donors`) is one seeded sequence over all questions. A change in a few\n questions' contexts or gold shifts every later draw, and the first rebuild gave **342 of 715 questions a new\n donor** for a reason unrelated to the control.\n- **The new option** (`rag.py context --donors-from`, `ragpipe.contexts.pinned_donors`) keeps the earlier donors\n wherever they still meet the strict rule, and draws only for the others. The earlier maps are saved in\n `scripts/rag/donors/`.\n- **Result:** 1 donor re-drawn per run (Q267 in `irpf`, Q209 in `irpf_with_rir1999`; their old donors' contexts now\n hold a gold document of theirs), and 6 more contexts change because the donor's context changed.\n- **None of these 7 is in `stratified_30`**, so the wrong-context answers are unchanged.\n- The manifest records `donors_from` and `donors_redrawn`.\n\n## 5. B6–B7: answers and judge\n\n- **Generation:** `rag.py run --budget 74.54 --force` on `full_stage1`, `full_stage2`, `gemini_core`, `pilot` and\n `fixA_oracle` (dry runs first).\n - **121 new calls**, all finish `stop`; everything else came from the cache.\n - Besides the changed contexts, the reruns retried the **6 old errors**, the `max_tokens` failures that fix A had\n left out of scope: Sabiá-4 S2c ×2; Sabiazinho-4 S2 4k, S2c, closed book and pilot `context_v1`, 1 each\n (`errors` column of `runs.csv`). **Every answer run now has 0 errors.**\n- **Stale labels:** `nuggets.py score` / `ctxsupport` keep existing labels without checking that the answer or the\n context is the same. The new `scripts/nuggets/drop_stale_labels.py --backup <backup>` compares every answer run\n and context set with the backup, and removes the labels of the changed questions from every nugget set and judge.\n It removed **240 labels**.\n- **Rescoring:** each set × judge × sample group of existing folders was rerun with its own sample:\n - gold set: Flash `all`, Flash `stratified_30`, Pro `stratified_70`;\n - cross-sets: `gemini-3.1-pro.rep0` and `qwen3.8-max.rep0` (Flash);\n - `ctxsupport`: Flash `all`, `stratified_30` and `stratified_70`, and Pro `stratified_70`.\n\n 227 calls, **0 failed**. Then `scoretable` (gold, both cross-sets, `stratified_30`) and `analyze`.\n\n**`runs.csv`, gold set, Gemini 3.8 Flash, all.** Every run of 596 or more questions with |ΔV_strict| ≥ 0.001:\n\n| Run | V_strict before → after |\n|---|---|\n| Luna S1 4k / S2 4k | 0.2713 → 0.2706 / 0.2993 → 0.2995 |\n| Luna S1 4k @gemini / S2 4k @gemini | 0.2961 → 0.2948 / 0.3266 → 0.3252 |\n| Luna oracle 4k | 0.3393 → 0.3359 |\n| Terra S2 4k / oracle 4k | 0.3410 → 0.3423 / 0.3679 → 0.3662 |\n| Sabiá-4 S3 / S4 / oracle 4k | 0.3147 → 0.3161 / 0.3075 → 0.3089 / 0.3185 → 0.3201 |\n| Sabiazinho-4 S2 4k / oracle 4k | 0.2722 → 0.2736 / 0.2915 → 0.2932 |\n\n- Pilot runs (25–30 questions): only Terra oracle 16k moves, 0.4027 → 0.4127 (25 questions).\n- Closed book: V_strict unchanged for all four generators.\n\n**`comparisons.csv`:**\n- 172 of 378 comparisons move, by at most |Δ diff| 0.017.\n- Headline pairs, V_strict:\n - S1 → S2 4k: Luna +0.028 → +0.029 (p .007 → .005); Terra +0.016 → +0.018 (p .11 → .08, still not\n significant); Sabiá-4 unchanged; Sabiazinho-4 +0.005 → +0.006;\n - closed book → S2: Luna +0.041; Terra −0.010 → −0.009 (p .55 → .60); Sabiá-4 +0.078; Sabiazinho-4 +0.095 →\n +0.096.\n- **Flips:** two borderline secondary comparisons, both Luna S2 4k vs oracle 4k:\n - A_strict: +0.027 → +0.024, p 0.046 → 0.071;\n - W: CI lower bound 0.002 → 0.000.\n\n## 6. B8: dashboards\n\n- `build_dashboard_data.py`, `build_trace_data.py` and `build_explorer_data.py` were rerun (5.5 min, exit 0).\n- The trace's prompt check verifies 20,258 prompts byte for byte against the rebuilt contexts.\n- Its other checks pass:\n - ranks and budgets of the 59,120 per-item rows;\n - context selection of 7,865 sets;\n - templates unchanged.\n- The trace and explorer data are gitignored. They go to the HF eval repo (`raw/dashboard_trace.tar.gz`) with the\n release.\n\n## 7. Code and data changes (uncommitted)\n\n| Path | Change |\n|---|---|\n| `original/articulados/lei_12715_20120917.docx`, `decreto_lei_5844_19430923.docx` | repaired by `scripts/lexml/repair_docx.py` (new; `--all --check` verifies) |\n| `lexml/articulados/` | 12 files + 2 new annexes, `.err.log`s, `PARSER_VERSION` |\n| `scripts/lexml/audit_article_coverage.py`, `reviewed_duplicate_articles.tsv` (new), `unmatchable_articles.tsv` (−2) | §2.4 |\n| `segmented/`, `dataset/` | §3 |\n| `embeddings/*/corpus/manifest.json`, `embeddings/costs.csv`, `endpoint_meter.jsonl` | §4 |\n| `scripts/rag/corpus_exclusions.yaml` | `chunks: {}` with the history in a comment |\n| `scripts/rag/strategies.yaml` | expected rows |\n| `scripts/rag/ragpipe/contexts.py`, `rag.py`, `scripts/rag/donors/` (new) | `--donors-from` (§4.1) |\n| `scripts/nuggets/drop_stale_labels.py` (new) | §5 |\n| `runs/`, `nuggets/scoring/` | regenerated outputs and ledgers |\n| `../lexml-parser-projeto-lei` | §2.1 (3 files) |\n\nAll test suites pass: rag (46), segmentation (49), dataset (36), parser (42). `pinned_donors` has no unit test of\nits own yet.\n\n## 8. Commits and Hugging Face release (after the review, 2026-11-22)\n\n- **Git:**\n - `../lexml-parser-projeto-lei` `d6e2549` (branch `extensions`);\n - this repo `bdbdbad` (`main`);\n - both pushed to GitHub over HTTPS with the `gh` credential (SSH has no key on this machine).\n - `lexml/articulados/PARSER_VERSION` names the parser commit.\n- **HF build** (`build_release.py`):\n - Card counts updated: 104,625 chunks; 21,514 / 73,173 / 77,135 rows per strategy; 102,012 vectors.\n - Repo A's card gets a short note on the revision, and repo B's file list gets this note.\n - `nuggets/full/cache` and `nuggets/parity_openrouter/cache` are not on this machine and did not change, so\n their archives were downloaded from the Hub and kept (`--keep-raw`). Every other archive was repacked.\n- **Push** (`push_release.py`, after dry runs):\n - **repo A** `eduseiti/BR-TaxQA-R`: 2 new files (the annexes), 25 changed → **`5886f9a`**\n (`5886f9aa4a0a2c5b14aaeb1fff7cca4ce080bab5`);\n - **repo B** `eduseiti/BR-TaxQA-R-RAG-eval`: 1 new file (this note), 419 changed → **`4ea3a09`**\n (`4ea3a09d88204c0a30a7fd434cb0c517a12cb904`).\n - A dry run after the push: both repos in sync.\n - Recorded in `release/hf_release.json`.\n- **Next:** stage 2 of the plan (A1, token-weighted metric) on the revised corpus.\n","20261122_192653_a1_token_weighted_provision_metric_results.md":"# A1: token-weighted provision metric — implementation and results\n\nDate: 2026-11-22. Stage 2 of `docs/20261122_164407_methodology_additions_plan_token_weighted_citations_sol_and_fix_b.md`\n(§3), run on the corpus revised by fix B (`docs/20261122_181611_fix_b_corpus_revision_results.md`). No API calls.\n\n## Summary\n\n- **What was added.**\n - A table of Qwen3 tokens per LexML unit: `segmented/unit_tokens.csv.gz`, 81,179 units in 258 files.\n - A token accounting of every budget-view context against the gold units (`scripts/rag/ragpipe/tokens.py`).\n - Five new metrics at the article and provision levels: `token_recall`, `item_coverage`, `token_precision`,\n `noise_share` and `scaffold_share`. They are written under the new evaluation id\n **`v3_either_containment_merge_skip`** (decision D5), for both embeddings.\n - The old metrics in v3 are identical to `either_containment_merge_skip` (11,255 rows, max |Δ| = 0).\n- **Gate passed.** The unit tokens add up to the article chunks. Over 16,054 unsplit articles, prefix + the\n sum of own tokens deviates from `n_tokens_qwen3` by a median of +0.5% and at most 4.8%. None is above 5%.\n- **The contexts are mostly not the cited text.** At 4k (jua, provision level):\n - only 7–9% of the tokens are gold text;\n - 62–68% are off-gold content;\n - 25–30% are scaffold (title/ementa prefix, ancestor paths, grouping names).\n\n The article level is a little cleaner: 11–13% gold. All shares get worse as the budget grows.\n- **S2 beats S1 on every token measure, but its article-level gain is mostly fragments.**\n - Provision level, 4k: the token-weighted gain is as large as the binary one. Token recall +0.060 vs full-hit\n recall +0.052 (jua), both p < .001.\n - Article level, 4k: binary recall +0.106, but token recall only **+0.008 (p .15)** with jua and +0.017 with\n Gemini. S2 touches many more cited articles than S1, but with a paragraph or an inciso, not the whole text.\n - S2's noise share is 5–6 points lower than S1's. Its scaffold share is 4–5 points higher: more, smaller\n chunks each repeat the prefix.\n- **S3's context-precision advantage was mostly an artefact, as suspected** (granularity note §5, caveat 2).\n - Provision level, S3 − S2: context precision +0.026 at 4k and +0.057 at 16k, but token precision only\n +0.004 and +0.003.\n - S3 has the highest noise share of the S2 family. Its token recall gain is real but small: +0.006 at 4k\n (n.s.), +0.030 at 16k.\n- **The caput variants (S2c/S4) have the cleanest contexts**: token precision +0.005 over S2 and +0.006 over S3\n at 4k (p < .001). The caput sentence they carry is often itself the cited text. They do not add scaffold\n against S2 with jua; with Gemini they add about 2 points.\n- **Token metrics do not track answer quality better than the binary hit.**\n - Per-question Spearman with V_strict, provision level, mean over runs: full-hit recall 0.169,\n `item_coverage` 0.158, `token_recall` 0.149, `token_precision` 0.034. The binary hit stays the best.\n - In the paired S2 − S1 design (granularity note §4) as well: provision full hit 0.122, `item_coverage`\n 0.110, `token_recall` 0.095.\n - Noise does not predict utilisation (ρ ≈ 0.01). Neither does token precision once recall is controlled\n for (partial ρ −0.01).\n- **Whole-article questions** (granularity note §3): with graded coverage, S1's lead over S2 shrinks.\n - jua: from 3.3 points (full hit) to 1.5 points (coverage).\n - Gemini: from 1.7 points to 0.3.\n\n S2 gets partial credit for the paragraphs it delivers. This supports reading 1 of that note: on these\n questions, part of the article is nearly as good as all of it.\n\n## 1. What was built\n\n### 1.1 Unit tokens (`scripts/segmentation/unit_tokens.py`, ≈ 8 s)\n\nA **unit** is an element numbered by `calculaPos`: the 6 dispositivo and 7 grouping types, outside\n`Alteracao` (`common.Positions`). The table has one row per unit of every statutory file that has dispositivo,\ngrouping or DSP chunks. Columns:\n- the nested-set interval (`Num_Inicio`, `Num_Final`), the same numbering as the chunk table;\n- `own_tokens`: Qwen3 tokens of the unit's own text. This is its `Rotulo`, `TituloDispositivo`, `NomeAgrupador`,\n `p` and `table` elements whose nearest numbered ancestor is the unit, so the text of a quoted `Alteracao`\n belongs to the dispositivo that quotes it. The pieces are joined as the segmentation's `texto` joins them;\n- `subtree_tokens`: the unit with all its children, tokenised as one text;\n- `subtree_own_sum`: the sum of `own_tokens` over the subtree.\n\nA unit lies inside a chunk iff its `Num_Inicio` is inside the chunk's interval. So the units of a chunk, or of\na gold unit, form one contiguous block of the file's units sorted by start, and every overlap is a slice\nof a prefix sum.\n\nTwo side outputs:\n- `segmented/prefix_tokens.csv`: the tokens of each file's `[ epígrafe | ementa ]` prefix. There is one\n prefix per file (checked).\n- `segmented/unit_tokens_report.json`: the checks.\n\n| Check | Result |\n|---|---|\n| Unit chunks (dispositivo, grouping, DSP) whose interval does not start at a unit | 0 of all |\n| Unsplit ART/DSP base chunks: prefix + `subtree_own_sum` vs `n_tokens_qwen3` | 16,054 chunks; relative deviation median +0.5%, p99 +2.0%, min −4.8%, max +4.4%; none above 5%; total +0.38% |\n| Same with `subtree_tokens` (one tokenisation) | median +0.5%, max 3.2%; total +0.37% |\n\nThe small positive bias comes from token boundaries at the joins. The accounting uses the additive\n`own_tokens` and rescales gold + off-gold to the context size when they exceed it (§1.2).\n\nA first run skipped the 28 annexes that hold only loose dispositivos (DSP chunks), because `DSP` was missing\nfrom the chunk-type list. 387 chunks had no unit. This was fixed before any evaluation.\n\n### 1.2 Accounting of a context (`ragpipe/tokens.py`)\n\nWhat a chunk shows:\n- **content**: the units inside its interval;\n- **path**: the dispositivo units around it (article label, caput sentence before an inciso, paragraph head),\n plus two more cases:\n - for the S2c/S4 `caput` variant, the caput (`contexto_ids`);\n - for a split-article part, the units its repeated head shows (`parcial_ids`; e.g. the caput sentence\n before paragraphs). These are restricted to the chunk's own article.\n- the file prefix;\n- TXT/TAB chunks (non-statutory text, loose annex content) have no units: they hold a prefix and off-gold\n content.\n\nThe tokens `T` of a context (the `n_tokens_qwen3` of the selected texts, as in `context_precision`) are\nsplit into three parts:\n\n| Part | Definition |\n|---|---|\n| gold | own tokens of the distinct gold units visible as content **or on a path**, each counted once |\n| off-gold | own tokens of the distinct non-gold dispositivo units in the content, plus the text of unit-less chunks |\n| scaffold | `T − gold − off-gold`: prefixes, grouping names, path text outside the gold, repeated text |\n\nGold + off-gold are rescaled to `T` when the sum of own tokens exceeds it (the +0.4% bias), so the three\nshares always add up to 1.\n\nPer gold item:\n- `coverage` = visible own tokens of the item's subtree ÷ its own tokens;\n- when the item has several candidate units, the best one is used. This happens with the annex rule `either`\n (main file and annex) and with repeated article ids, the same \"any\" logic as the hit;\n- `gold_tokens` (the size used to weight items) = the largest candidate.\n\nPer question:\n- `token_recall` = Σ coverage·size ÷ Σ size;\n- `item_coverage` = the mean coverage over items;\n- the context shares are `gold / T`, `off-gold / T` and `scaffold / T`.\n\nItems with no LexML unit have no size and are left out of the token metrics. Per strategy, that is 46 of\n2,230 provision items (no LexML id) and 11 of 1,958 article items (article not in the LexML).\n\n**Deviations from the plan's definitions (§3.3), all deliberate:**\n1. **Path text is credited to the gold.** The plan counted all ancestor-path text as scaffold. But when the\n gold is a caput and the context holds its inciso I, the caput sentence printed before the inciso *is*\n the cited text, and the generator sees it. Counting it once as gold makes \"S2 rebuilt the caput from its\n incisos\" a full coverage, the same as the CPT chunk itself. Path text outside the gold, and every\n repetition, stays scaffold.\n2. **Grouping names are scaffold** (as in the plan), but the article label is part of the article's own text,\n so it is gold when the article is.\n3. **Split leaves.** When one leaf is cut into pieces (72 split articles have parts that share a unit), each\n piece gets an equal share of the leaf's tokens. Two pieces in one context cover it fully.\n\n### 1.3 Pipeline changes\n\n- `rag.py evaluate --token-metrics` (`EvalConfig.token_metrics`): default id\n `v3_<annex_rule>_<dedup>_<overflow>`. Without the flag, nothing changes: same columns, same config hash.\n- `per_item.csv.gz` gets `gold_tokens` and `budget_cov_<B>`. `per_question.csv.gz`, `metrics.csv` and\n `comparisons.csv` get the five metrics (budget view, article and provision levels; the three context\n shares for gold = all and slice = all only). `report.md` gets a §8 with them.\n- `Paths.unit_tokens` and `Paths.prefix_tokens` are read next to `--chunks`. The chunk loader reads\n `contexto_ids`.\n- Runtime: ≈ 100 s per embedding, against ≈ 30 s before (the accounting is per question × strategy × level ×\n budget).\n- Tests: `scripts/rag/tests/test_tokens.py` (7 tests).\n - Hand-computed accounting on a small nested corpus: inciso with its path, caput variant, repeated head of a\n split part, leaf pieces, grouping and non-statutory chunks, rescaling.\n - A smoke test checks that v3 leaves the old metrics unchanged and that the shares sum to 1.\n - All 53 rag tests pass.\n\n### 1.4 Consistency with the binary hits (jua, all budgets, both levels)\n\n- No coverage above 1.\n- No item with coverage 0 that is hit, at any budget.\n- Coverage > 0 without a hit: 0–3 items per budget, all S2c/S4 caput items. The caput sentence reaches the\n context only inside a paragraph chunk (the variant's purpose), which the binary matcher does not count.\n- Provision items fully hit with coverage < 0.99: none, except 1 at 16k.\n- Items with full coverage but no full hit: 3–6 per budget. For example, S2 retrieves every caput and\n paragraph chunk of art. 10 of Lei 9.250 but not the ART chunk. The text is all there, but the binary rule\n wants the article chunk.\n\n## 2. Results: what the contexts hold\n\njua-4b-mixed, provision level, all gold (`noise_signal.csv`; Gemini is in the same file and shows the same\npattern):\n\n| Metric | Strategy | 1k | 2k | 4k | 8k | 16k |\n|---|---|---:|---:|---:|---:|---:|\n| full-hit recall | S1 | 0.178 | 0.265 | 0.369 | 0.468 | 0.541 |\n| | S2 | 0.219 | 0.311 | 0.420 | 0.524 | 0.598 |\n| | S3 | 0.224 | 0.321 | 0.429 | 0.536 | 0.632 |\n| token recall | S1 | 0.179 | 0.271 | 0.376 | 0.481 | 0.558 |\n| | S2 | 0.233 | 0.333 | 0.436 | 0.542 | 0.621 |\n| | S2c | 0.233 | 0.330 | 0.440 | 0.541 | 0.618 |\n| | S3 | 0.237 | 0.343 | 0.442 | 0.551 | 0.651 |\n| | S4 | 0.236 | 0.339 | 0.450 | 0.554 | 0.642 |\n| context precision (binary) | S1 | 0.158 | 0.153 | 0.122 | 0.084 | 0.053 |\n| | S2 | 0.198 | 0.174 | 0.136 | 0.097 | 0.063 |\n| | S3 | 0.204 | 0.200 | 0.162 | 0.144 | 0.119 |\n| token precision | S1 | 0.098 | 0.092 | 0.069 | 0.047 | 0.030 |\n| | S2 | 0.113 | 0.101 | 0.076 | 0.052 | 0.033 |\n| | S2c | 0.125 | 0.108 | 0.081 | 0.055 | 0.034 |\n| | S3 | 0.115 | 0.105 | 0.079 | 0.056 | 0.036 |\n| | S4 | 0.126 | 0.111 | 0.085 | 0.058 | 0.036 |\n| noise share | S1 | 0.593 | 0.641 | 0.680 | 0.708 | 0.730 |\n| | S2 | 0.507 | 0.572 | 0.623 | 0.659 | 0.684 |\n| | S2c | 0.487 | 0.563 | 0.621 | 0.661 | 0.687 |\n| | S3 | 0.512 | 0.582 | 0.640 | 0.693 | 0.726 |\n| | S4 | 0.494 | 0.576 | 0.638 | 0.693 | 0.729 |\n| scaffold share | S1 | 0.310 | 0.267 | 0.251 | 0.245 | 0.240 |\n| | S2 | 0.380 | 0.327 | 0.301 | 0.288 | 0.283 |\n| | S2c | 0.388 | 0.329 | 0.299 | 0.284 | 0.279 |\n| | S3 | 0.374 | 0.312 | 0.280 | 0.251 | 0.238 |\n| | S4 | 0.380 | 0.314 | 0.276 | 0.249 | 0.234 |\n\nArticle level, 4k (jua / Gemini):\n\n| | S1 | S2 | S2c | S3 | S4 |\n|---|---:|---:|---:|---:|---:|\n| article recall (binary) | 0.398 / 0.413 | 0.503 / 0.515 | 0.480 / 0.511 | 0.507 / 0.517 | 0.487 / 0.517 |\n| token recall | 0.344 / 0.371 | 0.352 / 0.388 | 0.366 / 0.398 | 0.361 / 0.405 | 0.378 / 0.409 |\n| token precision | 0.108 / 0.118 | 0.115 / 0.129 | 0.122 / 0.134 | 0.119 / 0.134 | 0.127 / 0.138 |\n| noise share | 0.642 / 0.671 | 0.586 / 0.625 | 0.583 / 0.602 | 0.602 / 0.636 | 0.599 / 0.617 |\n\nPaired comparisons (`comparisons.csv`, 10,000 resamples; jua unless stated):\n\n| Comparison | Level, budget | Binary | Token-weighted |\n|---|---|---|---|\n| S1 → S2 | article, 4k | recall **+0.106** [0.083, 0.130] | token recall +0.008 [−0.003, 0.019], p .15; item coverage +0.003, p .58 |\n| S1 → S2 | article, 4k, Gemini | recall +0.103 | token recall +0.017 [0.006, 0.028] |\n| S1 → S2 | article, 16k | recall +0.100 | token recall +0.033 [0.022, 0.044] |\n| S1 → S2 | provision, 4k | recall +0.052 [0.032, 0.073] | token recall **+0.060** [0.040, 0.080]; noise −0.057; scaffold +0.051 |\n| S2 → S3 | provision, 4k | context precision +0.026 | token precision +0.004 [0.000, 0.007]; noise +0.017 |\n| S2 → S3 | provision, 16k | context precision +0.057 | token precision +0.003; token recall +0.030 [0.017, 0.044] |\n| S2 → S2c | provision, 4k | context precision +0.009 | token precision +0.005 [0.002, 0.008]; token recall +0.004, n.s. |\n| S3 → S4 | provision, 4k | context precision +0.008 | token precision +0.006 [0.003, 0.010] |\n\n**Reading.**\n1. **Noise.** Two-thirds of a 4k context is text about something else, and a quarter is scaffold. As\n expected, S1 has the most noise: a whole article for one inciso. The plan expected S3 to be about as\n noisy as S1. It is not: S3 sits between S2 and S1, because only 58% of its contexts hold a grouping chunk\n (granularity note §5).\n2. **The highest signal ratio is in S2c/S4, not S2.** The plan expected S2c/S4 to \"show the cost of their\n scaffold\". With jua that cost is cancelled: the caput sentence is gold whenever the caput is cited, and\n the variants' contexts hold fewer texts (11.5 vs 12.4 at 4k), hence fewer prefixes.\n3. **Scaffold is the price of self-contained chunks**, and it falls with the budget. At 1k a third of an S2\n context is prefix and path. The ementa prefix (up to 128 tokens per chunk) is most of it.\n4. **The article-level S1 → S2 gain is about breadth, not depth.** The binary article recall counts a\n paragraph of the article as a hit. S2 reaches more cited articles, but delivers about as much of their text\n as S1 at 4k. The provision level, where the gold is the cited unit itself, is the fair level for S2.\n5. **S3's high context precision is an artefact of the binary rule**: a 3,000-token chapter that holds a\n 40-token gold inciso counts as relevant in full. Token-weighted, S3 ≈ S2 at 4k. At 16k S3's real advantage\n is recall (+0.03), not precision.\n\n## 3. Do token metrics track answer quality? (§3.5 analysis 2)\n\n`scripts/report/a1_token_metrics.py` (4 s), outputs in\n`nuggets/scoring/analysis/gold-v0-auto/gemini-3.8-flash/all/token_metrics/`. The runs are every answer run with\na retrieval context (jua S1/S2 at 2k/4k/8k; S2c/S3/S4 at 4k; Gemini S1/S2 at 4k; 4 generators where they\nexist): 40 runs per level (the 2k/8k grid covers fewer generators). Judge Gemini 3.8 Flash, primary set.\n\n**(a) Levels: Spearman over questions within a run, mean over runs** (`spearman_levels.csv`):\n\n| Metric (provision level) | ~ answer V_strict | ~ context's own nugget support | ~ answer utilisation |\n|---|---:|---:|---:|\n| full-hit recall | **0.169** | 0.115 | 0.090 |\n| partial (any) recall | 0.149 | 0.113 | **0.123** |\n| token recall | 0.149 | 0.102 | 0.074 |\n| item coverage | 0.158 | **0.122** | 0.114 |\n| context precision (binary) | 0.125 | **0.189** | 0.029 |\n| token precision | 0.034 | 0.110 | 0.009 |\n| noise share | 0.072 | 0.021 | 0.011 |\n| token precision, partial on token recall | −0.073 | — | −0.011 |\n\n- Utilisation is the share of the context-supported nuggets that the answer supports, per question.\n- Per generator, V_strict ~ full-hit recall / item coverage: Luna 0.184 / 0.172, Terra 0.170 / 0.186,\n Sabiá-4 0.149 / 0.132, Sabiazinho-4 0.174 / 0.145.\n- At the article level the ordering is the same (full hit 0.160, coverage 0.147, token recall 0.098).\n\nThe precision rows are **confounded by gold size**. Token precision rises with the gold's size (ρ = 0.45 with\nthe question's gold tokens, S2 4k): a question citing three long articles fills more of any context with\ngold. Questions with large gold have more nuggets and are not easier. This is why the cross-question\ncorrelation of precision is near zero, or negative once recall is held fixed. The paired design below\nremoves that confound.\n\n**(b) Gains: the granularity note §4 design** (`spearman_gains.csv`). Per question, the S2 − S1 retrieval gain\nat 4k against the S2 − S1 V_strict gain. Spearman, mean over the 4 generators (jua; `none` excluded):\n\n| Group (n) | article recall | prov. full hit | prov. any hit | token recall | item coverage | token precision | context precision |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| all (551) | 0.074 | **0.122** | 0.112 | 0.095 | 0.110 | 0.090 | 0.077 |\n| whole_only (186) | 0.090 | 0.026 | **0.091** | 0.046 | 0.071 | 0.045 | 0.043 |\n| sub_only (130) | 0.038 | **0.126** | 0.124 | 0.094 | 0.122 | 0.110 | 0.087 |\n| mixed (235) | 0.100 | **0.157** | 0.123 | 0.124 | 0.129 | 0.104 | 0.086 |\n\nGemini (2 generators): all 0.085 (full hit) vs 0.083 (item coverage) vs 0.067 (token recall).\n\n**Reading.**\n- **No token metric beats the binary full hit as a predictor of answer quality**, in levels or in gains. All\n the correlations are weak (≤ 0.19), as in the granularity note.\n- Item coverage is the best of the token metrics, close to the full hit. Token recall (size-weighted) is\n worse: large gold items dominate it, and their partial delivery matters little to the answer.\n- **Noise does not measurably hurt the generators.** Neither noise share nor token precision predicts\n utilisation, before or after controlling for recall. The generators use what is in the context about as\n well whether it is 5% or 15% of the tokens. Utilisation does differ between strategies (phase 5, e.g.\n Terra 0.65 with S2 against 0.51–0.55 with S3/S4 at 4k), but per question that difference does not follow the\n noise share.\n- Binary context precision correlates best with the **context's** own nugget support (0.19). The\n context-support judge labels nuggets as supported by passages; a context with more passages near the\n gold supports more nuggets. Token precision, which counts only the cited unit itself, does so less (0.11).\n- On whole-article questions, coverage (0.071) sits between the full hit (0.026) and the any hit (0.091).\n This confirms the granularity note's corrected statement: for these questions partial retrieval counts.\n\n## 4. Whole vs sub-article questions with graded coverage (§3.5 analysis 3)\n\nProvision items, statutory, per-question mean, 4k (`coverage_by_group.csv`; question groups as in the\ngranularity note §3):\n\n| Embedding | Group | S1 full / coverage | S2 full / coverage | S3 full / coverage | S2 − S1, full → coverage |\n|---|---|---|---|---|---|\n| jua | whole_only (187) | 0.444 / 0.459 | 0.411 / 0.444 | 0.427 / 0.455 | −0.033 → **−0.015** |\n| jua | sub_only (130) | 0.410 / 0.416 | 0.580 / 0.587 | 0.590 / 0.597 | +0.170 → +0.171 |\n| jua | mixed (235) | 0.299 / 0.306 | 0.353 / 0.372 | 0.355 / 0.373 | +0.054 → +0.066 |\n| Gemini | whole_only | 0.437 / 0.465 | 0.420 / 0.462 | 0.461 / 0.489 | −0.017 → **−0.003** |\n| Gemini | sub_only | 0.450 / 0.455 | 0.597 / 0.603 | 0.605 / 0.611 | +0.147 → +0.148 |\n| Gemini | mixed | 0.307 / 0.320 | 0.371 / 0.394 | 0.379 / 0.396 | +0.064 → +0.073 |\n\n- On whole-article questions, S1's retrieval advantage under the strict rule shrinks to 1.5 points (jua) or\n vanishes (Gemini) once S2's partial delivery of those articles gets graded credit. That is about S2's\n coverage of whole articles. Measured by coverage, S2 delivers 97–99% of what S1 delivers on these\n questions; under the strict full hit it gets 93–96% of S1's value.\n- On sub-article questions nothing changes: the units are small, so coverage ≈ full hit.\n- The asymmetry of the granularity note becomes sharper. S2 is far ahead where citations are fine-grained\n (+15–17 points) and level with S1 where they are coarse. On whole-article questions the answers were already\n tied (granularity note §3), and graded coverage now agrees with that.\n\n## 5. Implications for the paper\n\n1. **Report the provision level as the primary retrieval level, with token recall next to it.** The binary\n article recall overstates S2's advantage (+0.106 at 4k, against +0.008 token-weighted). The binary context\n precision overstates S3's (+0.026, against +0.004). Both are artefacts of counting a chunk as wholly\n relevant or wholly irrelevant.\n2. **The cleanest description of the strategies' trade-off is the three-way token split.**\n - S1: high noise, low scaffold.\n - S2: −5 points of noise, +5 points of scaffold, +6 points of gold coverage at the provision level.\n - S3: S2 plus grouping chunks that raise recall at large budgets and raise noise.\n - S2c/S4: the best signal ratio.\n3. **Do not claim that \"less noise → better answers\".** The data do not support it: noise does not predict\n answer quality or utilisation once recall is fixed. The S2 > S1 answer gain is explained by delivering the\n cited unit (provision coverage), not by cleaner contexts.\n4. **For the remaining plan.**\n - A2 can reuse `unit_tokens` to weight a cited provision against the gold.\n - The A3 (Sol) contexts are the same as Terra's, so the token tables need no rerun for it.\n\n## 6. Files and reproduction\n\n| Path | Status |\n|---|---|\n| `scripts/segmentation/unit_tokens.py` | new: unit-token builder and its check |\n| `segmented/unit_tokens.csv.gz` (0.9 MB, byte-deterministic), `prefix_tokens.csv`, `unit_tokens_report.json` | new |\n| `scripts/rag/ragpipe/tokens.py`, `tests/test_tokens.py` | new |\n| `scripts/rag/ragpipe/evaluation.py`, `report.py`, `data.py`, `rag.py` | `--token-metrics`, report §8, `Paths.unit_tokens`, `contexto_ids` |\n| `runs/retrieval/{jua-4b-mixed,gemini-emb-2}/irpf/eval/v3_either_containment_merge_skip/` | new evaluation (manifests, metrics, comparisons, reachability, report in git; per-question and per-item tables gitignored) |\n| `scripts/report/a1_token_metrics.py` → `nuggets/scoring/analysis/gold-v0-auto/gemini-3.8-flash/all/token_metrics/` | analyses §2–4 |\n| `scripts/report/build_dashboard_data.py`, `docs/dashboard/index.html` | the dashboard reads v3. The retrieval tab offers the five metrics (budget chart and comparisons) with their definitions. Trace and explorer data rebuilt on v3 (same values) |\n\n```bash\n.venv/bin/python scripts/segmentation/unit_tokens.py # ≈ 8 s, after segment_all.py\nfor e in jua-4b-mixed gemini-emb-2; do\n .venv/bin/python scripts/rag/rag.py evaluate --retrieval runs/retrieval/$e/irpf --token-metrics # ≈ 100 s each\ndone\n.venv/bin/python scripts/report/a1_token_metrics.py # ≈ 4 s\n```\n\n**Not done:**\n- The HF release of these outputs. Repo A gets `segmented/unit_tokens.csv.gz` and `prefix_tokens.csv`; repo B\n gets the v3 evaluations and the analysis tables. Planned for stage 6 together with A2/A3 (plan §6), unless\n wanted earlier.\n- The `irpf_with_rir1999` ablation was not re-evaluated with token metrics.\n\n## 7. Next\n\nStage 3 of the plan: **A2, in-text legal citations**, closed book of the 4 current generators first\n(`docs/20261122_134404_in_text_legal_citation_scoring_plan.md`). Its gate is a manual check of 100–150\ncitations with ≥ 95% correct attribution. Stage 0 (new OpenRouter key, credit check, decisions D2–D3) is still\nneeded before A3.\n","20261122_194659_a2_in_text_legal_citations_results.md":"# A2: in-text legal citations of the generated answers — implementation and first results\n\nDate: 2026-11-22. Results note for item A2 of\n`docs/20261122_164407_methodology_additions_plan_token_weighted_citations_sol_and_fix_b.md`, following the design in\n`docs/20261122_134404_in_text_legal_citation_scoring_plan.md`. No API calls; $0.\n\n## Summary\n\n- **Implemented** `scripts/nuggets/nuggetizer/intext_citations.py` and the command `nuggets.py intext`, which takes\n ≈ 40 s for all 108 answer runs. Tests are in `scripts/nuggets/tests/test_intext_citations.py` (19 tests, all\n passing).\n- **Outputs:** `nuggets/scoring/analysis/gold-v0-auto/gemini-3.8-flash/all/intext/`.\n- **Validation:**\n - **Manual check:** 2 × 120 citations, stratified by generator × (closed book, RAG 4k). The first round found\n 5 errors (95.8%). After the fixes, a new sample had 2 errors (98.3%), and one of them is now fixed too.\n Stage 3's gate (≥ 95% correct attribution) is met.\n - **`lexml-linker` cross-check:** the act detector finds 3,184 of the linker's 3,184 federal acts in the\n closed-book claims. It also finds 268 more through aliases (RIR, CTN, Código Civil…) that the linker does not\n know.\n - **Oracle sanity check:** with the oracle 4k context, the article-level precision of the in-text citations is\n 0.81–0.91, at or above the 0.77–0.81 of the linked sources. As expected.\n- **Closed book: GPT-5.6 Terra cites best from memory, but cites the P&R's own article in only 32% of the questions.**\n (Article level, the 596 questions with gold references.)\n - **Terra** cites an article in 80% of its answers. Its cited articles are right in 30%.\n - **Luna** cites less often (39%) but is the most precise (38%).\n - **The Maritaca models** cite often (Sabiá-4 77%, Sabiazinho-4 58%) but rarely the right article (precision 15%\n and 9%).\n- **Hallucination signals are 3–7× higher for the Maritaca models in closed book:**\n - articles that do not exist in the cited act: 5–7%, against 0.7–1.0% for GPT;\n - units (paragraph, inciso…) that do not exist in an existing article: 17–22%, against 7–8%;\n - acts outside the corpus: 13–15%, against 2–3%. Sabiá-4 alone cites \"IN RFB nº 2.179, de 2024\" 54 times for\n the 2024 return rules; the P&R cites IN RFB nº 2.178, de 2024.\n - Citations of the revoked RIR/1999: Sabiazinho-4 16, Sabiá-4 6, Luna 1, Terra 0.\n- **No act from 2025 or later is cited** in any run, so the year-level check for later-year knowledge is negative.\n Acts from 2024 that are outside the corpus and written without a day can't be dated offline (§4.3).\n- **RAG:**\n - **In-text citation rates drop a lot for the Maritaca models.** In closed book they cite in 58–77% of their\n answers, with RAG at 4k in 16–38%; they lean on the linked sources instead. The GPT models keep citing in\n 82–90% of their RAG answers.\n - **S2 lowers the share of in-text article citations outside the context** for every generator (§3.6 of the\n citation plan). Terra goes from 19.0% to 12.4%, Luna from 14.2% to 10.2%, Sabiá-4 from 24.2% to 14.1% and\n Sabiazinho-4 from 42.8% to 40.4%.\n - **Hardly any citation is in the context but not in the claim's sources** (1–4%). A citation that is in the\n context is almost always the claim's own source.\n- **Link with quality** (descriptive): answers that cite a gold article score higher on V_strict than answers\n that cite only wrong articles. Terra closed book: 0.426 vs 0.324; Terra S2 4k: 0.421 vs 0.226.\n\n## 1. What was built\n\n### 1.1 Pipeline (`nuggetizer/intext_citations.py`)\n\n1. **Act detection** (`find_acts`), claim by claim. Three kinds of mention:\n - **Numbered acts, by regex.** Type and issuer, then \"nº\", the number, and a date or year. All the written\n forms seen in the survey are covered:\n - `Lei nº 9.250, de 1995`, `Lei 7.713/88`, `Lei nº 7.713` (no year);\n - `Instrução Normativa RFB nº 2.178, de 5 de março de 2024`, `IN nº 84/2001`, `IN SRF nº 15, de 2001`;\n - `Solução de Consulta (Interna) Cosit nº …`, `Solução de Divergência`;\n - `Parecer Normativo CST/Cosit`;\n - `Ato Declaratório (Interpretativo|Normativo|Executivo) …`;\n - `Medida Provisória nº 2.158-35`, `Decreto-Lei`, `Lei Complementar`, `Portaria`, `Resolução`, `Nota`,\n `Súmula`, `Emenda Constitucional`.\n - **Named acts, by an alias table:**\n - RIR/2018 (also \"Regulamento do Imposto sobre a Renda … 2018\"), RIR/1999 and RIR/99, RIR/94, /80 and /75;\n - CTN, Código Civil, Constituição Federal, ECA, Estatuto do Idoso / da Pessoa Idosa, CLT, CPC.\n\n \"Regulamento do Imposto de Renda\" without a year is read as RIR/2018 (resolver `alias_default`, 15 closed-book\n citations). When the name is followed by \"(Decreto nº …)\" or \"aprovado pelo Decreto nº …\", the numbered decree\n decides, and the two count as one act.\n - **Anaphors:**\n - \"da mesma Lei\", \"do referido Decreto\", \"desta Instrução Normativa\", \"do citado diploma\";\n - a bare type word without a number (\"do art. 10 da Lei\").\n\n They point back to the previous act of the same type, in the claim or in earlier claims of the same answer.\n2. **Resolution** to `dataset/documents.jsonl`: type family (from the `document_id` prefix) + number (dots removed;\n \"MP nº 2.158\" also matches 2.158-35) + year when given; the issuer (IN SRF vs RFB, PN CST vs Cosit, ADI/ADN/ADE)\n only breaks ties. Outcomes: `corpus`, `ambiguous` (3 cases in all runs), `not_in_corpus` (kept as\n `family:number:year`), `unresolved` (anaphor with nothing to point to).\n3. **Provision chains:** `scripts/dataset/citations.py` (`find_chains`, `chain_units`), unchanged. A chain is\n attributed to an act by these rules, in order:\n - **genitive:** \"art. 8º, § 2º, da Lei …\" (also \"art. 725 e seguintes do Decreto …\") binds to the act right after;\n - **before:** otherwise, the closest act before the chain in the claim (the P&R style \"Lei nº …, art. 8º\");\n - **after:** otherwise, the closest act after it;\n - **carried:** otherwise, the last act of the previous claims of the same answer;\n - **none:** otherwise, the chain stays unattributed.\n\n Chains with no article (or numbered annex) count only when they bind directly to an act (\"item 2 do Parecer\n Normativo CST nº 60\"). This drops \"outros anexos\", \"item 5 da ficha\" and the like. An act mentioned with no\n chain is a **document-level citation** (`act_only`).\n4. **Fixes found by the survey and the manual check:**\n - acts after \"com a redação dada pela\", \"alterado pelo\", \"incluído pela\" are amending acts, not citations, and are\n skipped;\n - \"constituição\" as a common noun (\"constituição de servidão\") is not the Constitution; a qualifier is required;\n - \"§ 1º\" of an article that has only a parágrafo único is rewritten to `par1u`, and the reverse (53 closed-book\n citations). This applies to existence and to the gold match.\n\n### 1.2 Scoring\n\n- **Gold:** the gold items of `ragpipe.relevance.gold_items` (596 questions). Recall uses the same denominators as\n the retrieval evaluation: all gold items of the level, including unreachable provisions.\n- **Match rules** (`unit_matches`, defaults of citation plan §7, D6):\n - **document:** same `document_id`;\n - **article:** same article, with annex rule `either`. A citation that names an annex (\"Anexo I, art. 10\")\n matches only that file when the gold item names files;\n - **provision:** full when the cited unit equals the gold unit or is its ancestor (the coarse citation \"art. 8º\"\n for a gold \"art. 8º, II, b\"); partial when the cited unit is a descendant of the gold unit. The two are\n reported apart (`recall_any`, `precision_any`).\n- **Per answer and level:**\n - recall over all answers with gold (an answer with no citation has zero recall), and over citing answers;\n - precision over citing answers. The cited units are distinct `(act, article)` / `(act, fragment)` pairs, and\n acts outside the corpus count as wrong;\n - `precision_in_corpus` leaves out the acts outside the corpus;\n - `cited_any`: the answer cites at least one gold item.\n- **Validity, all 715 questions:**\n - `article_missing` / `unit_missing`: against the LexML units of the document (`segmented/unit_tokens.csv.gz`, any\n file of the document). Only for resolved documents that have articles;\n - `not_in_corpus`;\n - `later`: dated after 2024-05-03, the P&R date. The full date is used when written or known from the corpus,\n otherwise the year; a 2024 act without a day stays undetermined;\n - `revoked`: RIR/1999, /94, /80, /75.\n- **Context class (§3.6), RAG runs:** each citation is turned into an article- or provision-level item and matched\n with the retrieval `Matcher` (G2–G5). The class is then:\n - `in_sources`: it hits one of the claim's `fundamentos` texts;\n - `in_context_not_sources`: it hits another text of the context;\n - `outside_context`: no context text holds it.\n\n The same is done at the document level.\n\n### 1.3 Deviation from the plan: `lexml-linker` is a cross-check, not the resolver\n\nThe linker's XML output (`linkertool -x`) gives one span that merges the chain with the act (\"art. 39 da Lei nº\n11.196, de 2005\"). It also returns nothing for Receita Federal acts or aliases, so a regex detector is needed anyway.\nOne detector for all acts keeps the act positions the attribution needs in one place. The linker is run on every\nclosed-book claim as a check (`linker_crosscheck.json`):\n\n| | count |\n|---|---:|\n| Federal act found by both | 3,184 |\n| Linker only | 0 |\n| Regex only, numbered act | 1 |\n| Regex only, alias (RIR, CTN, Código Civil, ECA…) | 268 |\n\n## 2. Validation\n\n### 2.1 Manual check\n\n| Round | Sample | Errors | Correct | Errors found |\n|---|---|---:|---:|---|\n| 1 (before fixes) | 120 (8 strata × 15, seed 7) | 5 | 95.8% | (a) \"art. 75 do Regulamento …, aprovado pelo Decreto nº 9.580\" bound to the previous law; (b), (c) \"constituição de servidão\" taken as the Constitution (×2); (d) an amending act (\"redação dada pela Lei nº 12.844\") counted as cited; (e) a `carried` chain (\"O art. 49 referido no parecer\") bound to the parecer |\n| 2 (after fixes) | 120 (seed 2026) | 2 | 98.3% | (f) \"art. 725 e seguintes do Decreto nº 9.580\" bound to the previous law (fixed afterwards); (g) \"doações … ao Estatuto do Idoso\" (the fund) counted as a document-level citation of the Estatuto |\n\n- (a)–(d) and (f) are fixed and covered by tests.\n- (e) and (g) remain:\n - `carried` is 10 of 4,264 closed-book citations;\n - a named statute mentioned without a citation is rare.\n- Model errors are not counted as extraction errors, since the extraction reads them correctly. Examples: \"Lei nº\n 123, de 2006\" for LC 123; \"art. 190 da Lei nº 8.069/1970\"; claims cut after \"alínea\".\n\n### 2.2 Coverage of the resolver (closed book, 4 generators, 4,264 citation rows)\n\n| Outcome | Rows |\n|---|---:|\n| Resolved to a corpus document | 3,884 (91.1%) |\n| Act outside the corpus | 364 (8.5%) |\n| Chain with no act | 16 (0.4%) |\n\n- Resolvers: regex 3,885, alias 339, `alias_default` 15, anaphor 9.\n- Bindings: genitive 3,795, act only 359, before 66, after 18, none 16, carried 10.\n- In RAG runs, chains with no act are more frequent: 0.2–0.6% for GPT, 6–7% for Sabiá-4 and 23–24% for Sabiazinho-4.\n They are mostly \"conforme o art. 63\" or \"arts. 26 a 45\", where the act is the claim's source document. They are\n left unattributed (see §5).\n\n## 3. Closed book: citations from memory\n\nQuestions with gold references, article level (document and provision in `intext_citations_runs.csv`):\n\n| Generator | Answers citing an article | Recall (all answers) | cited@any | Recall (citing) | Precision (citing) |\n|---|---:|---:|---:|---:|---:|\n| GPT-5.6 Terra | 79.6% | 0.138 | 0.320 | 0.170 | 0.295 |\n| GPT-5.6 Luna | 39.3% | 0.082 | 0.203 | 0.194 | 0.384 |\n| Sabiá-4 | 76.5% | 0.060 | 0.165 | 0.077 | 0.146 |\n| Sabiazinho-4 | 57.6% | 0.027 | 0.078 | 0.045 | 0.092 |\n\n- **Document level** (cited@any): Terra 0.458, Sabiá-4 0.328, Luna 0.261, Sabiazinho-4 0.260.\n- **Provision level:** full recall over all answers is 0.093 (Terra), 0.063, 0.041 and 0.018. Precision counting\n partial matches is 0.26, 0.35, 0.12 and 0.08.\n- Coarse citations (\"art. 8º\" for a gold inciso) are full matches; finer-than-gold citations are rare (recall_any −\n recall ≤ 0.02).\n\n### 3.1 Validity (all questions)\n\n| Generator | Citations | Act outside corpus | Article missing | Unit missing | Revoked (RIR/1999) | Act ≥ 2025 |\n|---|---:|---:|---:|---:|---:|---:|\n| GPT-5.6 Terra | 1,344 | 3.0% | 0.7% | 7.8% | 0 | 0 |\n| GPT-5.6 Luna | 633 | 1.9% | 1.0% | 6.5% | 1 | 0 |\n| Sabiá-4 | 1,370 | 14.5% | 5.2% | 21.6% | 6 | 0 |\n| Sabiazinho-4 | 917 | 12.5% | 6.5% | 16.5% | 16 | 0 |\n\n- **\"Unit missing\":** the article exists but the cited paragraph, inciso or alínea does not. Examples: Lei 9.250\n art. 8º inciso VII (art. 8º has two incisos); RIR art. 153 parágrafo único (it has §§ 1º–3º).\n- **Acts outside the corpus, most cited:**\n - Sabiá-4: IN RFB 2.179/2024 (54), 2.172/2023, 2.171/2023, 2.110/2022 (10 each), ECA, IN 2.168/2023;\n - Sabiazinho-4: IN RFB 2.177/2024 (6), 2.179/2024 (5), 2.010/2021, Lei 8.012/1990, IN RFB 213/2022, Lei\n 10.637/2002;\n - GPT: IN SRF 15/2001, Lei 8.218/1991, Súmula 215 STJ, Lei 14.663/2023, Estatuto do Idoso, CPC (≤ 2 each).\n\n These may be real acts the P&R doesn't cite, or invented ones. Only a lookup can tell (citation plan §7.3; not\n done).\n\n## 4. RAG answers\n\n### 4.1 In-text citations, article level (4k, primary embedding)\n\n| Generator | Context | Citing | Recall (all) | cited@any | Precision (citing) |\n|---|---|---:|---:|---:|---:|\n| Terra | S1 | 82.3% | 0.332 | 0.594 | 0.525 |\n| Terra | S2 | 90.4% | 0.375 | 0.672 | 0.536 |\n| Terra | oracle | 88.9% | 0.574 | 0.894 | 0.907 |\n| Luna | S1 | 85.6% | 0.359 | 0.645 | 0.538 |\n| Luna | S2 | 89.8% | 0.393 | 0.685 | 0.501 |\n| Luna | oracle | 89.8% | 0.593 | 0.899 | 0.910 |\n| Sabiá-4 | S1 | 34.3% | 0.135 | 0.249 | 0.488 |\n| Sabiá-4 | S2 | 34.6% | 0.151 | 0.268 | 0.465 |\n| Sabiá-4 | oracle | 47.5% | 0.328 | 0.464 | 0.874 |\n| Sabiazinho-4 | S1 | 21.2% | 0.065 | 0.136 | 0.434 |\n| Sabiazinho-4 | S2 | 16.1% | 0.053 | 0.098 | 0.432 |\n| Sabiazinho-4 | oracle | 15.5% | 0.077 | 0.140 | 0.806 |\n\n- **In-text recall rises from S1 to S2** for Terra, Luna and Sabiá-4 (+0.02 to +0.04), and falls for Sabiazinho-4,\n which cites less in the text under S2.\n- **The Maritaca models cite in the text far less with RAG than in closed book** (Sabiá-4 77% → 35%; Sabiazinho-4\n 58% → 16–21%). They seem to leave the legal basis to the linked sources. For them, the linked-source scores of\n phase 5 are the better measure of legal grounding.\n- In-text precision with retrieval (0.43–0.54) is at the level of the linked sources. With the oracle (0.81–0.91),\n it is above them: the sanity check of citation plan §4.\n\n### 4.2 In-text citations vs the claim's sources vs the context (citation plan §3.6), article level, 4k\n\n| Generator | Context | In the claim's sources | In context, not in sources | Outside the context |\n|---|---|---:|---:|---:|\n| Terra | S1 | 79.4% | 1.7% | 19.0% |\n| Terra | S2 | 86.0% | 1.6% | 12.4% |\n| Terra | oracle | 86.4% | 2.2% | 11.4% |\n| Luna | S1 | 84.6% | 1.2% | 14.2% |\n| Luna | S2 | 88.3% | 1.6% | 10.2% |\n| Luna | oracle | 87.6% | 1.6% | 10.8% |\n| Sabiá-4 | S1 | 74.1% | 1.7% | 24.2% |\n| Sabiá-4 | S2 | 84.4% | 1.5% | 14.1% |\n| Sabiá-4 | oracle | 85.9% | 1.9% | 12.2% |\n| Sabiazinho-4 | S1 | 53.6% | 3.6% | 42.8% |\n| Sabiazinho-4 | S2 | 56.3% | 3.3% | 40.4% |\n| Sabiazinho-4 | oracle | 58.0% | 3.4% | 38.6% |\n\n- **S2 cuts the in-text citations from outside the context** by about a third for the GPT models and by 42% for\n Sabiá-4. A likely reason is that the cited paragraph or inciso is now in the context as its own text. This is the\n in-text analogue of the phase 5 result that S2 helps on sub-article questions (granularity note §3).\n- **10–14% of the GPT models' article citations stay outside the context, even with the oracle.** This is a floor of\n parametric knowledge used in RAG answers, at the citation level: \"per-citation leakage\", beside the nugget-level\n leakage of `utilisation_runs.csv`. It is also the baseline for A3's H3 (Sol).\n- **Sabiazinho-4's ≈ 40% outside the context** mixes real leakage with unattributed chains read as the wrong act,\n which are not in this table, and with its weaker matching of claims to sources. Read it with care.\n- Revoked acts in RAG answers: 3–24 citations per run. They can only come from memory, since the RIR/1999 is\n excluded from the main corpus.\n\n### 4.3 Later-year acts\n\n- No citation of an act dated 2025 or later, in any run.\n- Acts from 2024 outside the corpus, written with the year only, can't be dated offline:\n - Lei 14.937/2024 (Luna, with Decreto Legislativo 36/2024 on the Rio Grande do Sul calamity);\n - Lei 14.848/2024 (Terra);\n - Lei 14.871/2024 and Lei 14.973/2024 (Sabiá-4);\n - INs RFB 2.168, 2.173, 2.177, 2.179, 2.210 and 2.219 of 2024 (Sabiazinho-4, Sabiá-4).\n\n Any of them dated after 2024-05-03 would be knowledge from after the reference date. A dated list from LexML or\n the Receita Federal would settle this. For A3 (Sol), this check matters most.\n\n## 5. Link with answer quality (citation plan §3.7; descriptive)\n\nV_strict by what the answer cites at the article level (questions with gold, answered):\n\n| Generator | Context | No citation | Only wrong articles | A gold article | Spearman (recall, V_strict), citing answers |\n|---|---|---:|---:|---:|---:|\n| Terra | closed book | 0.279 (111) | 0.324 (270) | 0.426 (177) | 0.17 |\n| Terra | S2 4k | 0.376 (49) | 0.226 (137) | 0.421 (361) | 0.32 |\n| Luna | closed book | 0.240 (342) | 0.286 (120) | 0.256 (112) | 0.04 |\n| Luna | S2 4k | 0.364 (48) | 0.228 (112) | 0.410 (324) | 0.28 |\n| Sabiá-4 | closed book | 0.218 (127) | 0.214 (336) | 0.253 (90) | 0.10 |\n| Sabiá-4 | S2 4k | 0.351 (373) | 0.228 (53) | 0.364 (144) | 0.30 |\n| Sabiazinho-4 | closed book | 0.161 (233) | 0.182 (296) | 0.152 (43) | 0.02 |\n| Sabiazinho-4 | S2 4k | 0.310 (493) | 0.133 (31) | 0.235 (53) | 0.28 |\n\n- With RAG, answers that cite only wrong articles are the worst group for every generator, about 0.10–0.20 below\n the answers that cite a gold article.\n- In closed book, Terra's correct citations go with clearly better answers (+0.10). For the other models, citation\n correctness says little about the answer.\n- These are associations: both depend on how hard the question is.\n\n## 6. Files\n\n| File | Content |\n|---|---|\n| `scripts/nuggets/nuggetizer/intext_citations.py` | detector, resolver, attribution, scoring, context classes, run driver |\n| `scripts/nuggets/nuggets.py intext` | command: `--sample all`, `--runs <glob>`, `--no-linker` |\n| `scripts/nuggets/tests/test_intext_citations.py` | 19 tests (forms from the survey, the fixed errors, match rules) |\n| `…/all/intext/intext_citations.csv.gz` | one row per cited unit: run, question, claim, chain, act text/kind/resolver/status, `act_key`, `document_id`, unit ids, match per level, validity flags, `ctx_document/article/provision` |\n| `…/all/intext/intext_answers.csv.gz` | one row per answer × level: `n_gold`, `n_cited`, recall, recall_any, cited_any, precision (3 variants) |\n| `…/all/intext/intext_citations_runs.csv` | per run × level; the document-level rows also carry the validity and context-class shares |\n| `…/all/intext/intext_vs_quality.csv` | §5 |\n| `…/all/intext/linker_crosscheck.json` | §1.3 counts and examples |\n\nThe tables also cover the other runs: budgets 2k and 8k, S2c/S3/S4, the `stratified_30` runs, wrong-context and\n`context_v1`, and the gemini-emb-2 runs (`context_id` `…@gemini-emb-2`).\n\n## 7. Open points\n\n1. **Unattributed chains in RAG answers.** These are 23% of Sabiazinho-4's in-text chains: \"conforme o art. 63\",\n with no act. They could be bound to the document of the claim's own source (`fundamentos`). That would raise its\n in-text recall and change its §4.2 classes. It is not done yet, because it mixes the two citation channels.\n Decide before the paper tables.\n2. **Acts outside the corpus and 2024 acts:** these need a manual or LexML lookup, to tell invented acts from real\n but uncited ones and to date the 2024 acts (§3.1, §4.3). This is citation plan §7.3; the default was a manual\n sample only.\n3. **A3 (Sol)** gets these tables at no extra work once its runs exist: rerun `nuggets.py intext` (H3: per-citation\n leakage; H4: closed-book precision and later-year acts).\n4. Not done: an in-text citation panel in the explorer's question trace (optional in the citation plan).\n","20261122_205115_a3_gpt_6_2_sol_results.md":"# A3: GPT-6.2 Sol in GPT-5.6 Terra's four conditions — execution, costs and results\n\nDate: 2026-11-22. Results note for item A3 of\n`docs/20261122_164407_methodology_additions_plan_token_weighted_citations_sol_and_fix_b.md` (stages 4–5).\n\nUser decisions of 2026-11-22:\n- D2: the batch route;\n- D3: Terra's 4 conditions only (closed book, S1 4k, S2 4k, oracle 4k; jua contexts, revised corpus of fix B);\n- D4: a new OpenRouter key.\n\n## Summary\n\n- **Done:**\n - 2,741 Sol answers (715 + 715 + 715 + 596), 0 errors, all served by OpenAI;\n - scored by the primary judge (Gemini 3.8 Flash, set `gold-v0-auto`), 0 failed calls;\n - A2 in-text citation tables and the H1–H5 analyses (`scripts/report/a3_sol_analysis.py`).\n- **Cost: $18.41.**\n - Generation $12.73, all through OpenRouter's Batch API at $1 / $5 per M tokens: pilot $0.52, full run $12.20,\n probes $0.01.\n - Scoring $5.68.\n - This is inside the plan's batch estimate ($19–24 with scoring). The ledgers match OpenRouter's reported batch\n costs to the cent. The key has $17.91 left of its $37.30 limit.\n- **Two deviations from the plan:**\n 1. **Reasoning can't be disabled for Sol** (\"Reasoning is mandatory for this endpoint and cannot be disabled\",\n on both the synchronous and batch routes). The runs use `minimal`, the lowest accepted effort. This is a\n confound against Terra (`none`). In practice it is small:\n - RAG answers: reasoning tokens in 0.2–0.4% of the answers;\n - closed book: 43% of the answers, mean 31 tokens per answer.\n 2. **The `:batch` model id can't be called synchronously.** Our client gained OpenRouter batch support\n (`llm_client/batch.py`, `rag.py run --batch`, `rag.py batch wait`; §1).\n- **Sol is much better than Terra in every condition:** +0.08 to +0.09 V_strict, p < 0.001 in each:\n\n | Condition | Terra | Sol |\n |---|---:|---:|\n | Closed book | 0.351 | 0.445 |\n | S1 | 0.325 | 0.409 |\n | S2 | 0.342 | 0.422 |\n | Oracle | 0.366 | 0.446 |\n\n- **H1 (retrieval adds less recall for Sol): supported in direction, weak in size.**\n - Closed book → S2 is −0.023 V_strict for Sol (p 0.16) against −0.009 for Terra. The difference in differences\n is −0.014 (CI −0.048 to 0.021, p 0.44).\n - With partial credit (V), Sol loses −0.042 (p 0.003) and the difference in differences is −0.031 (CI −0.060 to\n −0.003, p 0.035).\n - For Sol, closed book is its best non-oracle condition. S1 is significantly worse than closed book (−0.036,\n p 0.03).\n- **H2 (retrieval still buys correctness): not supported for Sol.** Sol contradicts few nuggets even without\n retrieval: 10.9% of the questions, against 29.5% for Terra. S2 lowers that only to 8.7% (p 0.12); Terra goes from\n 29.5% to 8.0%. The difference in differences, +0.19, is significant (p < 0.001). Terra's case for retrieval\n (correctness) mostly disappears with Sol; only the oracle context still cuts Sol's contradictions (4.4%).\n- **H3 (more own knowledge inside RAG answers): supported.**\n - Nugget-level leakage roughly doubles: P(answer support | context not support) is 0.050–0.056 against 0.024–0.027\n for Terra.\n - The share of the answer's supported vital nuggets that the context does not support is 6.1–6.5%, against\n 3.7–3.8% for Terra.\n - In-text article citations outside the context under S2: 15.1% against 12.4%. Under S1 and the oracle they are\n the same.\n - Sol also uses more of the context: utilisation 0.74 against 0.63–0.65.\n- **H4 (more accurate closed-book citations, more from later years): accuracy yes, later years no.** Closed book,\n article level:\n - cited@any: 0.491 against Terra's 0.320;\n - precision among citing answers: 0.445 against 0.295;\n - non-existent units: 3.6% against 7.8%; non-existent articles: 0.1% against 0.7%.\n\n **No act from 2025 or later is cited**, and the only 2024 act outside the corpus is one Portaria. Sol answers with\n the 2024 rules and doesn't bring in later ones.\n- **H5 (smaller S1 → S2 gain than Terra's): not distinguishable.** Sol gains +0.013 (p 0.09), Terra +0.018; the\n difference in differences is −0.005 (p 0.68).\n\n## 1. Execution\n\n### 1.1 Probe (≈ $0.011)\n\n- **`openai/gpt-6.2-sol:batch`** on `chat/completions`: refused with HTTP 404 (\"cannot be used with the\n chat/completions endpoint (adapter OpenAIBatchAdapter)\"). It is an asynchronous id only, so no cost. OpenRouter's\n Batch API is `POST /api/v1/batches`:\n - the requests are inline, with no file upload;\n - one model and one endpoint per batch;\n - the results come back inline in `GET /api/v1/batches/{id}`;\n - usage is reported per request, cost only per batch;\n - there is no cancel endpoint.\n- **The batch-level `provider` accepts only `only` and `allow_fallbacks`.** `require_parameters` and\n `data_collection` are refused there (HTTP 400), so they stay in each request body. OpenRouter may not apply them\n there. The checks that matter are made on the replies themselves:\n - served provider OpenAI on every result;\n - no tool use;\n - billed cost = token cost at $1 / $5, exactly. The batch was billed $0.010859 for 4,574 input and 1,257 output\n tokens.\n- **Reasoning:** `effort: none` is refused synchronously and in batch (the batch failed before any cost).\n `minimal` is accepted.\n- Knowledge cutoff: not in the catalogue, and not probed (informational only, plan §5.4).\n\n### 1.2 Client changes (no change to any existing request or cache key)\n\n- **`llm_client/client.py`:** `LLM.body()` builds the OpenRouter batch body: the synchronous body without `model`,\n with `provider` keeping only the keys the batch level refuses. Batch queueing is enabled for `openrouter`.\n- **`llm_client/batch.py`:** OpenRouter submit, poll and collect.\n - Each result is checked like a synchronous reply: tool use, served provider. A failed check is ledgered as\n `rejected:` and not cached.\n - Ledger rows are `batch:` rows at half the list price.\n - The job record keeps OpenRouter's reported `usage` next to the ledger sum (`usd_rows`), so the two can be\n reconciled.\n - `BatchRecorder(max_requests=…)` splits a queue into several jobs.\n - Keys that are still in an open job are not queued again.\n- **`rag.py`:**\n - `run`/`generate --batch [--batch-max N]` queues the uncached calls and submits; nothing is written until the\n rerun.\n - `rag.py batch status|wait` polls and collects into `runs/answers/cache`. Job records are in\n `runs/answers/batches/` (gitignored, like `runs/**`).\n- **Tests:** 2 new OpenRouter batch tests (submit split, collect, ledger, provider mismatch). The suites pass:\n llm_client 15, rag 53, nuggets 19.\n- **`scripts/rag/llms.yaml`:** entry `gpt-6.2-sol`.\n - Price $2 / $0.10 / $10 list with `batch_discount: 0.5`; model `openai/gpt-6.2-sol`; effort `minimal`;\n `only: [openai]`.\n - Comments record the probe findings.\n- **Experiment file:** `scripts/rag/experiments/sol.yaml`.\n\n### 1.3 Pilot (stratified_30; stage 4 gate)\n\n- 114 requests (115 calls; one prompt is byte-identical to another), $0.52, all collected.\n- Tokens per answer are close to Terra's:\n\n | Condition | Sol input / output | Terra input / output |\n |---|---:|---:|\n | Closed book | 464 / 257 | 421 / 296 |\n | S1 | 3,785 / 413 | 3,714 / 403 |\n | S2 | 3,783 / 463 | 3,741 / 418 |\n | Oracle | 2,201 / 461 | 2,530 / 402 |\n\n- Projected full run: ≈ $12.5, at the bottom of the plan's $12.4–17.5. Gate passed.\n\n### 1.4 Full run\n\n- **OpenRouter refuses a batch whose worst case exceeds the balance.** Every request is costed at `max_tokens`:\n 2,626 requests came to $58.29, against a $35.79 balance (HTTP 402, nothing charged). The run was therefore\n submitted as 4 jobs of ≤ 650 requests (`--batch-max 650`), all accepted at once. Each took ≈ 15 min.\n\n | Job | Requests | Billed |\n |---|---:|---:|\n | 1 | 650 | $1.15 |\n | 2 | 650 | $3.81 |\n | 3 | 650 | $4.00 |\n | 4 | 632 | $3.24 |\n\n- 2,582 requests in all, all cached, 0 failed. Answers are written in `runs/answers/jua-4b-mixed/irpf/\n {answer_closed_v1,answer_v1}/gpt-6.2-sol/<condition>/`.\n- Mean per answer: closed book 465 input / 260 output tokens; S1 and S2 3,773 / 470; oracle 2,581 / 483. All\n replies finished `stop`.\n\n| Condition | Abstention | Claims | Answer length (chars) | Quotes OK | Reasoning tokens > 0 |\n|---|---:|---:|---:|---:|---:|\n| Closed book | 0.1% | 2.73 | 610 | — | 42.9% (mean 31) |\n| S1 4k | 3.6% | 2.66 | 660 | 99.9% | 0.4% |\n| S2 4k | 2.1% | 2.61 | 662 | 99.9% | 0.4% |\n| Oracle 4k | 4.0% | 2.74 | 678 | 99.9% | 0.2% |\n\nSol writes fewer, shorter claims than Terra. Terra's closed-book answers have 4.46 claims and 1,049 characters.\n\n### 1.5 Costs\n\n| Item | USD | Ledger |\n|---|---:|---|\n| Probes (batch of 2 + 1 sync) | 0.011 | `runs/costs.csv` |\n| Pilot batch | 0.518 | `runs/costs.csv` |\n| Full batches | 12.199 | `runs/costs.csv` |\n| Scoring, 2,613 judge calls (Flash flex) | 5.679 | `nuggets/scoring/costs.csv` |\n| **Total A3** | **18.41** | |\n\nPlan estimate for batch: $19–24, without the reasoning surcharge. The OpenRouter key's usage is $19.39, which\nincludes $0.98 already on it before this work; $17.91 is left.\n\n## 2. Results (primary nugget set, judge Gemini 3.8 Flash, all 715 questions; oracle 596)\n\nOutputs: `nuggets/scoring/analysis/gold-v0-auto/gemini-3.8-flash/all/sol/` (`means.csv`, `sol_vs_terra.csv`,\n`within.csv`, `did.csv`, `utilisation.csv`, `intext.csv`). Rebuild with `.venv/bin/python\nscripts/report/a3_sol_analysis.py` (no API calls).\n\n### 2.1 Means\n\n| Generator | Condition | V_strict | A_strict | V | Questions with a contradiction |\n|---|---|---:|---:|---:|---:|\n| Terra | closed book | 0.351 | 0.308 | 0.490 | 29.5% |\n| Terra | S1 4k | 0.325 | 0.284 | 0.456 | 9.2% |\n| Terra | S2 4k | 0.342 | 0.304 | 0.479 | 8.0% |\n| Terra | oracle 4k | 0.366 | 0.324 | 0.513 | 6.5% |\n| Sol | closed book | **0.445** | 0.386 | 0.590 | 10.9% |\n| Sol | S1 4k | 0.409 | 0.359 | 0.537 | 7.1% |\n| Sol | S2 4k | 0.422 | 0.368 | 0.548 | 8.7% |\n| Sol | oracle 4k | 0.446 | 0.389 | 0.580 | 4.4% |\n\n### 2.2 Sol − Terra, paired by question\n\n| Condition | V_strict diff (95% CI) | p | Contradiction diff | p |\n|---|---:|---:|---:|---:|\n| Closed book | +0.093 (0.063, 0.123) | < 0.001 | −0.186 | < 0.001 |\n| S1 4k | +0.084 (0.063, 0.106) | < 0.001 | −0.021 | 0.06 |\n| S2 4k | +0.079 (0.058, 0.101) | < 0.001 | +0.007 | 0.58 |\n| Oracle 4k | +0.080 (0.058, 0.102) | < 0.001 | −0.022 | 0.04 |\n\nThe chapter-cluster CIs agree; all V_strict CIs exclude 0.\n\n### 2.3 Hypotheses\n\n| | Test | Terra | Sol | Difference in differences (95% CI), p | Verdict |\n|---|---|---:|---:|---|---|\n| H1 | closed book → S2, V_strict | −0.009 | −0.023 | −0.014 (−0.048, 0.021), 0.44 | direction as expected, not significant |\n| H1 | closed book → S2, V (partial credit) | −0.011 | −0.042 | −0.031 (−0.060, −0.003), 0.035 | supported |\n| H1 | closed book → S1, V_strict | −0.027 | −0.036 (p 0.03) | −0.009, 0.61 | — |\n| H2 | closed book → S2, any contradiction | −0.215 | −0.022 (p 0.12) | +0.193 (0.154, 0.232), < 0.001 | not supported for Sol: few contradictions without retrieval |\n| H3 | leakage (vital), S1 / S2 / oracle | 0.024 / 0.026 / 0.027 | 0.050 / 0.056 / 0.052 | — | supported |\n| H3 | answer support not in context (vital), S2 | 3.7% | 6.5% | — | supported |\n| H3 | in-text article citations outside the context, S1 / S2 / oracle | 19.0 / 12.4 / 11.4% | 19.9 / 15.1 / 11.4% | — | weakly (S2 only) |\n| H4 | closed book, article cited@any / precision | 0.320 / 0.295 | 0.491 / 0.445 | — | supported (accuracy) |\n| H4 | acts from 2025 or later, closed book | 0 | 0 | — | not supported |\n| H5 | S1 → S2, V_strict | +0.018 | +0.013 | −0.005 (−0.028, 0.019), 0.68 | not distinguishable |\n\nOther figures:\n- Utilisation, P(answer support | context support) on vital nuggets: Sol 0.74 / 0.74 / 0.69, Terra 0.63 / 0.65 /\n 0.59 (S1 / S2 / oracle). Sol uses more of what the context holds, and adds more from outside it.\n- S2 → oracle cuts Sol's contradictions (−0.035, p 0.001) but not Terra's.\n\n### 2.4 In-text legal citations (A2 tables, `intext.csv`)\n\n| Generator | Condition | Citing (article) | Recall, all answers | cited@any | Precision (citing) | Unit missing |\n|---|---|---:|---:|---:|---:|---:|\n| Terra | closed book | 79.6% | 0.138 | 0.320 | 0.295 | 7.8% |\n| Sol | closed book | 82.5% | 0.237 | 0.491 | 0.445 | 3.6% |\n| Terra | S2 4k | 90.4% | 0.375 | 0.672 | 0.536 | 0.0% |\n| Sol | S2 4k | 94.4% | 0.412 | 0.706 | 0.533 | 0.3% |\n| Terra | oracle 4k | 88.9% | 0.574 | 0.894 | 0.907 | 0.8% |\n| Sol | oracle 4k | 93.5% | 0.622 | 0.936 | 0.902 | 0.8% |\n\n- At the provision level, Sol's closed-book recall almost doubles Terra's: 0.176 vs 0.093.\n- With retrieval, Sol's provision-level recall is a little below Terra's: S2 0.229 vs 0.245.\n- Acts outside the corpus in closed book: 2.9% (Terra 3.0%). The most frequent: CPC (8), ECA (6), IN RFB\n 1.700/2017 (5), Súmula 215 STJ (3).\n- No revoked act in closed book.\n\nV_strict by citation (article level, questions with gold):\n\n| Generator | Condition | Cites a gold article | Cites only wrong articles |\n|---|---|---:|---:|\n| Sol | closed book | 0.482 | 0.356 |\n| Sol | S2 4k | 0.484 | 0.289 |\n| Terra | closed book | 0.426 | 0.324 |\n| Terra | S2 4k | 0.421 | 0.226 |\n\n## 3. Reading\n\n1. **The newer, stronger model knows the P&R content better.**\n - Closed book, Sol beats Terra by +0.09 V_strict, and beats every RAG condition of every earlier generator.\n Terra's best is the oracle at 0.366.\n - It also contradicts the gold answer three times less often without retrieval.\n\n Memorisation of the public P&R 2024 can't be excluded: it is part of \"parametric knowledge\" (citation plan\n §1.3).\n2. **For Sol, the 4k retrieval contexts don't help, and slightly hurt.**\n - V drops significantly from closed book to S2 (−0.042), and V_strict drops from closed book to S1 (−0.036).\n - Even the oracle context only matches closed book on V_strict (0.446 vs 0.445).\n - What retrieval still gives Sol: grounding (quotes, linked sources) and, with the oracle, fewer contradictions.\n\n The trend seen with Terra (H1) is stronger with Sol, as hypothesised. On V_strict it is not significant as a\n difference in differences; on V it is.\n3. **The S2 > S1 result holds for Sol** (+0.013, p 0.09; Terra +0.018, p 0.08). Its size does not depend on the\n generator here (H5).\n4. **Confounds to state in the paper:**\n - generation (6.2 vs 5.6) and tier (Sol vs Terra) are not separated: no `gpt-6.2-terra` exists, and the optional\n `gpt-6.1-terra` control was not run (D3);\n - Sol ran at reasoning effort `minimal`, Terra at `none`. Reasoning tokens appear in 43% of Sol's closed-book\n answers (31 tokens on average) and almost never with a context, so the closed-book advantage could owe a\n little to it;\n - batch vs flex serving should not matter (same model, same parameters, served by OpenAI).\n\n## 4. Not done / next\n\n1. **The HF eval repo (B) update and the dashboard / explorer rebuild with the Sol runs** (plan §5.4 step 6). The\n HF push is outward-facing, so it waits for the user's go-ahead. The dashboard builders may need a colour/order\n entry for the new generator.\n2. **Optional controls** (D3: not requested):\n - `wrong-S2_budget4000` on `stratified_30` (≈ $0.1 batch);\n - `gpt-6.1-terra` closed book + S2, to separate generation from tier (≈ $3 batch + $3.3 scoring).\n\n The remaining key balance, $17.91, covers both.\n3. The paper's main tables and the results overview figures (`scripts/report/make_results_overview_figures.py`)\n do not include Sol yet.\n","scripts/nuggets/README.md":"# Gold-answer nuggetization — BR-TaxQA-R v2.0\n\nTurns the 715 gold answers into **legal nuggets** (short, self-contained, atomic statements), so the\nanswers of the RAG generators can be scored against them. Design:\n`docs/20261011_224049_gold_answer_nuggetization_plan_v2.md` (**plan v2**).\n\n**Status (2026-10-23): phase 5 (scoring) done** on the 25 runs of the trimmed RAG grid (`nuggets/scoring/`,\n$55.96 billed: primary scoring, context support, cross-sets, a second judge, and the analyses without LLM):\n`docs/20261023_210727_rag_phase5_scoring_and_analysis.md` (results, conclusions, open items §9). Commands:\n\"Phase 5\" under \"Commands\".\n\n**Earlier status (2026-10-21): phases 2–4 done** on the 715 questions (`nuggets/full/`, $65.34 billed, 4 h 15 min; the\nfrozen set is `nuggets/gold/v0-auto/`): `docs/20261021_155704_nuggetization_phases_2_to_4_execution.md`. Next:\nphase 5 (scoring), after the RAG answer runs. Open items: that note's §6.\n\n**Earlier status (2026-10-13): phase 1 pilot done** on `stratified_30` (`nuggets/pilot/`, $8.29 billed; the last\ntwo 3.1 Pro items ran through Batch, pilot note §11). Every phase 1 item of plan v2 §4 is implemented: three\nfamilies, replicates, the 2-call mode, alignment, round trip, two auditors with repair, planted-error\nauditor test, known-answer tests and the pilot report. **Phase 2 waits for the user's gate decisions**\n(pilot note §12). Read, in this order:\n\n1. `docs/20261012_114025_nuggetization_preview_10_questions.md` — preview v1: API findings, first\n cost estimate, open items;\n2. `docs/20261012_154616_nuggetization_preview_open_items_resolution.md` — decisions on R8/judge,\n granularity and git;\n3. `docs/20261012_160349_nuggetization_preview_v2_execution.md` — v2/v3 runs, pointer rule (§13);\n4. `docs/20261012_192640_nuggetization_phase1_pilot.md` — **the pilot**: results, `answer_cleaned`\n content loss (§8), Gemini 3.1 Pro daily quota (§9), **cost estimate (§10)**, decisions (§12);\n5. `docs/20261020_130829_openrouter_support_plan.md` — **OpenRouter route** (default from 2026-10-21):\n design, decisions (§7), implementation and probe results (§8).\n\n## Layout\n\n```\nscripts/llm_client/ provider-neutral client (shared with RAG Phase 3 later)\n client.py LLM.complete_json(): openai (Responses API), gemini (REST), openai_compat (Qwen),\n openrouter (Chat Completions, pinned upstream); route_config(); disk cache keyed\n by the request; ledger rows; --budget cap (BudgetExceeded)\n batch.py Batch API jobs (direct route only)\n tests/ pytest, OpenRouter provider against mocked replies (no network)\nscripts/nuggets/\n nuggets.py CLI: sample, create [--replicate], importance, validate, selfscore, align,\n roundtrip, audit, repair, plant, known build|judge, report, pilotreport,\n batch, openrouter-key; phase 5: score, ctxsupport, scoretable, analyze, intext\n probe_openrouter.py one create_v4 call per model through OpenRouter (route checks, plan §5 step 1)\n models.yaml registry: model ids, medium-effort params (D12), prices (checked 2026-10-11);\n `openrouter:` block per model (id, params, pinned provider, served_provider)\n prompts/ create_v1..v4.pt.md, assign_v1..v2.pt.md (pt-BR; see \"Prompts\" below)\n nuggetizer/\n data.py questions, o200k lengths, stratified samples, user prompt\n schema.py pydantic models → strict JSON schemas sent to the APIs\n values.py pt-BR value extraction (R$, %, dates, years); digits_for_words (spelled-out %)\n scoring.py phase 5: per-question scores (V_strict, V, A_strict, A, W, contradictions), paired\n bootstrap / permutation / chapter-cluster comparisons, default pairs\n analysis.py phase 5 without LLM: value checks, citation score, linkage, utilisation, slices,\n perturbation, cross-sets, judge agreement\n intext_citations.py A2: legal citations written in the answer text → acts (regex + aliases + anaphors) →\n corpus documents; scored against the gold references; validity; context classes\n validate.py mechanical checks (plan v2 §3.3, §3.5.1), flags\n known_answer.py known-answer test builders G V Y N D C W E and metrics (plan v2 §5.7)\n planted.py one planted error per question, to measure auditor sensitivity\n report.py report.md: nuggets side by side, validation, self-score, tokens, cost extrapolation\n pilot_report.py report_pilot.md: agreement, 1 vs 2 calls, round trip, audit, known-answer, costs\nnuggets/<run>/ outputs (see \"Outputs\")\n```\n\n## Install and keys\n\n```bash\npython3.12 -m venv .venv # already exists in the repo checkout\n.venv/bin/pip install -r scripts/nuggets/requirements.txt\n```\n\nIf `.venv/bin/pip` is missing (the venv of the other machine's layout), use\n`uv pip install --python .venv/bin/python -r scripts/nuggets/requirements.txt`.\n\n`nuggets.py` loads `.env` (repo root, gitignored) with `python-dotenv`; no shell sourcing is needed.\n\n- **Default route, `--route openrouter`:** only `OPENROUTER_API_KEY=sk-or-v1-...` is needed. The key has a\n credit limit of **$100** (raised from $80 on 2026-10-21; a second cap behind `--budget`) and **expires on 2026-11-20**: renew it before\n then, on both machines. `nuggets.py openrouter-key` prints its limit, usage and expiry (free).\n- **`--route direct`** (the preview and pilot runs, and their caches): `OPENAI_API_KEY`, `GEMINI_API_KEY`\n and `DASHSCOPE_API_KEY` (Alibaba Model Studio, **Singapore** region). Setup: plan v2 §8.\n\n## Commands\n\nAll from the repository root. Global options go **before** the subcommand.\n\n```bash\nP=.venv/bin/python; N=scripts/nuggets/nuggets.py\nO=\"--out nuggets/pilot --sample stratified_30 --budget 5.00\" # example; see \"Costs and the budget cap\"\n\n$P $N --out nuggets/pilot sample # input/questions.jsonl + sample.json (preview_10, stratified_30)\n$P $N $O create --models gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max # --prompt defaults to create_v4\n$P $N $O validate # free; rewrites nuggets.jsonl with values/flags/issues\n$P $N $O selfscore --judge gemini-3.8-flash --sets gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max # --prompt assign_v2\nfor j in gemini-3.1-pro qwen3.8-max gpt-6.1-sol; do\n $P $N $O selfscore --judge $j --sets gpt-6.1-sol # the other judges, primary set only\ndone\n$P $N $O report # nuggets/pilot/report.md\n```\n\nThe rest of the phase 1 pilot, as run (pilot note §1; set names: `<model>.rN` replicate, `.2call`,\n`.repN` repaired, `.planted`):\n\n```bash\n$P $N $O create --models gpt-6.1-sol --replicate 2 # and 3: same-model noise\n$P $N $O importance --source gpt-6.1-sol # 2-call mode → create/gpt-6.1-sol.2call\n$P $N $O align --pairs gpt-6.1-sol:gemini-3.1-pro,gpt-6.1-sol:qwen3.8-max,gemini-3.1-pro:qwen3.8-max\n$P $N $O roundtrip --set gpt-6.1-sol # Flash writes, Qwen checks (check_v2)\nfor a in gemini-3.1-pro qwen3.8-max; do\n $P $N $O audit --set gpt-6.1-sol --auditor $a --others gemini-3.1-pro,qwen3.8-max\ndone\n$P $N $O repair --set gpt-6.1-sol --auditors gemini-3.1-pro,qwen3.8-max --new gpt-6.1-sol.rep1\n$P $N $O validate # then audit/selfscore on .rep1\n$P $N $O known build --set gpt-6.1-sol.rep1\n$P $N $O known judge --set gpt-6.1-sol.rep1 --judge gemini-3.8-flash # and gemini-3.1-pro\n$P $N $O plant --set gpt-6.1-sol.rep1 # then audit the .planted set\n$P $N $O pilotreport # nuggets/pilot/report_pilot.md\n```\n\n- `--sample` names a list in `<out>/sample.json`. `preview_10` = one question per answer-length\n decile (o200k tokens of question + answer, seed 13); `stratified_30` = three per decile, and its\n first pick per decile is `preview_10`. Questions 001 and 003 are the prompt's worked examples and\n are never sampled.\n- `--workers` (default 5) is the concurrency **per model**. `create` runs the models in parallel.\n- `--route` (global, default `openrouter`) picks the route. **Rerunning a command on `nuggets/pilot/` or a\n preview folder needs `--route direct`**: the route enters the cache key, so the OpenRouter route would call\n the API again instead of reading those caches.\n- Several `selfscore` processes may run in parallel on the same `--out`. The ledger is shared, and\n the budget cap reads it before every call.\n\n### Phase 5: scoring RAG answers (`nuggets/scoring/`)\n\n```bash\nA=runs/answers/jua-4b-mixed/irpf; C=runs/contexts/jua-4b-mixed/irpf\nS=\"--out nuggets/scoring --sample all --workers 24 --budget <ledger total + allowance>\"\n$P $N $S score --runs \"$A/*/*/*\" --dry-run # uncached calls and cost (ledger mean per call); then without\n$P $N $S score --runs \"$A/answer_v1/sabia-4/S[12]_budget4000\" --set qwen3.8-max.rep0 # a cross-set\n$P $N $S score --runs \"$A/answer_v1/sabia-4/S[12]_budget4000\" --judge gemini-3.1-pro # a second judge\n$P $N $S ctxsupport --contexts $C/S1_budget4000 $C/S2_budget4000 # nuggets vs the context\n$P $N --out nuggets/scoring --sample all scoretable [--set <set>] # free: tables/<set>/<judge>/<sample>/\n$P $N --out nuggets/scoring --sample all analyze # free, ≈ 8 min: analysis/<set>/<judge>/<sample>/\n$P $N --out nuggets/scoring --sample all intext # free, ≈ 40 s: analysis/<set>/<judge>/<sample>/intext/\n$P $N --out nuggets/scoring --sample stratified_70 --budget <cap> ctxaudit known|corpus|classify # note §10\n```\n\n- `--runs` and `--contexts` take run / context folders or globs relative to the repository root. `--set gold` (the\n default) is `nuggets/gold/v0-auto`; any other name is a set of `nuggets/full/create/`.\n- Abstentions and errors get `not_support` for every nugget, without a judge call. A rerun only adds the questions\n that are missing: labels already in an output folder are kept.\n- Output folders: `score/<set>/<judge>/<run_id>/` and `ctxsupport/<set>/<judge>/<context path>/`, each with\n `labels.jsonl`, `calls.jsonl` and `manifest.json`.\n- Prompts: `assign_v2` for answers, `assign_ctx_v1` for contexts.\n- `intext` (A2, no LLM calls): the in-text legal citations of every run under `runs/answers/` (`--runs <glob>` to\n restrict), one row per cited unit (`intext_citations.csv.gz`), per answer and level (`intext_answers.csv.gz`),\n per run (`intext_citations_runs.csv`), V_strict by citation (`intext_vs_quality.csv`) and the `lexml-linker`\n cross-check (`linker_crosscheck.json`; needs `linkertool` on the PATH, else `--no-linker`). Tests:\n `scripts/nuggets/tests/test_intext_citations.py`. Results: `docs/20261122_194659_a2_in_text_legal_citations_results.md`.\n- Measured cost (Flash flex): $0.0023 per answer, $0.0044–0.0047 per 4k context; Gemini 3.1 Pro $0.0091 per answer.\n\n## OpenRouter route (default)\n\nEvery model has an `openrouter:` block in `models.yaml` (plan `docs/20261020_130829_openrouter_support_plan.md`):\n\n| Model | OpenRouter id | Pinned endpoint | Params |\n|---|---|---|---|\n| `gpt-6.1-sol` | `openai/gpt-6.1-sol` | `openai/flex` (half price) | `reasoning.effort: medium`, strict `json_schema` |\n| `gemini-3.1-pro` | `google/gemini-3.1-pro-preview` | `google-ai-studio/flex` (half price) | same |\n| `gemini-3.8-flash` | `google/gemini-3.8-flash` | `google-ai-studio/flex` (half price) | same |\n| `qwen3.8-max` | `qwen/qwen3.8-max-0902` | `alibaba` (list price; no flex or batch) | `reasoning.max_tokens: 2048`, `json_object` |\n\n- **Pinned:** `only` one endpoint, `allow_fallbacks: false`, `require_parameters: true`,\n `data_collection: deny`. Every reply's upstream provider is checked against `served_provider`; another one\n raises `RouteMismatch` (the call is in the ledger, not in the cache).\n- **Ledger:** columns `route`, `provider_served`, `usd_billed` (OpenRouter's `usage.cost`). The budget cap and the\n reports use `usd_billed` when present, else `usd_standard` (batch rows at half). `usd_standard` stays the\n list price of the direct API, for comparison. An older `costs.csv` gets the new columns (empty) on its first\n new row.\n- **Errors:** HTTP 402 (key limit or balance used up) raises `CreditsExhausted`, not retried. An upstream error\n in an HTTP 200 reply is retried like a 502. `finish_reason: length` is a truncated reply, retried.\n- **No 250/day quota** on Gemini 3.1 Pro: OpenRouter calls Google on its own accounts (do not add our Gemini key\n to OpenRouter as BYOK). **`--batch` is refused on this route**: flex already gives the 50 % discount on\n synchronous calls.\n- Probe (2026-10-21, `nuggets/probe_openrouter/`, $0.125): plan §8.\n\n## Batch mode (direct route only; OpenAI and Gemini Batch APIs, 50 % off)\n\nAny command can run in batch mode with `--route direct`. With the global `--batch`, cache hits are served as usual, and every\nuncached OpenAI or Gemini request is **queued** instead of called. At the end, one job per model is\nsubmitted (`<out>/batches/`), and the command stops **without writing its outputs**. Qwen\n(`openai_compat`, no batch in Singapore) is still called synchronously.\n\n```bash\n$P $N $O --batch create --models gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max # submits the GPT and Gemini jobs\n$P $N --out nuggets/<run> batch wait # polls every 2 min; caches results as they finish\n$P $N $O create --models gpt-6.1-sol,gemini-3.1-pro,qwen3.8-max # same command, no --batch: all cached\n```\n\n- `batch status` lists the jobs; `batch collect` polls once; `batch wait` polls until no job is open\n (jobs finish within 24 h; Gemini expires them after 48 h).\n- **Budget:** a job is billed whole, so the cap is checked **at submission**: ledger + estimated job\n cost (the mean cost of the same role and model in the ledger, else a rough token estimate) must stay\n under `--budget`, or nothing is submitted.\n- **Ledger:** each result is a row tagged `batch:<tag>`. `usd_standard` stays the synchronous price;\n the budget cap and `report_pilot.md` count batch rows at half (`BATCH_DISCOUNT`).\n- A batch result the command's validation rejects (e.g. it misses a nugget number) is called again\n synchronously when the command is rerun.\n- `batches/*.json` (job records) are versioned; `batches/*.jsonl` (inputs, full requests) are gitignored.\n- Gemini 3.1 Pro's **250 requests/day** quota does not apply to batch jobs (their limit is queued tokens:\n 5M for 3.1 Pro at Tier 1, so a full set goes in one or two jobs).\n\nA command that hits a daily quota stops after the other items finish, with `QuotaBlocked`. Completed\ncalls are cached, so rerunning the same command after the reset resumes where it stopped.\n\n## Prompts\n\n| Prompt | Status | Note |\n|---|---|---|\n| `create_v1` | superseded | preview v1 |\n| `create_v2` | **rejected** | R2 \"one nugget per listed object\": GPT over-split illustrative lists (execution note §3) |\n| `create_v3` | superseded | R2 \"follow the answer's structure\"; passed both acceptance checks (execution note §8–§9) |\n| **`create_v4`** | **current; pilot passed** | `create_v3` + pointer rule: a sentence that only delegates to another question gives no nugget (execution note §13; pilot note §2) |\n| `assign_v1` | superseded | penalized the implicit P&R period (R8) |\n| `ctxaudit_classify_v1` | current | cause of an unsupported nugget (phase 5 note §10) |\n| **`assign_ctx_v1`** | **current** | phase 5 context support: nuggets against the retrieved legal texts; PGD instructions not in the texts and another period's value are `not_support` |\n| **`assign_v2`** | **current** | implicit period: a missing exercício 2024 / ano-calendário 2023 is not a defect; another year is `contradicts` |\n| `importance_v1` | tested, not adopted | 2-call mode: importance in a second call (pilot note §4) |\n| `align_v1` | current | cross-set alignment, relation per nugget (`gemini-3.8-flash`) |\n| `roundtrip_write_v1`, `roundtrip_check_v2` | current | round trip; `check_v1` listed missing legal citations as omissions (pilot note §6.2) |\n| `audit_v1` | current | checks C1–C6 of plan v1 §3.4.1, omissions, redundant pairs |\n| `repair_v1` | current | appended to the creation prompt; current nuggets + issues both auditors agree on |\n\n**Rule for prompt examples:** never quote or paraphrase a question of `stratified_30` in a prompt;\nthe sample would then measure leakage. Invent examples (as in `create_v3`/`v4`). Make a new\nversion (`create_vN`) for any change, and keep the old file: manifests and cache keys refer to the\nprompt text.\n\n## Outputs\n\n```\nnuggets/<run>/\n sample.json samples + dataset SHA-256\n input/questions.jsonl prepared questions (gitignored; regenerated by `sample`)\n cache/<sha256>.json raw API response per request (gitignored; back it up, see below)\n costs.csv ledger: one row per API call, retries included\n create/<model>/ nuggets.jsonl, validation.json, calls.jsonl, manifest.json\n selfscore/<judge>/<set>/ assignments.jsonl, calls.jsonl, manifest.json\n report.md\n```\n\nExisting runs: `nuggets/preview/` (v1 prompts), `nuggets/preview_v2/` (rejected `create_v2`,\ncreation only), `nuggets/preview_v3/` (`create_v3` + `assign_v2`), `nuggets/pilot/` (phase 1; extra folders\n`align/`, `roundtrip/`, `audit/`, `known/`, and `report_pilot.md`), `nuggets/probe_openrouter/` (OpenRouter\nroute probe, `probe.jsonl`). A full copy, caches included,\nis in `../nuggets_backup_20261012_132700/` (outside the repo). From the pilot on, the caches go to\na private HF dataset repo at the end of each phase (resolution note §3.2).\n\n**Cache semantics.** The cache key is the hash of (provider, model id, params, system prompt, user\nprompt, schema). Rerunning a command is free and returns the same responses. A **new run with the\nsame prompt in a new `--out`** calls the API again, because each `--out` has its own cache. The\nv3 cache cannot serve `create_v4` (different prompt text).\n\n## Costs and the budget cap\n\n- Every call is logged to `<out>/costs.csv` at the **standard** (synchronous list) price, and, on the\n OpenRouter route, with the **billed** cost (`usd_billed`, flex discount and OpenAI cache writes included).\n- `--budget USD` makes the client refuse any call once the ledger of that `--out` reaches the cap.\n It is checked before every call; concurrent workers can overshoot by at most one call each. The\n cap is **cumulative per `--out`**: for a second step in the same folder, set it to the amount\n already spent plus the new allowance.\n- **Always pass `--budget`**, and stop and report if a run hits it or costs more than expected.\n- **Gemini 3.1 Pro has a daily quota of 250 requests per model** on our tier. The client raises\n `QuotaExhausted` at once (no backoff); `known judge` writes partial results and a rerun completes them\n from the cache. Full runs with 3.1 Pro need the Batch API (pilot note §9.1). The reset time is unclear\n(the 429 points to 00:00 UTC, but the quota stayed blocked until about 03:25 UTC), so do not plan around it.\n- Measured on the pilot (`stratified_30`, standard prices): pilot note §10 and `report_pilot.md` §1, §9.\n- Measured on `preview_10` with `create_v3`/`assign_v2` (standard prices, per 10 questions):\n creation GPT $0.111, Gemini 3.1 Pro $0.327, Qwen3.8-Max $0.146; self-score layout above $0.369.\n So **one full creation + self-score loop on `stratified_30` is ≈ $2.9**. Reasoning length varies\n between runs by up to ≈ 20 % (Gemini Pro). Phase 1–4 estimate: execution note §11.\n\n## Validator codes\n\n| Code | Severity | Meaning |\n|---|---|---|\n| `number_not_in_source`, `year_not_in_source` | error | a number or year in the nugget is not in the question or answer (R9; 2023/2024 are allowed as the P&R period) |\n| `span_not_found` | error | `source_span` not found in the answer |\n| `duplicate_of` | error | same normalized text as another nugget |\n| `no_vital`, `verdict_count` | error | no vital nugget; a Sim/Não answer without exactly one `resposta_direta` |\n| `enum_item_uncovered` | error | an enumerated item of the answer is not covered by any span |\n| `span_fuzzy` | warning | span matched only approximately (≥ 85 %) |\n| `backreference` | warning | \"esse\", \"tal\", \"o referido\"… (self-containment proxy; often resolved inside the nugget) |\n| `value_without_period` | warning | a value without a year or period expression (R8) |\n| `pointer_in_text` | warning | \"pergunta NNN\" in a nugget's text (`create_v4` forbids it) |\n| `pointer_uncovered` | warning | an uncovered sentence with a pointer: **expected** under `create_v4`; check it only for a missed content part of a mixed sentence |\n| `unit_uncovered` | warning | another uncovered sentence (possible omission) |\n| `verdict_polarity`, `many_nuggets` | warning | a \"Não\" verdict nugget without a negation; more than 40 nuggets |\n\nFlags (filled by the validator from the answer, copied to every nugget): `has_pointer`, `temporal` (the\nanswer states an R$, % or date value; the \"provision amended after 2024-05-03\" half of plan v2 §3.1 is not\nimplemented), `short_answer` (< 80 characters), `procedimento_pgd` (ficha / PGD / campo / código NN).\n\nCoverage rule: a sentence counts as covered when spans cover ≥ 50 % of it; an enumerated item from 30 %\n(spans may leave out a long parenthetical); every exact occurrence of a span counts (answers repeat items\nverbatim). Pilot note §2.1.\n\n## Provider notes (direct route, checked 2026-10-12; OpenRouter: plan §8)\n\n- `gpt-6.1-sol`: `reasoning.effort: medium`, strict JSON schema, no `temperature`. It reasons very\n little on this task (≈ 140 tokens per creation call). The 3.1k-token prompt prefix is cached\n automatically, at $0.10/M.\n- Gemini (`gemini-3.1-pro-preview`, `gemini-3.8-flash`): `thinkingConfig.thinkingLevel: \"medium\"`,\n `responseJsonSchema`. No implicit caching was reported for the prefix. Flash prices double on\n 2027-01-01.\n- `qwen3.8-max-0902` (pinned snapshot): `enable_thinking` with `thinking_budget: 2048`.\n **`response_format: json_schema` returned malformed JSON**, so `json_object` + pydantic + retry is\n used. The context cache hits automatically.\n\n## Before phase 2: what is still missing\n\n1. ~~Batch API submit/collect~~ **done** (see \"Batch mode\").\n2. Known-answer builders (phase 4, pilot note §7): W without near-duplicate neighbours; D/C tests whose fact\n is restated elsewhere; V with another period's value from the corpus; the Flash rewrite for conditions\n that are not delimited by punctuation.\n3. `--dry-run`, a `fake` provider and tests (plan v2 phase 0 gate). Done in part: the OpenRouter provider has\n tests against mocked replies (`.venv/bin/python -m pytest scripts/llm_client/tests`).\n4. The corpus half of the `temporal` flag.\n\nDecisions: `docs/20261013_103834_nuggetization_open_decisions.md`. Closed: `create_v4`, one call, gate\nthresholds (+ \"flagged by both\" on any check, each auditor ≥ 80 % of planted errors). Open: phase 4 builder fixes, cache backup to\nthe private HF repo, and, still from the plan, the optional \"expanded\" score on `has_pointer` questions and\nthe open-weight Qwen judge.\n","scripts/rag/README.md":"# RAG pipeline — BR-TaxQA-R v2.0 segmentation experiment\n\nTests whether **hierarchical segmentation** of the legal documents cited by the *Perguntas e\nRespostas IRPF 2024* gives better chunks for answering its questions. This directory holds the\npipeline code. Design: `docs/20260927_204356_rag_pipeline_implementation_plan.md`.\n\n**Status: Phase 1 (retrieval and its evaluation, \"the legal-provision test\"), Phase 2 (generator\ncontexts, `context`) and Phase 3 (answer generation, `generate` / `run`; pilot on `stratified_30`).**\nPhase 3 run and decisions: `docs/20261023_110952_rag_phase3_generation_pilot.md`. Phase 2 run and decisions:\n`docs/20261021_210251_rag_phase2_contexts_execution.md`; the first evaluation's plan, costs and grounding\nsafeguards: `docs/20261021_194457_first_rag_evaluation_readiness_costs_and_grounding.md`.\n\n## Stages\n\n```\nchunks + vectors ──► R retrieve ──► rankings ──► RE evaluate ──► metrics, report (Phase 1)\n │\n └──► C context ──► G generate ──► answers ──► nugget scoring\n (Phase 2) (Phase 3) (scripts/nuggets/)\n```\n\nStages talk only through files, so each one can be rerun, replaced or released on its own.\n\n| Stage | Input | Output |\n|---|---|---|\n| R — retrieve | `segmented/chunks_all.csv.gz`, `embeddings/<model>/…`, `dataset/questions.jsonl` | `runs/retrieval/<model>/<instruction>/<strategy>/rankings.csv.gz` |\n| RE — evaluate | rankings, chunks, `dataset/references.jsonl` + `documents.jsonl` | `runs/retrieval/<model>/<instruction>/eval/<eval_id>/…` |\n| C — context | rankings, chunks (with text), dataset, `prompts/context_v2.pt.md` | `runs/contexts/<model>/<instruction>/<context_id>/contexts.jsonl.gz` |\n| G — generate | contexts, `dataset/questions.jsonl`, `llms.yaml`, `prompts/answer_v1.pt.md` | `runs/answers/<model>/<instruction>/<prompt>/<llm>/<context_id>/answers.jsonl` |\n\n## Install\n\n```bash\npython3.12 -m venv .venv\n.venv/bin/pip install -r scripts/rag/requirements.txt\n```\n\n## Quick start\n\nFrom the repository root, with the dataset, the chunks and the vectors in place (built by the\nrepository scripts or downloaded from the Hub):\n\n```bash\nR=scripts/rag/rag.py\n.venv/bin/python $R check --embedding jua-4b-mixed # input checks only\n.venv/bin/python $R retrieve --embedding jua-4b-mixed # S1, S2, S3, S2c, S4; top-1000 (≈20 s)\n.venv/bin/python $R evaluate --retrieval runs/retrieval/jua-4b-mixed/irpf # ≈15 s\n.venv/bin/python $R compare --retrieval runs/retrieval/jua-4b-mixed/irpf --a S1 --b S2\n```\n\nThen read `runs/retrieval/jua-4b-mixed/irpf/eval/either_containment_merge_skip/report.md`.\n\nPhase 2, the generator contexts (≈ 70 s for the 12 pilot sets × 715 questions, half of it loading):\n\n```bash\n.venv/bin/python $R context --retrieval runs/retrieval/jua-4b-mixed/irpf # the pilot sets (below)\n.venv/bin/python $R context --retrieval runs/retrieval/jua-4b-mixed/irpf --sets S2@budget=16000,oracle@budget=8000\n.venv/bin/python $R show-context --context runs/contexts/jua-4b-mixed/irpf/S2_budget4000 --questions 012,345\n```\n\nPhase 3, the answers (keys in the repository-root `.env`: `MARITACA_API_KEY`, `OPENROUTER_API_KEY`). Size\nevery grid with `--dry-run` first; `--budget` (USD) caps the total of the ledger `runs/costs.csv`:\n\n```bash\n.venv/bin/python $R run --experiment scripts/rag/experiments/pilot.yaml --dry-run # calls, cached, est. cost\n.venv/bin/python $R run --experiment scripts/rag/experiments/pilot.yaml --budget 18\n.venv/bin/python $R generate --contexts runs/contexts/jua-4b-mixed/irpf --sets S2_budget4000 --llms sabia-4 \\\n --sample all --budget 30 # one run, all questions\n.venv/bin/python $R show-answers --run runs/answers/jua-4b-mixed/irpf/answer_v1/sabia-4/S2_budget4000 --questions 350\n```\n\nOptions (every subcommand has `--help` with an example):\n\n| Subcommand | Main options |\n|---|---|\n| `check` | `--embedding` (required), `--instruction` (default `irpf`, or the only one), `--no-hash` |\n| `retrieve` | `--strategies S1,S2,S3,S2c,S4`, `--top-n 1000`, `--exclusions <yaml> \\| none` (default `corpus_exclusions.yaml`), `--run-name` (default: the instruction), `--force` (replace a run made with other settings) |\n| `evaluate` | `--annex-rule {either,main_first}`, `--budgets 1000,…,16000`, `--unit-ks`, `--raw-ks`, `--dedup {containment,containment_merge,none}`, `--overflow {skip,stop}`, `--comparisons S1:S2,S2:S3`, `--eval-id`, `--token-metrics` |\n| `compare` | `--a`, `--b`, `--views budget,unit,raw`, `--eval-id` |\n| `report` | `--eval <eval dir>` (regenerate `report.md`) |\n| `context` | `--sets` (specs below), `--dedup`, `--overflow`, `--order {score,document}`, `--template context_v2`, `--annex-rule`, `--oracle-strategy S1`, `--seed`, `--eval-id`, `--no-token-count`, `--force` |\n| `show-context` | `--context <set dir>`, `--questions`, `--no-text`, `--max-chars` |\n| `generate` | `--contexts <folder>`, `--sets <context ids>`, `--llms <llms.yaml names>`, `--sample stratified_30 \\| all \\| 001,002`, `--prompt answer_v1`, `--closed-prompt answer_closed_v1`, `--budget`, `--dry-run`, `--workers 8`, `--registry`, `--force` |\n| `run` | `--experiment <yaml>` (the same settings as a versioned file), `--sample`, `--budget`, `--dry-run` |\n| `show-answers` | `--run <answer run dir>`, `--questions` |\n\nInput locations default to the repository layout and can be changed with `--chunks`, `--dataset`,\n`--embeddings-dir`, `--runs-dir` and `--strategies-file`.\n\n## Corpus exclusions\n\n`corpus_exclusions.yaml` lists documents of the dataset that are **not retrieval candidates** (rule: documents\nrevoked as a whole before the P&R date, 2024-05-03). They stay in `dataset/`, `segmented/` and `embeddings/`;\n`retrieve` drops their chunks from every strategy and records the list in its manifest, from which `evaluate`\n(their gold items: `unreachable_reason = excluded_from_corpus`) and `context` (oracle) take it. Now excluded:\n`decreto_3000_19990326` (RIR/1999). The run without exclusions is kept as an ablation:\n`retrieve --exclusions none --run-name irpf_with_rir1999`. Analysis and audit:\n`docs/20261022_203625_corpus_exclusion_revoked_rir1999.md`.\n\n## What is measured\n\n**Strategies** (`strategies.yaml`): the chunk types each one indexes and the text variant it\nprefers per unit (`variantes`; caput plan `docs/20261005_184116_*`). Paragraph-family chunks have a\n`base` text (article label + paragraph) and a `caput` text (with the caput's opening sentence).\nCounts of the 2026-10-08 chunk set (`d1b9cf7e…`):\n\n| | Tipos | Variants | Chunks | Texts |\n|---|---|---|---:|---:|\n| S1 | ART, DSP, TXT, TAB | base | 26,364 | 26,323 |\n| S2 | S1 + CPT, PAR, INC, ALI, ITE | base | 83,496 | 83,330 |\n| S3 | S2 + PRT, LIV, TIT, SBT, CAP, SEC, SSC | base | 88,600 | 88,434 |\n| S2c | as S2 | caput, base | 83,496 | 80,325 |\n| S4 | as S3 | caput, base | 88,600 | 85,429 |\n\nA `caput` row is indexed instead of its base twin, never next to it; the evaluation treats only the\nindexed rows as members of a strategy (`strategies.member_mask`).\n\nVectors are stored per unique text, so a ranked item is **one text**. It is represented by its\ncoarsest chunk (`unit_precedence`), and the other chunks with that text are its aliases.\n\n**Retrieval** (`dense`): exact cosine over the stored L2-normalized vectors (brute force, no ANN\nindex). Ties are broken by `text_id`. One scoring pass serves all strategies.\n\n**Gold** (`references.jsonl`, resolved references only), at three levels:\n\n| Level | Gold item | A chunk hits it when… |\n|---|---|---|\n| document | `document_id` | it belongs to the document's main or annex LexML file |\n| article | `(document_id, article_id)` | it is (part of) the article, or a grouping chunk that contains it. Annex rule `either`: article N of the main file or of an annex; `main_first`: the annex only when the main file lacks it |\n| provision | `(document_id, fragment_id)`, e.g. `art1_cpt_inc10` | **full**: a `cobre_ids` id equals the fragment or is its ancestor, or a grouping chunk contains it, or all parts of a split article that hold it are retrieved; **partial**: the chunk holds only part of it |\n\n**Views** (the headline is the token budget, because raw k is not comparable across strategies):\n\n| View | Ranked list | Cutoffs |\n|---|---|---|\n| `budget` | Texts selected by `ragpipe.context.select`, in rank order: containment de-duplication, then filled up to B Qwen3 tokens (`n_tokens_qwen3`), skipping texts that do not fit | 1k, 2k, 4k, 8k, 16k |\n| `unit` | Ranking projected to distinct documents / articles (a grouping chunk stands for the articles it contains) | 1, 3, 5, 10, 20, 50, 100; MRR and nDCG@10 at cutoff `-` |\n| `raw` | Texts as retrieved (diagnostic) | 1, 5, 10, 20, 50, 100, 1000 |\n| `oracle` | Can any chunk of the strategy hit the item at all (the ceiling)? | `-` |\n\n**Metrics** per question, averaged over questions with gold at the level: `recall`, `hit`,\n`full_recall`, `partial_recall` (provision), `mrr`, `ndcg@10`, `context_precision` (share of context\ntokens from texts that hit gold), `context_tokens`, `context_texts`. Every metric is reported over\nall resolved gold (`gold=all`) and over the gold the strategy can reach (`gold=reachable`), and per\nslice: `all`, `explicit`/`embedded` (origin of the reference), `statutory`/`non_statutory`,\n`annex_A` (gold in a category-A annex, e.g. the RIR/2018), `whole_article`/`sub_article`\n(provision level) and the P&R chapter (`data/pr_irpf_2024_chapters.csv`).\n\n**Token-weighted metrics** (`--token-metrics`, eval id `v3_…`; `ragpipe/tokens.py`, needs\n`segmented/unit_tokens.csv.gz` from `scripts/segmentation/unit_tokens.py`). In the budget view, at the article and\nprovision levels, each context's tokens are split into gold text (the distinct gold units shown, as content or\non an ancestor path, counted once), off-gold content and scaffold (prefixes, grouping names, path text outside\nthe gold, repeats). This gives `token_precision`, `noise_share` and `scaffold_share`, which add up to 1, and\n`token_recall` / `item_coverage` (shown gold tokens ÷ gold tokens, items weighted by size / averaged). Design\nand results: `docs/20261122_192653_a1_token_weighted_provision_metric_results.md`.\n\n**Paired comparisons** (S1 vs S2, S2 vs S3): mean per-question difference, with a 95 % paired\nbootstrap CI (10,000 resamples, seed 13) and a two-sided sign-flip permutation p-value.\n\n## Contexts (Phase 2)\n\nA **context set** is one way of building the context of every question (`--sets`, comma list):\n\n| Spec | Context id | Context |\n|---|---|---|\n| `S2@budget=4000` | `S2_budget4000` | the strategy's ranking cut by the budget selection (containment de-duplication, `skip` overflow): **the same texts as the evaluation's budget view** |\n| `S3@k=10` | `S3_k10` | the first k texts after de-duplication |\n| `closed_book` | `closed_book` | empty: what the generator knows without retrieval |\n| `oracle@budget=4000` | `oracle_budget4000` | the question's gold articles (rules G1–G3, annex rule) as S1 article units, plus the chunks of gold documents with no gold article; ordered by S1 rank (unranked after, in file order), cut by the budget. A gold document none of whose gold articles is matchable (e.g. a treaty's \"art. IX\") adds its chunks. Empty for the 119 questions without resolved gold |\n| `wrong:S2@budget=4000` | `wrong-S2_budget4000` | the S2 context of a **donor** question: another P&R chapter, no shared gold document, no chunk of the question's gold documents in the donor context (seeded permutation). Control for answers from the model's own knowledge |\n\nThe default `--sets` is the pilot grid: S1, S2, S3, S2c, S4 at 4k; S1, S2 at 2k and 8k; closed-book;\noracle at 4k; wrong S2 at 4k. Non-default options add a suffix to the id (`S2_budget4000_order-document`).\n\n**Rendering** (`--template`, default **`context_v2`**, `prompts/context_v2.pt.md`): one block per text,\njoined by a blank line:\n\n```\n[Documento 1] INSTRUÇÃO NORMATIVA Nº 1.500, DE 29 DE OUTUBRO DE 2014 — Receita Federal do Brasil — Art. 90 (parte 1 de 2)\nEmenta: Dispõe sobre normas gerais de tributação relativas ao Imposto sobre a Renda das Pessoas Físicas.\nArt. 90. Podem ser considerados dependentes: I – o cônjuge; …\n\n[Documento 5] INSTRUÇÃO NORMATIVA Nº 1.500, DE 29 DE OUTUBRO DE 2014 — Receita Federal do Brasil — Art. 90 (parte 2 de 2)\nArt. 90. Podem ser considerados dependentes: § 7º …\n```\n\nThe header is the document title, the issuing body when the title lacks it (RFB/SRF acts), the annex\nlabel for annex chunks (e.g. `Anexo 17 – ANEXO IX LIMITES ANUAIS …`), the chunk's citation path\n(`citacao`) and `(parte p de n)` for a split article. The chunk's `[ Epígrafe | Ementa | Anexo ]` prefix\nis removed from the text; the ementa is shown once per document, on its first block. `context_v1` keeps\nthe full chunk text (prefix included) under the header, with `Anexo` alone for annexes.\nThe budget counts the full chunk texts (`n_tokens_qwen3`), so the selection does not depend on the\ntemplate; the rendered Qwen3 count is in each line (`rendered_tokens_qwen3`). At 4k a context renders to\n≈ 3.8k tokens with `context_v2` and ≈ 4.45–4.6k with `context_v1`.\n\n**De-duplication** (`--dedup`, also an `evaluate` option): **`containment_merge` (default since 2026-10-21)**\ndrops a text inside an already selected chunk, and lets a parent ranked *after* its selected children\nreplace them (in the first child's place; it needs only its extra tokens), so no text repeats.\n`containment` (the Phase 1 rule, eval `v2d_either_containment_skip`) keeps such a parent next to its\nchild, whose text is then sent twice (9–15 % of the 4k context in S2–S4). `none` keeps everything.\nEffect on the legal-provision test: Phase 2 note §4.\n\n**Budget fill** (`--overflow`): texts are taken in rank order and never truncated. With `skip` (default)\na text that does not fit the remaining budget is passed over and filling goes on with lower-ranked texts\nthat fit, until no remaining candidate fits; with `stop` filling ends at the first text that does not fit.\nSo a context is at most the budget: at 4k, 16 tokens short on average (max ≈ 70). The late, small texts\nthat fill the gap can come from deep ranks (S2 4k: median deepest rank 36, p90 333), but they carry only\n1–6 % of the context tokens.\n\n**Gold coverage per context** (`gold` field): for each level, the gold items fully (`full`) or partly\n(`any`) held by the context, by the evaluation's rules. For retrieval sets it is checked against the\nevaluation's `budget_full_<B>` (`consistency_with_evaluation` in the manifest: 0 mismatches expected).\nIt is the per-question link between retrieval and answer scores (phase 5).\n\n## Answers (Phase 3)\n\nOne **answer run** = one context set × one generator (`llms.yaml`) × one prompt. Every question of the sample\ngets one call; questions whose context is empty (the oracle of a question without resolved gold) are\n`skipped`. The closed-book set uses `answer_closed_v1`, every other set `answer_v1`.\n\n- **Reply format** (strict JSON schema): `afirmacoes` — claims, each with `fundamentos`\n `[{documento, trecho}]` (context document number and a verbatim quote) — then `abstencao`. The scored\n answer is the claim texts joined in order; no claim means abstention, written as a fixed sentence.\n- **Grounding checks (no LLM):** each quote is looked up in the cited `[Documento n]` block (words in\n order, punctuation and case ignored, an ellipsis may skip text): `ok`, `not_found`, `too_short`\n (< 3 words) or `bad_document`; a claim is *grounded* when one of its quotes is `ok`. Values (R$, %, dates)\n of the answer that are in neither the context nor the question are listed (`values_not_in_context`).\n- **No tools, no web search:** `llm_client` refuses a registry entry with tools / plugins / `:online`, and\n rejects (without retry, logged in the ledger as `rejected:<reason>`) a reply with tool calls, URL\n citations, web search sources, built-in tool executions (Maritaca) or a billed cost above its token cost.\n- **Generators** (`llms.yaml`): Sabiá-4 and Sabiazinho-4 (Maritaca, direct route, temperature 0, BRL prices\n converted with the recorded `fx_brl_per_usd`), GPT-5.6 Terra and Luna (OpenRouter, `openai/flex`,\n reasoning effort `none`; no temperature parameter). DeepSeek entries are disabled here.\n- **Cache:** raw responses in `runs/answers/cache/` (keyed by the request): a rerun is free and gives the\n same file; a run folder refuses another configuration (prompt, generator settings, context set) unless\n `--force`. Lines of other questions already in a run's `answers.jsonl` are kept, so a run can grow from the\n pilot sample to all questions.\n\n## Output formats\n\n`runs/retrieval/<embedding>/<instruction>/`:\n\n| File | Content | In git |\n|---|---|---|\n| `manifest.json` | git commit + dirty flag, command line, SHA-256 of every input, parameters, counts, timings, `config_hash`, input checks | yes |\n| `<strategy>/rankings.csv.gz` | `question_number, rank, text_id, chunk_id, alias_chunk_ids, score` (top-N per question; aliases `;`-separated) | no (Hub) |\n| `eval/<eval_id>/manifest.json` | matcher rules, cutoffs, gold counts, pointer to the retrieval manifest | yes |\n| `eval/<eval_id>/metrics.csv` | `strategy, level, view, cutoff, gold, slice, metric, value, n_questions` | yes |\n| `eval/<eval_id>/comparisons.csv` | `a, b, level, view, cutoff, metric, mean_a, mean_b, diff, ci_low, ci_high, p_permutation, n_questions` | yes |\n| `eval/<eval_id>/reachability.csv` | gold items per strategy × level: reachable, unreachable by reason, G3/G4 counts | yes |\n| `eval/<eval_id>/report.md` | generated tables | yes |\n| `eval/<eval_id>/metrics_by_chapter.csv.gz` | as `metrics.csv`, with `slice = chapter:<name>` | no |\n| `eval/<eval_id>/per_question.csv.gz` | one row per question × strategy × level × view × cutoff × gold set (for other tests) | no |\n| `eval/<eval_id>/per_item.csv.gz` | one row per gold item × strategy: `rank_full`, `rank_any`, `unit_pos`, `budget_full_<B>`, `budget_any_<B>`, reachability flags | no |\n\n`runs/contexts/<embedding>/<instruction>/`:\n\n| File | Content | In git |\n|---|---|---|\n| `summary.csv` | one row per context set: options, counts, mean texts / tokens, gold recall and hit per level, consistency mismatches | yes |\n| `<context_id>/manifest.json` | parameters, input hashes (retrieval manifest, chunks, dataset, template), counts, donor rule, consistency check | yes |\n| `<context_id>/contexts.jsonl.gz` | one line per question: `context_id, question_number, kind, [donor_question], n_texts, context_tokens_qwen3, rendered_tokens_qwen3, rendered_chars, items[{n, text_id, chunk_id, alias_chunk_ids, rank, score, document_id, arquivo, tipo, citacao, tokens_qwen3, fonte}], gold{level: {n, full, any}}, context` | no (Hub) |\n\n`runs/answers/<embedding>/<instruction>/`:\n\n| File | Content | In git |\n|---|---|---|\n| `summary.csv` | one row per answer run: counts, abstention rate, claims, answer length, tokens, quote and claim grounding rates, values not in context, cost | yes |\n| `<prompt>/<llm>/<context_id>/run.json` | generator config (no key), prompt and schema SHA-256, context manifest pointer and SHA-256, counts, `config_hash` | yes |\n| `<prompt>/<llm>/<context_id>/answers.jsonl` | one line per question: `run_id, question_number, answer` (the nugget-scoring contract) + `status, abstained, claims[{texto, fundamentos[{documento, trecho, status}]}], checks, cited_chunk_ids, usage, usd_list, usd_billed, from_cache, model_served, provider_served, cache_key` | yes |\n| `cache/<key>.json` | raw request and response | no (backup / Hub) |\n\n`runs/costs.csv`: one row per API call (all stages), the `llm_client` ledger with `fx_brl_per_usd` for BRL-priced\nmodels.\n\nExample lines:\n\n```\n# rankings.csv.gz\n001,1,3343d23be0d7f974,in_rfb_2178_20240305#167,,0.803779\n# metrics.csv\nS2,provision,budget,4000,all,sub_article,recall,0.376…,…\n```\n\nThe same inputs give byte-identical rankings and metrics (gzip with mtime 0, stable sorting, fixed\nseeds). A run directory refuses to be overwritten by a run with another configuration unless\n`--force` is given.\n\n## Extending\n\n- **A strategy:** add an entry to `strategies.yaml` (the Tipos it indexes, optionally `variantes`\n and the expected chunk count). No code change.\n- **A retriever:** a class with `name`, `info()` and `search(query_ids, candidate_rows, top_n)`\n (`ragpipe/retrievers/base.py`). Override `search_many` to share work across strategies.\n- **An embedding model or instruction:** embed with `scripts/embedding/embed.py`, then\n `retrieve --embedding <slug> --instruction <name>`. Only the documented embedding release files\n are read; the embedding code is not imported.\n\n## Code\n\n```\nrag.py CLI\nstrategies.yaml strategy → Tipo sets, grouping Tipos, unit precedence, expected counts\ndata/ P&R chapter ranges (from the PDF table of contents)\nragpipe/data.py loading of chunks, dataset and embedding outputs; input checks\nragpipe/strategies.py strategy filters, text ↔ chunk aliasing\nragpipe/retrievers/ Retriever protocol, dense retriever\nragpipe/retrieval.py stage R driver\nragpipe/relevance.py gold items and the gold ↔ chunk matcher (shared with answer evaluation)\nragpipe/context.py containment de-duplication, k / budget selection, header and template rendering\nragpipe/exclusions.py corpus exclusion list (corpus_exclusions.yaml) → excluded chunk rows\nragpipe/contexts.py stage C driver: context sets, oracle, wrong-context donors, gold coverage\nragpipe/generation.py stage G driver: registry, prompts, run loop on llm_client, grounding checks, outputs\nllms.yaml generator registry (providers, pinned models, parameters, prices, FX rate)\nexperiments/ versioned experiment files (pilot.yaml)\nprompts/ context_v1/v2.pt.md (context templates; v2 the default); answer_v1.pt.md,\n answer_closed_v1.pt.md (system part, a '<<<USER>>>' line, user part)\nragpipe/metrics.py IR metrics, paired bootstrap / permutation\nragpipe/evaluation.py stage RE driver and aggregation\nragpipe/report.py metrics → markdown\nragpipe/runs.py manifests, hashing, deterministic writing\ntests/ pytest on a fixture corpus with random vectors (no network, no GPU)\n```\n\nRun the tests with `.venv/bin/python -m pytest scripts/rag/tests`.\n\n## License and citation\n\nCode under the repository license; dataset BR-TaxQA-R v2.0 under CC BY 4.0. Citation: to be added\nwith the paper.\n"};