From 396741a108d322040ee30783ab21d7ea21d9206d Mon Sep 17 00:00:00 2001 From: nickvido Date: Fri, 20 Nov 2026 23:18:50 -0500 Subject: [PATCH] Fix section numbers being paired with the wrong section body parseUslmToIr reads each section's number from the non-ordered parse and its heading/content/notes from the order-preserving parse, pairing the two by list index. The non-ordered walk visits a container's hierarchy children (subchapter, part, ...) before its direct
children, while the ordered walk follows document order, so any chapter that mixes the two shifted every following section onto its neighbour's number. Stamp each
start tag with its document position before parsing and pair the two views by that marker instead of by index. On release point 119-73 this took heading/number mismatches from 26-45% of sections (titles 7, 12, 19, 25, 42, 50) to zero. Co-Authored-By: Claude Opus 5.5 --- src/transforms/uslm-to-ir.ts | 36 +++++++--- tests/unit/transforms/section-pairing.test.ts | 71 +++++++++++++++++++ 2 files changed, 99 insertions(+), 8 deletions(-) create mode 100644 tests/unit/transforms/section-pairing.test.ts diff --git a/src/transforms/uslm-to-ir.ts b/src/transforms/uslm-to-ir.ts index d88bca6..b4c72bb 100644 --- a/src/transforms/uslm-to-ir.ts +++ b/src/transforms/uslm-to-ir.ts @@ -7,6 +7,12 @@ const HIERARCHY_TAGS = ['subtitle', 'part', 'subpart', 'chapter', 'subchapter'] const SECTION_BODY_TAGS = ['subsection', 'paragraph', 'subparagraph', 'clause', 'subclause', 'item', 'subitem'] as const; const NOTE_SCOPE_TAGS = new Set(['note', 'notes']); const BLOCK_NOTE_TAGS = new Set(['p', 'section', 'table']); +// Both parsers see the same
elements but walk them in different orders (the non-ordered tree +// groups children by tag, so a chapter's children are visited before its direct
+// children). Each
start tag is stamped with its document position so the two views can be +// paired by identity rather than by list index. +const SECTION_SEQUENCE_ATTRIBUTE = 'data-us-code-tools-section-seq'; +const SECTION_SEQUENCE_KEY = `@_${SECTION_SEQUENCE_ATTRIBUTE}`; const parser = new XMLParser({ ignoreAttributes: false, @@ -91,7 +97,7 @@ interface XmlNode { export function parseUslmToIr(xml: string, xmlPath?: string): ParsedTitleResult { const parseErrors: ParseError[] = []; - const strippedXml = stripBom(xml); + const strippedXml = stampSectionSequence(stripBom(xml)); let document: { uslm?: { title?: XmlNode }; uscDoc?: { meta?: XmlNode; main?: { title?: XmlNode } } }; let orderedDocument: OrderedEntry[]; @@ -132,10 +138,12 @@ export function parseUslmToIr(xml: string, xmlPath?: string): ParsedTitleResult }; let uncodifiedSectionIndex = 0; - const orderedSections = collectOrderedSectionNodes(orderedTitleNode); + const orderedSectionsBySequence = new Map( + collectOrderedSectionNodes(orderedTitleNode).map((entry) => [entry.sequence, entry] as const), + ); - for (const [sectionIndex, { node: sectionNode, hierarchy }] of collectSectionNodes(titleNode).entries()) { - const orderedSectionNode = orderedSections[sectionIndex]; + for (const { node: sectionNode, hierarchy } of collectSectionNodes(titleNode)) { + const orderedSectionNode = orderedSectionsBySequence.get(readSectionSequence(sectionNode)); const sectionNumber = readCanonicalNumText(parseErrors, sectionNode.num, xmlPath, 'section number'); const fallbackSectionNumber = sectionNumber || `uncodified-${++uncodifiedSectionIndex}`; @@ -209,8 +217,20 @@ function findOrderedPath(nodes: OrderedEntry[] | undefined, path: string[]): Ord return current; } -function collectOrderedSectionNodes(titleNode: OrderedEntry[]): Array<{ children: OrderedEntry[]; hierarchy: HierarchyIR }> { - const sections: Array<{ children: OrderedEntry[]; hierarchy: HierarchyIR }> = []; +type OrderedSectionNode = { children: OrderedEntry[]; hierarchy: HierarchyIR; sequence: string | undefined }; + +function stampSectionSequence(xml: string): string { + let sequence = 0; + return xml.replace(/<((?:[\w.-]+:)?section)(?=[\s/>])/g, (_match, tag: string) => `<${tag} ${SECTION_SEQUENCE_ATTRIBUTE}="${sequence++}"`); +} + +function readSectionSequence(sectionNode: XmlNode): string | undefined { + const value = (sectionNode as Record)[SECTION_SEQUENCE_KEY]; + return typeof value === 'string' ? value : undefined; +} + +function collectOrderedSectionNodes(titleNode: OrderedEntry[]): OrderedSectionNode[] { + const sections: OrderedSectionNode[] = []; collectOrderedSectionNodesRecursive(titleNode, {}, sections, false); return sections; } @@ -265,7 +285,7 @@ function collectSectionNodesRecursive( function collectOrderedSectionNodesRecursive( nodes: OrderedEntry[], hierarchy: HierarchyIR, - sections: Array<{ children: OrderedEntry[]; hierarchy: HierarchyIR }>, + sections: OrderedSectionNode[], insideNoteScope: boolean, ): void { for (const entry of nodes) { @@ -288,7 +308,7 @@ function collectOrderedSectionNodesRecursive( if (tag === 'section') { if (!insideNoteScope) { - sections.push({ children: value, hierarchy }); + sections.push({ children: value, hierarchy, sequence: orderedAttributes(entry)?.[SECTION_SEQUENCE_KEY] }); } collectOrderedSectionNodesRecursive(value, hierarchy, sections, insideNoteScope); continue; diff --git a/tests/unit/transforms/section-pairing.test.ts b/tests/unit/transforms/section-pairing.test.ts new file mode 100644 index 0000000..0d59a92 --- /dev/null +++ b/tests/unit/transforms/section-pairing.test.ts @@ -0,0 +1,71 @@ +import { describe, it, expect } from 'vitest'; +import { parseUslmToIr } from '../../../src/transforms/uslm-to-ir'; + +// Regression: section numbers (read from the non-ordered parse) were paired with headings and content +// (read from the order-preserving parse) by list index. The non-ordered walk visits a container's +// / children before its direct
children, so whenever a chapter mixes the two +// every following section got its neighbour's number. Real titles (e.g. 42, 50) were ~1 in 3 affected. +function buildXml(body: string): string { + return ` +
+<num value="50">Title 50</num><heading>WAR AND NATIONAL DEFENSE</heading> +${body} +
`; +} + +function section(num: string, heading: string, text: string): string { + return `
ยง ${num}.${heading}` + + `

${text}

`; +} + +function textOf(value: unknown): string { + return JSON.stringify(value); +} + +describe('section number / body pairing', () => { + it('keeps each section number with its own heading and content when sections precede subchapters', () => { + const xml = buildXml(` +CHAPTER 44NATIONAL SECURITY + ${section('3001', 'Short title', 'alpha text')} + SUBCHAPTER ICOORDINATION + ${section('3002', 'Congressional declaration of purpose', 'bravo text')} + ${section('3003', 'Definitions', 'charlie text')} + + ${section('3004', 'Trailing section', 'delta text')} + PART AMISC + ${section('3005', 'Part section', 'echo text')} + +`); + + const { titleIr, parseErrors } = parseUslmToIr(xml); + expect(parseErrors).toEqual([]); + + const byNumber = new Map(titleIr.sections.map((s) => [s.sectionNumber, s])); + const expected: Array<[string, string, string]> = [ + ['3001', 'Short title', 'alpha text'], + ['3002', 'Congressional declaration of purpose', 'bravo text'], + ['3003', 'Definitions', 'charlie text'], + ['3004', 'Trailing section', 'delta text'], + ['3005', 'Part section', 'echo text'], + ]; + expect(titleIr.sections).toHaveLength(expected.length); + for (const [num, heading, text] of expected) { + const parsed = byNumber.get(num); + expect(parsed?.heading).toBe(heading); + expect(parsed?.identifier).toBe(`/us/usc/t50/s${num}`); + expect(textOf(parsed?.content)).toContain(text); + for (const [, , other] of expected.filter(([n]) => n !== num)) { + expect(textOf(parsed?.content)).not.toContain(other); + } + } + }); + + it('does not leak the internal sequence marker into parsed output', () => { + const xml = buildXml(` +CHAPTER 44NATIONAL SECURITY + ${section('3001', 'Short title', 'alpha text')} +`); + const { titleIr } = parseUslmToIr(xml); + expect(JSON.stringify(titleIr)).not.toContain('section-seq'); + }); +});