@mailwoman/resolver 9.0.0 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +89 -0
  2. package/admin-coherence-passes.ts +435 -0
  3. package/admin-containment.ts +101 -0
  4. package/admin-winner.ts +178 -0
  5. package/backend-capabilities.ts +88 -0
  6. package/bare-toponym-race.ts +129 -0
  7. package/decorate-node.ts +127 -0
  8. package/fold-name.ts +19 -3
  9. package/index.ts +14 -0
  10. package/out/admin-coherence-passes.d.ts +70 -0
  11. package/out/admin-coherence-passes.d.ts.map +1 -0
  12. package/out/admin-coherence-passes.js +327 -0
  13. package/out/admin-coherence-passes.js.map +1 -0
  14. package/out/admin-containment.d.ts +48 -0
  15. package/out/admin-containment.d.ts.map +1 -0
  16. package/out/admin-containment.js +82 -0
  17. package/out/admin-containment.js.map +1 -0
  18. package/out/admin-winner.d.ts +109 -0
  19. package/out/admin-winner.d.ts.map +1 -0
  20. package/out/admin-winner.js +119 -0
  21. package/out/admin-winner.js.map +1 -0
  22. package/out/backend-capabilities.d.ts +37 -0
  23. package/out/backend-capabilities.d.ts.map +1 -0
  24. package/out/backend-capabilities.js +75 -0
  25. package/out/backend-capabilities.js.map +1 -0
  26. package/out/bare-toponym-race.d.ts +55 -0
  27. package/out/bare-toponym-race.d.ts.map +1 -0
  28. package/out/bare-toponym-race.js +110 -0
  29. package/out/bare-toponym-race.js.map +1 -0
  30. package/out/decorate-node.d.ts +24 -0
  31. package/out/decorate-node.d.ts.map +1 -0
  32. package/out/decorate-node.js +103 -0
  33. package/out/decorate-node.js.map +1 -0
  34. package/out/fold-name.d.ts +18 -3
  35. package/out/fold-name.d.ts.map +1 -1
  36. package/out/fold-name.js +19 -3
  37. package/out/fold-name.js.map +1 -1
  38. package/out/index.d.ts +4 -1
  39. package/out/index.d.ts.map +1 -1
  40. package/out/index.js +3 -1
  41. package/out/index.js.map +1 -1
  42. package/out/postcode-country-coherence.d.ts +91 -14
  43. package/out/postcode-country-coherence.d.ts.map +1 -1
  44. package/out/postcode-country-coherence.js +279 -42
  45. package/out/postcode-country-coherence.js.map +1 -1
  46. package/out/postcode-prefix.d.ts +101 -0
  47. package/out/postcode-prefix.d.ts.map +1 -0
  48. package/out/postcode-prefix.js +125 -0
  49. package/out/postcode-prefix.js.map +1 -0
  50. package/out/postcode-shape-coherence.d.ts +113 -0
  51. package/out/postcode-shape-coherence.d.ts.map +1 -0
  52. package/out/postcode-shape-coherence.js +193 -0
  53. package/out/postcode-shape-coherence.js.map +1 -0
  54. package/out/resolve.d.ts +1 -1
  55. package/out/resolve.d.ts.map +1 -1
  56. package/out/resolve.js +592 -410
  57. package/out/resolve.js.map +1 -1
  58. package/out/span-rescore.d.ts +28 -0
  59. package/out/span-rescore.d.ts.map +1 -1
  60. package/out/span-rescore.js +151 -17
  61. package/out/span-rescore.js.map +1 -1
  62. package/out/street-evidence.js +1 -1
  63. package/out/street-evidence.js.map +1 -1
  64. package/out/street-tier.d.ts.map +1 -1
  65. package/out/street-tier.js +28 -5
  66. package/out/street-tier.js.map +1 -1
  67. package/out/toponym-prior.d.ts +139 -0
  68. package/out/toponym-prior.d.ts.map +1 -0
  69. package/out/toponym-prior.js +308 -0
  70. package/out/toponym-prior.js.map +1 -0
  71. package/package.json +98 -7
  72. package/postcode-country-coherence.ts +355 -50
  73. package/postcode-prefix.ts +166 -0
  74. package/postcode-shape-coherence.ts +248 -0
  75. package/resolve.ts +809 -527
  76. package/span-rescore.ts +206 -19
  77. package/street-evidence.ts +1 -1
  78. package/street-tier.ts +31 -5
  79. package/toponym-prior.ts +367 -0
@@ -0,0 +1,166 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Postcode-prefix prior (#31, Mechanism 3) — the partial-code prior for postcodes the full-code
7
+ * gazetteer does not carry. #1480's abstention is the defect: a BT unit with no permissive source
8
+ * behind it (the NI half of Code-Point Open) misses the gazetteer, and the tree contributes
9
+ * NOTHING for it — no country scope, no district, no coordinate. This module derives the code's
10
+ * PREFIX and probes the PFX1 index (`postcode-prefix-<cc>.bin`), so the resolve "abstains on the
11
+ * UNIT and still contributes its DISTRICT": the node resolves from the prefix's centroid and/or
12
+ * ancestry, whichever the artifact carries.
13
+ *
14
+ * The index is a structural type (`PostcodePrefixIndexLike`, declared in `core/resolver/types.ts`),
15
+ * injected by the pipeline and never imported from `@mailwoman/neural` — B3-5: the probe touches
16
+ * zero model inputs. The loader lives in `@mailwoman/neural/postcode-prefix-index.ts` (PFX1 format:
17
+ * magic, header, dictionary, quantized i16 coordinates, `radiusP95Km`, ancestry); the resolver
18
+ * side only defines the derivation law and the probe.
19
+ *
20
+ * ## The derivation law (per artifact country)
21
+ *
22
+ * - **GB** — the OUTWARD code: the compact (whitespace-stripped) form minus its trailing 3 unit
23
+ * characters ("SW1A 2AA" → "SW1A", "BT9 5GS" → "BT9"). Never a greedy regex — the unit is
24
+ * exactly 3 chars in the compact form, and `outwardOf` in `mailwoman/gazetteer-pipeline/
25
+ * postcode-prefix.ts` is the build-side twin of this law.
26
+ * - **US** — the 3-digit section ("94043" → "940"). M-3 measured 3 digits as the first length
27
+ * where the ZIP prefix stops being free (145 km p95 median); a 5-digit artifact would be the
28
+ * full code the gazetteer already carries. No US artifact ships yet (B3-4 needs a ZCTA
29
+ * acquisition) — the branch exists so the law is tested before the data.
30
+ * - **Anything else** — abstain (null).
31
+ *
32
+ * ## The probe's country gate
33
+ *
34
+ * The index is country-specific EVIDENCE: it is only probed when its `country` matches the
35
+ * query's country scope (or the scope is absent). A GB index must not speak under a US scope —
36
+ * the pipeline passes the locale's index, and the walk's country filter is the caller's declared
37
+ * universe.
38
+ *
39
+ * ## Metadata contract (what the node carries afterward)
40
+ *
41
+ * - `postcode_prefix` — the prefix string that resolved it.
42
+ * - `postcode_prefix_ancestors` — the ancestry the prefix asserts (coarsest-first; GB outward
43
+ * nodes carry country → constituent-country → district).
44
+ * - `postcode_prefix_radius_p95_km` — the artifact's measured p95 radius, when the node carries a
45
+ * coordinate (M-3's receipt: a 1-digit US band and a GB outward code differ by 200×; never read
46
+ * a coordinate without its radius).
47
+ * - `coordinate_source: "postcode_prefix"` — ONLY when the node actually carries a coordinate.
48
+ * The ancestry-only tier (NI's 80 BT districts) stays coordinate-free — the meaning-of-zero
49
+ * rule, and the half that decides B3-3: inventing a BT centroid would reproduce the `BT3 9QQ` →
50
+ * Sheffield defect #1480 just fixed.
51
+ *
52
+ * **D-rule: opt-in behind `ResolveOpts.postcodePrefixPrior`, default-OFF** (the PCN1 posture:
53
+ * data + loader + offline probe, no decode wiring; the header ships without `delta` until a
54
+ * calibration measures one). Bars: B3-2 (≥60% of held-out units within 10 km, zero worse than the
55
+ * abstention arm), B3-3 (NI ≥95% country scope GB + NIR ancestry + correct district named, 0%
56
+ * coordinate), B3-5 (structural — no model inputs touched).
57
+ */
58
+
59
+ import type { PostcodePrefixIndexLike, PostcodePrefixNode, ResolvedPlace } from "@mailwoman/core/resolver"
60
+
61
+ /**
62
+ * A resolved place that may carry NO coordinate. `ResolvedPlace` requires `lat`/`lon` (every gazetteer row has a value,
63
+ * even the 0,0 unlocated sentinel), and the prefix prior's ancestry-only tier must express absence as `undefined`
64
+ * instead — B3-3: inventing a centroid would reproduce the `BT3 9QQ` → Sheffield defect #1480. `decorateNode` copies
65
+ * `lat`/`lon` onto the node verbatim, so an undefined coordinate stays absent on the node — the meaning-of-zero rule.
66
+ * Widened ONLY at this seam: gazetteer places (always coordinate-bearing) remain plain `ResolvedPlace`.
67
+ */
68
+ export type CoordinateOptionalPlace = Omit<ResolvedPlace, "lat" | "lon"> & { lat?: number; lon?: number }
69
+
70
+ /**
71
+ * The MINIMUM compact code length for a GB outward derivation — a shorter code has no 3-character unit to strip ("B3"
72
+ * is a GB area, not a unit-bearing code).
73
+ */
74
+ const MIN_GB_OUTWARD_CODE_LENGTH = 5
75
+
76
+ /**
77
+ * The MINIMUM code length for a US section derivation.
78
+ */
79
+ const MIN_US_SECTION_CODE_LENGTH = 3
80
+
81
+ /**
82
+ * Derive the prefix the index is keyed by, per the artifact's own country law. Returns null (abstain) for a country
83
+ * with no derivation law, or a code too short to carry a prefix.
84
+ */
85
+ export function derivePostcodePrefix(code: string, country?: string): string | null {
86
+ if (!code || !country) return null
87
+
88
+ const compact = code.replaceAll(/\s+/g, "")
89
+
90
+ switch (country.toUpperCase()) {
91
+ // The outward-code law: compact minus the trailing 3 unit characters ("SW1A2AA" → "SW1A",
92
+ // "BT93GS" → "BT9"). Exactly 3 — never a greedy regex, the build-side twin is `outwardOf`.
93
+ case "GB":
94
+ return compact.length >= MIN_GB_OUTWARD_CODE_LENGTH ? compact.slice(0, -3) : null
95
+ // The 3-digit sectional centre ("94043" → "940"). Deliberately looser than the build side, which
96
+ // requires a real ZIP shape: a probe for something that is not a code simply misses, and a reader
97
+ // that re-derived the writer's validation would be a second copy of it.
98
+ case "US":
99
+ return compact.length >= MIN_US_SECTION_CODE_LENGTH ? compact.slice(0, 3) : null
100
+ default:
101
+ return null
102
+ }
103
+ }
104
+
105
+ /**
106
+ * The outcome of a successful prefix probe.
107
+ */
108
+ export interface PostcodePrefixProbeResult {
109
+ /**
110
+ * The prefix string that hit.
111
+ */
112
+ prefix: string
113
+ /**
114
+ * The index node — its `ancestors` and optional coordinate/radius are the prior's payload.
115
+ */
116
+ node: PostcodePrefixNode
117
+ }
118
+
119
+ /**
120
+ * Probe the index for `code`'s prefix. Two abstention gates, in order: the index's country must match the query's
121
+ * country scope (or the scope is absent), and the derivation law must yield a prefix the index carries. Returns null to
122
+ * abstain — never throws, never guesses.
123
+ */
124
+ export function probePostcodePrefix(
125
+ code: string,
126
+ index: PostcodePrefixIndexLike,
127
+ queryCountry?: string
128
+ ): PostcodePrefixProbeResult | null {
129
+ const indexCountry = index.country?.toUpperCase()
130
+
131
+ // Country gate: the index is evidence FOR its own country only. A GB index under a US scope stays
132
+ // silent — the walk's country filter is the caller's declared universe.
133
+ if (queryCountry && indexCountry && queryCountry.toUpperCase() !== indexCountry) return null
134
+
135
+ const prefix = derivePostcodePrefix(code, indexCountry)
136
+
137
+ if (!prefix) return null
138
+
139
+ const node = index.probe(prefix)
140
+
141
+ return node ? { prefix, node } : null
142
+ }
143
+
144
+ /**
145
+ * Build the synthetic `ResolvedPlace` a prefix hit resolves a `postalcode` node to. `id: 0` — it is NOT a gazetteer row
146
+ * (the same sentinel `applyPostcodeConsistency` uses for its displaced place, resolve.ts) — and the coordinate is
147
+ * present ONLY when the node carries one, so an ancestry-only hit stays coordinate-free by construction (B3-3's 0%
148
+ * half).
149
+ */
150
+ export function postcodePrefixResolvedPlace(
151
+ prefix: string,
152
+ node: PostcodePrefixNode,
153
+ index: PostcodePrefixIndexLike
154
+ ): CoordinateOptionalPlace {
155
+ return {
156
+ id: 0,
157
+ name: prefix,
158
+ placetype: "postalcode",
159
+ // `""` = country unknown — the same empty-string convention the candidate backend uses for a row
160
+ // whose country_id resolves to nothing.
161
+ country: index.country?.toUpperCase() ?? "",
162
+ ...(node.lat !== undefined && node.lon !== undefined ? { lat: node.lat, lon: node.lon } : {}),
163
+ score: 0,
164
+ exactMatch: false,
165
+ }
166
+ }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Postcode-shape coherence (#31, Mechanism 1) — shape as CONFIDENCE and EXCLUSION, downstream of the
7
+ * siblings. The fifth member of the joint-consistency coherence family (after `applyAdminCoherence`
8
+ * #263, `applyExplicitCountryCoherence` #822, `applyRegionCountryCoherence`, and
9
+ * `findPostcodeCountryScope` #42/#1477), and the only one that is pure-sync and backend-free:
10
+ * everything it needs is `candidateSystemsForPostcode` plus the tree.
11
+ *
12
+ * The defect (M-1, `docs/superpowers/plans/2026-08-05-postcode-structure-arc.md`): the decoder
13
+ * sometimes tags a HOUSE NUMBER as `postcode` when its digits form a foreign postcode shape —
14
+ * "1200" in "Twin Peaks Golf Course, 1200 Cornell Dr, Longmont, CO 80503" is accepted only by the
15
+ * AU/NZ 4-digit shape, while every sibling placetype says US. The shape alone cannot say a code is
16
+ * foreign (49/100 Gauntlet codes are accepted by more than one system, 10 by none), so this pass
17
+ * never reads the shape as country evidence by itself — it INTERSECTS each span's candidate systems
18
+ * with the systems the SIBLINGS already assert, and only a confident sibling set can demote.
19
+ *
20
+ * ## The rule (three outcomes, per span)
21
+ *
22
+ * 1. **Intersection non-empty → CONFIRMED.** Stamp `postcode_shape_systems` (the narrowed
23
+ * intersection, upper-case). Additive metadata only — resolution is byte-identical (B1-1). The
24
+ * same intersection narrows `findPostcodeCountryScope`'s candidate list when the caller threads
25
+ * it (a pure subset of codex's shape candidates — safe by construction).
26
+ * 2. **Intersection empty + confident siblings → EXCLUDED.** A digit-only span is demoted to
27
+ * `house_number` (the correct sibling tag — B1-2's "correct sibling tag surviving"); a
28
+ * letter-bearing span keeps its tag and gets `postcode_shape_excluded: true` instead (the
29
+ * compound-split corner — "15 07691" — is #942 postal-compound-recovery territory, out of
30
+ * scope). Either way the span's contribution to the resolve is stripped: `firstPostcodeValue`,
31
+ * the walk's postcode lookup, and the post-walk postcode passes all skip excluded spans.
32
+ * 3. **No confident siblings → ABSTAIN** (the `postcode-country-coherence.ts:269` posture
33
+ * verbatim). A shape no codex system recognizes (the 10/110 slice-less codes) also abstains —
34
+ * an empty candidate set is no evidence either way.
35
+ *
36
+ * ## What counts as a sibling signal
37
+ *
38
+ * - The **country node**, via `matchCountry`, territory-mapped: PR/VI/GU/MP/AS are USPS
39
+ * abbreviations (`codex/us/state.ts`), so a "Puerto Rico" token speaks for `us` — the mapping
40
+ * that protects the true postcode in "Ponce, 00716, Puerto Rico".
41
+ * - The **region node**, via `matchSubdivision` (US states + CA provinces; the US-first tiebreak
42
+ * that makes "CA" mean California is `matchSubdivision`'s own), plus the region's
43
+ * `country_hint` metadata stamp (`mailwoman/region-recognition.ts` writes it on 2-letter US
44
+ * state abbreviations).
45
+ * - Signals are filtered to the codex SystemCode universe BEFORE the intersection test. A country
46
+ * with no codex slice (ES, MX, IE, …) can never appear in any candidate set, so an unfiltered
47
+ * signal would make every intersection empty and every span "foreign" — the slice-less filter
48
+ * is the whole reason the JP-shaped "15 07691" span in the ES Portopetro row ABSTAINS rather
49
+ * than false-excludes.
50
+ *
51
+ * Deliberately NOT a signal: a second postcode span. The census's "cross-span" idea fails on the
52
+ * symmetric case — "2000 Sydney NSW, SW1A 2AA London" would exclude BOTH true codes (their systems
53
+ * are disjoint), a regression worse than the defect. Cross-country multi-postcode strings are
54
+ * pathological, and every M-1 span carries a country/region/`country_hint` signal instead.
55
+ *
56
+ * `defaultCountry` is never a signal: it is a LOCALE DEFAULT, not knowledge. B1-3's confound —
57
+ * "Sydney NSW 2000, Australia" reached with a US default must not have its 2000 excluded, and "10
58
+ * Downing Street, London SW1A 2AA" under a US default must not either. Those rows are exactly what
59
+ * `findPostcodeCountryScope` exists to rescue, and an exclusion pass that trusted the default
60
+ * would delete the evidence the country pass needs.
61
+ *
62
+ * ## Evidence posture
63
+ *
64
+ * M-1's six Gauntlet exclusion spans grade 4 exclusions (US "1600"/"3080"/"1200" via their region,
65
+ * PR "3499" via the territory-mapped country) + 2 documented abstentions (MX "2000" — no country
66
+ * token, "Tabasco" is not a `matchSubdivision` key; ES "15 07691" — no ES slice). Within-country,
67
+ * the exclusion problem is close to empty on the curated board, and a 5-digit house number in a
68
+ * DE/FR address is shape-native — the shape cannot exclude it (M-1 finding #1), so the mechanism
69
+ * CONFIRMS it instead.
70
+ *
71
+ * **D-rule: opt-in behind `ResolveOpts.postcodeShapeCoherence`, default-OFF.** Demotion is the
72
+ * failure mode with teeth, so a default-on promotion needs the full pre-registered gate (B1-1
73
+ * byte-stability, B1-2 exclusion ≥90% with the correct sibling tag surviving, B1-3 confound ≤2%
74
+ * false exclusions; kill on any B1-3 δ).
75
+ */
76
+
77
+ import { candidateSystemsForPostcode } from "@mailwoman/codex"
78
+ import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
79
+ import { isUSStateAbbreviation } from "@mailwoman/codex/us"
80
+ import type { AddressNode } from "@mailwoman/core/decoder"
81
+
82
+ /**
83
+ * The codex address systems a sibling signal can speak for — the universe `candidateSystemsForPostcode` can return, in
84
+ * the upper-case ISO form this module's signals are emitted in (`SystemCode` itself is lower-case). Signals from
85
+ * countries with no codex slice are filtered out BEFORE the intersection test, so a slice-less country can never
86
+ * manufacture an empty intersection (the false-exclusion trap; see the header).
87
+ */
88
+ const SYSTEM_UNIVERSE: ReadonlySet<string> = new Set<string>(["US", "DE", "FR", "CA", "GB", "JP", "AU", "NZ"])
89
+
90
+ /**
91
+ * The pass's per-tree verdict — the caller (and the B1 board tests) can see exactly which spans were confirmed,
92
+ * excluded, or abstained, and which confirmed span's narrowed systems should bound the country-scope pass.
93
+ */
94
+ export interface PostcodeShapeVerdict {
95
+ /**
96
+ * The narrowed candidate systems (upper-case) of the FIRST confirmed postcode node — the one `firstPostcodeValue`
97
+ * will pick — to thread into `findPostcodeCountryScope` as its candidate list. Undefined when no postcode node was
98
+ * confirmed.
99
+ */
100
+ narrowing?: string[]
101
+ /**
102
+ * The postcode strings the mechanism confirmed (shape ∩ confident siblings ≠ ∅).
103
+ */
104
+ confirmed: string[]
105
+ /**
106
+ * The postcode strings the mechanism excluded (shape ∩ confident siblings = ∅).
107
+ */
108
+ excluded: string[]
109
+ /**
110
+ * The postcode strings the mechanism abstained on (no confident siblings, or no codex shape).
111
+ */
112
+ abstained: string[]
113
+ }
114
+
115
+ /**
116
+ * Collect the sibling country signals: the country node (territory-mapped), the region node (`matchSubdivision` +
117
+ * `country_hint`), each filtered to the codex SystemCode universe. The tree is walked once for ALL postcode spans —
118
+ * sibling evidence is tree-level, not per-span.
119
+ */
120
+ function collectSiblingSystems(roots: readonly AddressNode[]): Set<string> {
121
+ const out = new Set<string>()
122
+ const stack: AddressNode[] = [...roots]
123
+
124
+ while (stack.length) {
125
+ const n = stack.pop()!
126
+ stack.push(...n.children)
127
+
128
+ if (n.tag === "country") {
129
+ const matched = matchCountry(n.value)
130
+
131
+ if (!matched) continue
132
+ // Territory map: PR/VI/GU/MP/AS are USPS state-or-territory abbreviations (codex/us/state.ts),
133
+ // so a US-territory country token ("Puerto Rico", "Guam") is a US-system signal.
134
+ const system = isUSStateAbbreviation(matched.iso2) ? "US" : matched.iso2.toUpperCase()
135
+
136
+ if (SYSTEM_UNIVERSE.has(system)) {
137
+ out.add(system)
138
+ }
139
+
140
+ continue
141
+ }
142
+
143
+ if (n.tag === "region") {
144
+ // (a) The region's value as a subdivision ("CA" → US, "ON" → CA — the US-wins tiebreak for
145
+ // "CA" is matchSubdivision's own). (b) The `country_hint` stamp annotateUSRegions writes on
146
+ // 2-letter US state abbreviations — the same evidence via the pipeline's other seam.
147
+ const sub = matchSubdivision(n.value)
148
+
149
+ if (sub && SYSTEM_UNIVERSE.has(sub.country.toUpperCase())) {
150
+ out.add(sub.country.toUpperCase())
151
+ }
152
+
153
+ const hint = n.metadata?.["country_hint"]
154
+
155
+ if (typeof hint === "string" && SYSTEM_UNIVERSE.has(hint.toUpperCase())) {
156
+ out.add(hint.toUpperCase())
157
+ }
158
+ }
159
+ }
160
+
161
+ return out
162
+ }
163
+
164
+ /**
165
+ * Run the shape-coherence verdict over every `postcode` span in the tree, mutating the EXCLUDED spans in place (the
166
+ * retag / exclusion stamp) and stamping CONFIRMED spans' narrowed systems. Pure-sync: no backend, no queries. See the
167
+ * header for the full rule.
168
+ */
169
+ export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): PostcodeShapeVerdict {
170
+ const verdict: PostcodeShapeVerdict = { confirmed: [], excluded: [], abstained: [] }
171
+
172
+ // The postcode spans in tree order — the same DFS `firstPostcodeValue` uses, so the verdict's
173
+ // "first confirmed" is the node `state.postcode` will read.
174
+ const postcodes: AddressNode[] = []
175
+ const stack: AddressNode[] = [...roots]
176
+
177
+ while (stack.length) {
178
+ const n = stack.pop()!
179
+
180
+ if (n.tag === "postcode" && n.value.trim().length) {
181
+ postcodes.push(n)
182
+ }
183
+
184
+ stack.push(...n.children)
185
+ }
186
+
187
+ if (!postcodes.length) return verdict
188
+
189
+ const siblingSystems = collectSiblingSystems(roots)
190
+
191
+ for (const node of postcodes) {
192
+ const code = node.value.trim()
193
+ const systems = candidateSystemsForPostcode(code)
194
+
195
+ // A shape no codex system recognizes is no evidence either way — abstain (the 10/110
196
+ // slice-less Gauntlet codes: IE Eircode, SI, IM, …).
197
+ if (!systems.length) {
198
+ verdict.abstained.push(code)
199
+
200
+ continue
201
+ }
202
+
203
+ const intersection = systems.map((system) => system.toUpperCase()).filter((system) => siblingSystems.has(system))
204
+
205
+ if (intersection.length) {
206
+ verdict.confirmed.push(code)
207
+ // Additive only — resolution stays byte-identical (B1-1). The narrowed intersection is the
208
+ // candidate set the country-scope pass should bound itself to.
209
+ node.metadata = { ...node.metadata, postcode_shape_systems: intersection }
210
+
211
+ if (verdict.narrowing === undefined) {
212
+ verdict.narrowing = intersection
213
+ }
214
+
215
+ continue
216
+ }
217
+
218
+ if (siblingSystems.size) {
219
+ // Confident siblings, empty intersection → EXCLUDED. A digit-only span is demoted to its
220
+ // correct sibling tag (B1-2); a letter-bearing span (the "15 07691" compound corner) keeps
221
+ // its tag and is stamped instead — either way every resolve consumer skips it.
222
+ verdict.excluded.push(code)
223
+
224
+ if (/^\d+$/.test(code)) {
225
+ node.tag = "house_number"
226
+ } else {
227
+ node.metadata = { ...node.metadata, postcode_shape_excluded: true }
228
+ }
229
+
230
+ continue
231
+ }
232
+
233
+ // No confident siblings — the same abstention posture postcode-country-coherence.ts:269 takes
234
+ // on zero-or-two coherent countries. Never guess with the shape alone.
235
+ verdict.abstained.push(code)
236
+ }
237
+
238
+ return verdict
239
+ }
240
+
241
+ /**
242
+ * True when a node is a postcode span this pass excluded but could not retag (the letter-bearing compound corner). The
243
+ * resolve's postcode consumers (`firstPostcodeValue`, the walk's postcode lookup, the post-walk postcode passes) all
244
+ * skip these, which is what "strip the postcode tag's contribution" means for a span that keeps its tag.
245
+ */
246
+ export function isShapeExcludedPostcode(node: AddressNode): boolean {
247
+ return node.tag === "postcode" && node.metadata?.["postcode_shape_excluded"] === true
248
+ }