@mailwoman/resolver 10.0.0 → 10.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 (134) hide show
  1. package/README.md +9 -7
  2. package/lib/admin/coherence-passes.ts +31 -172
  3. package/lib/admin/containment.ts +15 -33
  4. package/lib/admin/jp-municipality.ts +21 -14
  5. package/lib/admin/winner.ts +37 -69
  6. package/lib/backend-capabilities.ts +28 -27
  7. package/lib/bare-toponym-race.ts +69 -37
  8. package/lib/decorate-node.ts +25 -49
  9. package/lib/fold-name.ts +5 -18
  10. package/lib/index.ts +5 -9
  11. package/lib/plausibility.ts +41 -68
  12. package/lib/postcode/country-coherence.ts +92 -296
  13. package/lib/postcode/prefix.ts +24 -86
  14. package/lib/postcode/shape-coherence.ts +26 -116
  15. package/lib/remote-resolver.ts +38 -33
  16. package/lib/rerank.ts +41 -54
  17. package/lib/resolve/passes.ts +188 -177
  18. package/lib/resolve.ts +744 -0
  19. package/lib/span-rescore.ts +219 -175
  20. package/lib/street/evidence.ts +65 -73
  21. package/lib/street/tier.ts +51 -194
  22. package/lib/toponym-prior.ts +54 -180
  23. package/out/admin/coherence-passes.d.ts +18 -69
  24. package/out/admin/coherence-passes.d.ts.map +1 -1
  25. package/out/admin/coherence-passes.js +24 -166
  26. package/out/admin/coherence-passes.js.map +1 -1
  27. package/out/admin/containment.d.ts +13 -31
  28. package/out/admin/containment.d.ts.map +1 -1
  29. package/out/admin/containment.js +13 -31
  30. package/out/admin/containment.js.map +1 -1
  31. package/out/admin/jp-municipality.d.ts +21 -14
  32. package/out/admin/jp-municipality.d.ts.map +1 -1
  33. package/out/admin/jp-municipality.js +18 -12
  34. package/out/admin/jp-municipality.js.map +1 -1
  35. package/out/admin/winner.d.ts +32 -64
  36. package/out/admin/winner.d.ts.map +1 -1
  37. package/out/admin/winner.js +23 -56
  38. package/out/admin/winner.js.map +1 -1
  39. package/out/{admin/index.d.ts → admin.d.ts} +1 -1
  40. package/out/admin.d.ts.map +1 -0
  41. package/out/{admin/index.js → admin.js} +1 -1
  42. package/out/admin.js.map +1 -0
  43. package/out/backend-capabilities.d.ts +19 -20
  44. package/out/backend-capabilities.d.ts.map +1 -1
  45. package/out/backend-capabilities.js +28 -26
  46. package/out/backend-capabilities.js.map +1 -1
  47. package/out/bare-toponym-race.d.ts +54 -27
  48. package/out/bare-toponym-race.d.ts.map +1 -1
  49. package/out/bare-toponym-race.js +69 -37
  50. package/out/bare-toponym-race.js.map +1 -1
  51. package/out/decorate-node.d.ts +6 -8
  52. package/out/decorate-node.d.ts.map +1 -1
  53. package/out/decorate-node.js +25 -49
  54. package/out/decorate-node.js.map +1 -1
  55. package/out/fold-name.d.ts +5 -18
  56. package/out/fold-name.d.ts.map +1 -1
  57. package/out/fold-name.js +5 -18
  58. package/out/fold-name.js.map +1 -1
  59. package/out/index.d.ts +5 -6
  60. package/out/index.d.ts.map +1 -1
  61. package/out/index.js +5 -8
  62. package/out/index.js.map +1 -1
  63. package/out/plausibility.d.ts +30 -60
  64. package/out/plausibility.d.ts.map +1 -1
  65. package/out/plausibility.js +19 -52
  66. package/out/plausibility.js.map +1 -1
  67. package/out/postcode/country-coherence.d.ts +53 -167
  68. package/out/postcode/country-coherence.d.ts.map +1 -1
  69. package/out/postcode/country-coherence.js +42 -259
  70. package/out/postcode/country-coherence.js.map +1 -1
  71. package/out/postcode/prefix.d.ts +18 -69
  72. package/out/postcode/prefix.d.ts.map +1 -1
  73. package/out/postcode/prefix.js +11 -78
  74. package/out/postcode/prefix.js.map +1 -1
  75. package/out/postcode/shape-coherence.d.ts +18 -85
  76. package/out/postcode/shape-coherence.d.ts.map +1 -1
  77. package/out/postcode/shape-coherence.js +11 -107
  78. package/out/postcode/shape-coherence.js.map +1 -1
  79. package/out/{postcode/index.d.ts → postcode.d.ts} +1 -1
  80. package/out/postcode.d.ts.map +1 -0
  81. package/out/{postcode/index.js → postcode.js} +1 -1
  82. package/out/postcode.js.map +1 -0
  83. package/out/remote-resolver.d.ts +32 -31
  84. package/out/remote-resolver.d.ts.map +1 -1
  85. package/out/remote-resolver.js +12 -20
  86. package/out/remote-resolver.js.map +1 -1
  87. package/out/rerank.d.ts +32 -46
  88. package/out/rerank.d.ts.map +1 -1
  89. package/out/rerank.js +16 -41
  90. package/out/rerank.js.map +1 -1
  91. package/out/resolve/passes.d.ts +108 -95
  92. package/out/resolve/passes.d.ts.map +1 -1
  93. package/out/resolve/passes.js +67 -126
  94. package/out/resolve/passes.js.map +1 -1
  95. package/out/resolve.d.ts +15 -0
  96. package/out/resolve.d.ts.map +1 -0
  97. package/out/resolve.js +557 -0
  98. package/out/resolve.js.map +1 -0
  99. package/out/span-rescore.d.ts +56 -65
  100. package/out/span-rescore.d.ts.map +1 -1
  101. package/out/span-rescore.js +134 -132
  102. package/out/span-rescore.js.map +1 -1
  103. package/out/street/evidence.d.ts +56 -61
  104. package/out/street/evidence.d.ts.map +1 -1
  105. package/out/street/evidence.js +22 -46
  106. package/out/street/evidence.js.map +1 -1
  107. package/out/street/tier.d.ts +18 -30
  108. package/out/street/tier.d.ts.map +1 -1
  109. package/out/street/tier.js +43 -191
  110. package/out/street/tier.js.map +1 -1
  111. package/out/{street/index.d.ts → street.d.ts} +1 -1
  112. package/out/street.d.ts.map +1 -0
  113. package/out/{street/index.js → street.js} +1 -1
  114. package/out/street.js.map +1 -0
  115. package/out/toponym-prior.d.ts +22 -110
  116. package/out/toponym-prior.d.ts.map +1 -1
  117. package/out/toponym-prior.js +41 -170
  118. package/out/toponym-prior.js.map +1 -1
  119. package/package.json +44 -147
  120. package/lib/resolve/index.ts +0 -989
  121. package/out/admin/index.d.ts.map +0 -1
  122. package/out/admin/index.js.map +0 -1
  123. package/out/postcode/index.d.ts.map +0 -1
  124. package/out/postcode/index.js.map +0 -1
  125. package/out/resolve/index.d.ts +0 -20
  126. package/out/resolve/index.d.ts.map +0 -1
  127. package/out/resolve/index.js +0 -808
  128. package/out/resolve/index.js.map +0 -1
  129. package/out/street/index.d.ts.map +0 -1
  130. package/out/street/index.js.map +0 -1
  131. package/vitest.config.ts +0 -38
  132. /package/lib/{admin/index.ts → admin.ts} +0 -0
  133. /package/lib/{postcode/index.ts → postcode.ts} +0 -0
  134. /package/lib/{street/index.ts → street.ts} +0 -0
@@ -2,131 +2,29 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
- *
6
- * Postcode-country coherence (#42) — the joint-consistency resolve keyed on the (postcode, locality)
7
- * PAIR, and the first mechanism in the tree allowed to override `defaultCountry`.
8
- *
9
- * The failing case: `12 Rue de Rivoli, 75001 Paris` under the en-US locale. `--locale` defaults to
10
- * `en-US`, `localeToCountry` turns that into `ResolveOpts.defaultCountry = "US"`, and the backend
11
- * turns THAT into a hard `spr.country = 'US'` WHERE clause. The candidate pool is all-US before
12
- * ranking begins, so a coarse placer that already called this address FR at confidence
13
- * 0.9999908844 has nothing to promote — a soft re-rank downstream of a hard filter is inert by
14
- * construction. Population then picks Paris, Texas (pop 24,969). With the postal extracts attached
15
- * the answer gets WORSE, not merely wrong: the postcode resolves to the US row (ZIP 75001,
16
- * Addison TX), `applyPostcodeConsistency` finds no Paris within its 50 km check (the nearest is
17
- * 143.8 km), and falls the locality coordinate back to the ZIP point. See
18
- * `docs/records/evals/2026-08-03-postcode-locality-scoping.md` for the instrumented diagnosis.
19
- *
20
- * No pattern-only change can fix this. `75001` is NOT unambiguously French:
21
- * `candidateSystemsForPostcode("75001")` returns `["us", "de", "fr"]`, and the 2026-08-04
22
- * candidate gazetteer holds the literal string in FOUR countries — FR 48.863,2.336 (Paris 1er),
23
- * US 32.960,-96.838 (Addison TX), DE 48.844,9.367, PL 54.190,16.188 (×2 rows). The SHAPE is
24
- * ambiguous four ways. The GEOMETRY is not: Addison and Paris are ~8,000 km apart, and only one
25
- * of the four has a same-named locality next to its 75001.
26
- *
27
- * So this pass asks the question the shape cannot answer — _in which country are this postcode and
28
- * this locality geographically consistent?_ — over exactly the primitive the resolver already uses
29
- * three times (`applyAdminCoherence` #263, `applyExplicitCountryCoherence` #822,
30
- * `applyRegionCountryCoherence`), just keyed on the postcode instead of a region or country token.
31
- *
32
- * ## Why it runs BEFORE the walk, not after
33
- *
34
- * Its three siblings are post-walk re-picks: the walk resolves greedily, they swap the wrong node
35
- * pair for the right one. That shape cannot work here, because the thing to correct is the walk's
36
- * COUNTRY SCOPE, and the scope poisons three separate things a post-walk pass cannot reach — the
37
- * postcode node's own resolution (Addison, not Paris 1er), the `applyPostcodeConsistency` fallback
38
- * that then drags the locality onto it, and the `country` filter on every other admin lookup. So
39
- * this pass is a pre-walk SCOPE decision: it runs once, before the first lookup, and replaces
40
- * `state.defaultCountry` for the whole walk. Everything downstream — including the three post-walk
41
- * coherence passes and the street/rooftop tiers — then sees the corrected country.
42
- *
43
- * ## Why it is not a hard veto (the doctrine check)
44
- *
45
- * Registries are SOFT priors here, positive evidence only. Two properties keep this one honest:
46
- *
47
- * 1. **The default country is tested FIRST, and a coherent default always wins.** If (postcode,
48
- * locality) is consistent under `defaultCountry`, the pass returns `null` immediately, having
49
- * spent at most two lookups, and the walk is byte-identical. Every correctly-scoped domestic
50
- * parse exits here. It is not "US loses to FR"; it is "US had no answer".
51
- * 2. **Abstention is the default outcome.** Zero coherent countries (a wrong-for-the-city
52
- * postcode, or a recall gap in the gazetteer) and MORE than one coherent country (a genuine
53
- * geographic tie) both return `null`. The mechanism only ever speaks when exactly one country
54
- * makes the pair consistent, and only ever when the default country could not.
55
- *
56
- * ## What #24 changed (2026-08-10)
57
- *
58
- * Two structural gaps, both found by replaying the 420-row panel-v2 benchmark. The pass is default-ON,
59
- * the eu-mixed block gave it 29 chances, and it fired **zero** times — while the right answer sat in
60
- * the shipped gazetteer within 4 km of truth on 21 of them.
61
- *
62
- * 1. **The candidate countries came from a proxy.** `candidateSystemsForPostcode` is a shape test over
63
- * the eight slices codex specifies (`us de fr ca gb jp au nz`), so CZ, CH, BE, DK, AT, NL and IT
64
- * could never be PROPOSED, however good the evidence. `13000` shapes as `[us, de, fr]`; the
65
- * gazetteer holds it in exactly one country, and that country is CZ. The candidate set now unions
66
- * the shape list with the countries the gazetteer actually holds the postcode in — one unscoped
67
- * lookup, exhaustive at the measured cardinality (the most-shared code in the artifact carries 12
68
- * rows across 8 countries). Every candidate still has to pass the same geometric pair test, so the
69
- * widening can only convert an abstention into a verdict or a verdict into an abstention, never a
70
- * verdict into a different one.
71
- * 2. **The pair was all-or-nothing.** Ten panel rows had unimpeachable one-sided evidence and no pair:
72
- * the gazetteer carries no CH or BE postcodes at all (so `Sarnen` and `Kelmis` could never agree
73
- * with anything), and `Praha 3` / `Praha 9` are municipal districts no admin gazetteer names (so
74
- * `13000` had nothing to agree WITH). Each half may now speak alone — but only when the DEFAULT
75
- * country corroborates NEITHER half, and only when the speaking half names exactly one country in
76
- * the whole gazetteer. See {@link PostcodeCountryScopeEvidence}.
77
- *
78
- * The abstention doctrine is unchanged and is what bounds the new rungs: a two-country tie is a HARD
79
- * abstention that never falls through to the single-sided rungs. Corroboration at home bounds them
80
- * asymmetrically: the address's own POSTCODE existing in the default country stops the pass dead,
81
- * while a LOCALITY value at home neutralizes that value as a foreign witness without silencing its
82
- * siblings (the per-value rule in the single-sided section below).
83
- *
84
- * ## Evidence
85
- *
86
- * Prototyped out-of-tree against the live gazetteer over the public `findPlace` surface (2026-08-03):
87
- * 400 real US (ZIP, city) pairs from `postalcode-us.db` + 400 real FR (CP, commune) pairs from
88
- * `postcode-locality-fr.db` — 800 pairs, **zero** border crossings, at both the 15 km and 25 km
89
- * checks. The 22 US abstentions were pairs whose ZIP parent name is not an exact-matching locality
90
- * in the admin gazetteer (a recall gap; abstention is the safe outcome). The confound board's
91
- * verdicts were identical at 15, 25 AND 50 km, so the mechanism is not check-tuned; the default
92
- * below is the 25 km the scale run measured.
93
- *
94
- * Cost: 2 lookups on the byte-stable path (postcode + locality under the default country), and at
95
- * most `2 × |candidateSystems| × |localityValues|` — candidates bounded at 12, locality values at 3,
96
- * and the common tree carries exactly one — when the default is incoherent. Nothing runs at all
97
- * unless the tree carries both a postcode and a locality.
98
- *
99
- * **Default-ON** since the operator promotion of 2026-08-05 (#1477) — the resolver gauntlet, pinned
100
- * both ways, returned zero newly-failing conditional cases, and 56,000 pair evaluations across both
101
- * backends returned zero false positives. `ResolveOpts.postcodeCountryCoherence: false` opts out,
102
- * and the walk is byte-stable then. Receipts:
103
- * `docs/records/evals/2026-08-05-postcode-coherence-default-on-evidence.md`.
104
5
  */
105
6
 
106
- // `postcode-systems` has no dedicated export subpath; the barrel is where every other consumer
107
- // (`neural/postcode-anchor.ts`) reaches it from.
108
7
  import { candidateSystemsForPostcode } from "@mailwoman/codex"
109
- import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
8
+ import { firstNodeWhere, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
110
9
  import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
111
10
  import { haversineKm } from "@mailwoman/spatial"
112
11
 
113
12
  /**
114
- * Default check radius (km) for the postcode↔locality consistency test. 25 km is what the 800-pair scale run measured;
115
- * the confound board returned identical verdicts at 15, 25 and 50, so this is a floor choice, not a tuned one.
13
+ * The default maximum distance, in kilometers, between a postcode and a locality
14
+ * for them to count as consistent.
15
+ *
16
+ * Verdicts did not change anywhere between 15 and 50 km, so the exact value matters little.
116
17
  */
117
18
  export const POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM = 25
118
19
 
119
20
  /**
120
- * Which half (or halves) of the address bought the verdict — the firing receipt, so a reader of a scoped result can
121
- * tell a two-sided agreement from a one-sided uniqueness claim without re-deriving it.
21
+ * The part of the address that justified a country-scope verdict.
122
22
  *
123
- * - `pair` — postcode AND locality both resolve in this country, within the radius. The strongest rung and the only one
124
- * that existed before #24.
125
- * - `locality` — the locality names exactly one country in the whole gazetteer, and the postcode names none that
126
- * contradict it. This is the CH/BE class: the gazetteer carries no Swiss or Belgian postcodes at all, so the pair
127
- * test can never fire there no matter how good the locality evidence is.
128
- * - `postcode` — the postcode is held in exactly one country and the locality is in no gazetteer at all. The `Praha 3`
129
- * class: a municipal district nobody's admin gazetteer names.
23
+ * - `pair`: the postcode and the locality both resolve in the country, within the threshold distance.
24
+ * - `locality`: the locality exists in exactly one country.
25
+ * The postcode copy in that country does not contradict it.
26
+ * - `postcode`: the postcode exists in exactly one country.
27
+ * No gazetteer knows the locality.
130
28
  */
131
29
  export type PostcodeCountryScopeEvidence = "pair" | "locality" | "postcode"
132
30
 
@@ -135,96 +33,92 @@ export type PostcodeCountryScopeEvidence = "pair" | "locality" | "postcode"
135
33
  */
136
34
  export interface PostcodeCountryScope {
137
35
  /**
138
- * ISO-3166 alpha-2, upper-case.
36
+ * The upper-case ISO 3166-1 alpha-2 country code.
139
37
  */
140
38
  country: string
39
+
141
40
  /**
142
- * The postcode string the verdict was reached on (as it appears in the tree).
41
+ * The postcode the verdict used.
143
42
  */
144
43
  postcode: string
44
+
145
45
  /**
146
- * The locality string the verdict was reached on.
46
+ * The locality the verdict used.
147
47
  */
148
48
  locality: string
49
+
149
50
  /**
150
- * Which evidence carried the verdict. See {@link PostcodeCountryScopeEvidence}.
51
+ * The evidence that supported the verdict.
151
52
  */
152
53
  evidence: PostcodeCountryScopeEvidence
54
+
153
55
  /**
154
- * Distance between the resolved postcode point and the nearest same-named locality, in km. Always `<= thresholdKm`.
155
- * Present ONLY for the `pair` rung — a single-sided verdict has no two points to measure between, and reporting a `0`
156
- * there would assert an agreement nobody tested (the meaning-of-zero rule).
56
+ * The distance in kilometers between the postcode point and the nearest locality with the same name.
57
+ *
58
+ * It is set only for `pair` evidence, because the other verdicts compare no second point.
157
59
  */
158
- distanceKm?: number
60
+ distanceKm: number | null
61
+
159
62
  /**
160
- * The postcode place that anchored the verdict. Absent on the `locality` rung.
63
+ * The postcode place behind the verdict.
64
+ * It is absent for `locality` evidence.
161
65
  */
162
- postcodePlace?: ResolvedPlace
66
+ postcodePlace: ResolvedPlace | null
67
+
163
68
  /**
164
- * The locality place that anchored the verdict. Absent on the `postcode` rung.
69
+ * The locality place behind the verdict.
70
+ * It is absent for `postcode` evidence.
165
71
  */
166
- localityPlace?: ResolvedPlace
72
+ localityPlace: ResolvedPlace | null
167
73
  }
168
74
 
75
+ /**
76
+ * Options for {@linkcode findPostcodeCountryScope}.
77
+ */
169
78
  export interface PostcodeCountryScopeOpts {
170
79
  /**
171
- * The postcode string from the tree (the resolver already pre-scans for it — pass `state.postcode` so this pass and
172
- * the walk can never disagree about WHICH postcode is the address's).
80
+ * The address's postcode.
81
+ *
82
+ * Callers should pass the value from the resolver's own pre-scan, so that this pass
83
+ * and the walk use the same postcode.
173
84
  */
174
85
  postcode: string
86
+
175
87
  /**
176
- * The country the caller's `defaultCountry` would hard-filter to — or `undefined` when no default is in force (the
177
- * browser cascade), where the pass CONSTRAINS instead of overriding: the default-coherence short-circuit is vacuous
178
- * and the exactly-one-country abstention carries the safety alone. Historically required: this pass was built to
179
- * correct a wrong one, so with no default there is nothing to correct and the caller should not be calling.
88
+ * The caller's default country filter, or null when no default applies.
89
+ *
90
+ * Without a default, only the `pair` test runs.
91
+ * The pass returns a scope when exactly one country qualifies.
180
92
  */
181
- defaultCountry: string | undefined
93
+ defaultCountry: string | null
94
+
182
95
  /**
183
- * Consistency check radius in km. Defaults to {@link POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM}.
96
+ * The consistency radius in kilometers.
97
+ *
98
+ * @defaultValue {@linkcode POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM}
184
99
  */
185
100
  thresholdKm?: number
101
+
186
102
  /**
187
- * Optional narrowing of the SHAPE half of the candidate-country set — the shape-coherence pass's intersection for a
188
- * CONFIRMED postcode span (see `resolver/postcode-shape-coherence.ts`, #31 Mechanism 1). When present it REPLACES
189
- * `candidateSystemsForPostcode`'s own list; it is a pure subset of that list (codex systems ∩ confident sibling
190
- * systems). Upper-case ISO-3166 alpha-2, e.g. `["US"]` for a 5-digit code whose siblings all say US.
103
+ * Upper-case ISO 3166-1 alpha-2 codes that replace the countries inferred from the postcode's shape.
191
104
  *
192
- * It narrows the shape half only. Since #24 the candidate set also carries the countries the GAZETTEER holds this
193
- * postcode in, and that half is not narrowable — it is the artifact reporting what it contains, which is the same
194
- * class of evidence the pair test itself runs on. Every candidate from either half still has to pass that test.
105
+ * The pass still adds countries whose gazetteer holds the postcode.
106
+ * Every candidate must pass the pair test.
195
107
  */
196
108
  candidateSystems?: readonly string[]
197
109
  }
198
110
 
199
- /**
200
- * A usable coordinate — the gazetteer stores an unlocated row as 0,0, which haversine would measure against.
201
- */
202
111
  function hasCoord(p: ResolvedPlace): boolean {
203
112
  return p.lat !== 0 || p.lon !== 0
204
113
  }
205
114
 
206
- /**
207
- * Upper bound on locality values the pass will consider. A parse rarely tags more than two; the cap keeps a
208
- * pathological tree from multiplying the pair sweep.
209
- */
210
115
  const MAX_LOCALITY_VALUES = 3
211
116
 
212
117
  /**
213
- * The address's locality strings in DOCUMENT ORDER — every `locality` value first, then every `dependent_locality`,
214
- * case-insensitively deduplicated. Two passes so a real locality always beats a dependent one regardless of tree
215
- * order.
118
+ * Returns up to three distinct locality values in document order, listing every
119
+ * `locality` before any `dependent_locality`.
216
120
  *
217
- * Document order is required, not cosmetic. The original stack-pop traversal visited the LAST node first, so on `92
218
- * Laurell Road, Gander, NL A1V 0A9` — where the model tags both `Gander` and the province abbreviation `NL` as
219
- * localities — the pass keyed its whole country verdict on "NL", whose only exact locality-band bearer is an alias of
220
- * Nal, Afghanistan, and the walk resolved a Newfoundland street 10,000 km away. The FIRST-written locality is the one
221
- * the address is about.
222
- *
223
- * ALL values matter, not just the first. On `Calle Mayor 12, Aravaca, 28023 Madrid` the model tags both `Aravaca` and
224
- * `Madrid` as localities; `Aravaca` is a neighbourhood the locality band cannot see, while `Madrid` carries the ES pair
225
- * verdict (the ES 28023 row sits 9.6 km from the Madrid locality row). A pass keyed on a single value bets the whole
226
- * country verdict on whichever one a traversal order happens to pick — first-only re-scoped that address to the US ZIP
227
- * 28023 centroid in North Carolina. So the verdict rungs try each value in order until one produces evidence.
121
+ * Order matters because the first locality written is the one the address is about.
228
122
  */
229
123
  export function localityValuesInDocumentOrder(roots: readonly AddressNode[]): string[] {
230
124
  const out: string[] = []
@@ -238,15 +132,15 @@ export function localityValuesInDocumentOrder(roots: readonly AddressNode[]): st
238
132
  }
239
133
 
240
134
  /**
241
- * The first of {@link localityValuesInDocumentOrder} — the locality the address is about.
135
+ * Returns the first value of {@link localityValuesInDocumentOrder}.
242
136
  */
243
- export function firstLocalityValue(roots: readonly AddressNode[]): string | undefined {
244
- return localityValuesInDocumentOrder(roots)[0]
137
+ export function firstLocalityValue(roots: readonly AddressNode[]): string | null {
138
+ return localityValuesInDocumentOrder(roots)[0] ?? null
245
139
  }
246
140
 
247
141
  function collectInDocumentOrder(nodes: readonly AddressNode[], tag: string, out: string[], seen: Set<string>): void {
248
142
  for (const n of nodes) {
249
- if (n.tag === tag && n.value.trim().length) {
143
+ if (n.tag === tag && n.value.trim()) {
250
144
  const value = n.value.trim()
251
145
  const key = value.toLowerCase()
252
146
 
@@ -260,39 +154,11 @@ function collectInDocumentOrder(nodes: readonly AddressNode[], tag: string, out:
260
154
  }
261
155
  }
262
156
 
263
- /**
264
- * Over-fetch for the UNSCOPED holder probes (#24). Postcodes are bounded and small — the 2026-08-10 candidate
265
- * gazetteer's most-shared code carries 12 rows across 8 countries — so 20 sees every bearer and the postcode holder set
266
- * is COMPLETE, not a sample. Locality names are not bounded that way (`rampur` has 1,096 rows, `bara` spans 42
267
- * countries), so 30 is a population-first WINDOW: it can only ever hide a country, which turns a "more than one
268
- * country" abstention into a false "exactly one". The explicit default-country probe below is what closes that gap for
269
- * the case that matters (the address is domestic after all).
270
- */
271
157
  const POSTCODE_HOLDER_FETCH = 20
272
158
  const LOCALITY_HOLDER_FETCH = 30
273
159
 
274
- /**
275
- * Upper bound on countries the pair rung will test, so a pathological name can't turn one incoherent parse into a
276
- * hundred lookups. The postcode holder set is ≤8 countries in the measured artifact and the codex shape list is ≤8, so
277
- * this only ever binds on a gazetteer very unlike today's.
278
- */
279
160
  const MAX_CANDIDATE_COUNTRIES = 12
280
161
 
281
- /**
282
- * Countries that hold an exact, coordinate-bearing row for `text` at `placetype`, mapped to their best (first) such
283
- * row. One UNSCOPED lookup.
284
- *
285
- * This is the #24 candidate source, and it replaces a proxy with the thing itself. The pass used to ask codex "which
286
- * address SYSTEMS could this shape be?" — a model-free shape test over the eight slices codex specifies. That answer is
287
- * correct and useless for two thirds of Europe: `13000` shapes as `[us, de, fr]`, the gazetteer holds it in exactly one
288
- * country (CZ), and CZ has no codex slice, so the pass could not propose the only country that could possibly be right.
289
- * Membership in the gazetteer is positive evidence of the same kind the pair test already runs on, available for one
290
- * lookup, and it is EXHAUSTIVE for postcodes at the measured cardinality.
291
- *
292
- * `exactMatch !== false` is the admission bar: a fuzzy postcode hit is a DIFFERENT postcode (the 2026-08-05 Code-Point
293
- * lesson — `BT3 9QQ` trigram-matching Sheffield's `S3 9QQ`), and a fuzzy locality hit is evidence about the index, not
294
- * about the country. Backends that do not stamp the flag leave it undefined and still contribute.
295
- */
296
162
  async function countriesHolding(
297
163
  backend: ResolverBackend,
298
164
  text: string,
@@ -307,7 +173,7 @@ async function countriesHolding(
307
173
  try {
308
174
  hits = await backend.findPlace({ text, placetype, limit, ...(opts?.primaryOnly ? { primaryOnly: true } : {}) })
309
175
  } catch {
310
- return out // a backend hiccup degrades to "no evidence", never to a crashed resolve
176
+ return out
311
177
  }
312
178
 
313
179
  for (const hit of hits) {
@@ -323,13 +189,6 @@ async function countriesHolding(
323
189
  return out
324
190
  }
325
191
 
326
- /**
327
- * Is the (postcode, locality) pair geographically consistent in `country`? Returns the winning pair and its distance,
328
- * or `null` when the postcode does not resolve there, no same-named locality exists there, or the nearest one is
329
- * outside the check. Costs one postcode lookup plus (only if that hit) one locality lookup — or just the locality
330
- * lookup when the caller already knows the country's postcode row (`knownPostcodePlace`, from the exhaustive unscoped
331
- * probe).
332
- */
333
192
  async function coherenceIn(
334
193
  country: string,
335
194
  postcode: string,
@@ -346,7 +205,7 @@ async function coherenceIn(
346
205
  try {
347
206
  postcodeHits = await backend.findPlace({ text: postcode, placetype: "postalcode", country, limit: 3 })
348
207
  } catch {
349
- return null // a backend hiccup degrades to "no evidence here", never to a crashed resolve
208
+ return null
350
209
  }
351
210
 
352
211
  postcodePlace = postcodeHits.find(hasCoord)
@@ -362,9 +221,6 @@ async function coherenceIn(
362
221
  return null
363
222
  }
364
223
 
365
- // EXACT matches only. A fuzzy same-country hit ("Paris" → "Parish") is not evidence that the postcode
366
- // belongs to this country; it is evidence that the FTS index is generous. Backends that do not stamp
367
- // `exactMatch` therefore contribute nothing here rather than contributing noise.
368
224
  let best: { localityPlace: ResolvedPlace; distanceKm: number } | null = null
369
225
 
370
226
  for (const candidate of localityHits) {
@@ -382,18 +238,11 @@ async function coherenceIn(
382
238
  }
383
239
 
384
240
  /**
385
- * The country in which this address's postcode and locality are geographically consistent — or `null` to abstain.
386
- *
387
- * Order matters and is the whole safety argument. The caller's `defaultCountry` is tested FIRST; a coherent default
388
- * short-circuits with `null` (nothing to correct, ≤2 lookups spent, the walk unchanged). Only when the default cannot
389
- * make the pair consistent are the codex shape's other candidate systems tried, and only a UNIQUE coherent alternative
390
- * produces a verdict — zero (no evidence) and two-or-more (a genuine tie) both abstain.
241
+ * Finds the one country, other than the caller's default, in which the address's
242
+ * postcode and locality are consistent.
391
243
  *
392
- * The candidate set is `candidateSystemsForPostcode` — a model-free SHAPE test over each codex slice's own postcode
393
- * pattern, no safelist and no prior. Its `SystemCode` values are ISO-3166 alpha-2 in lower case, so the upper-casing
394
- * below is the whole conversion. Note the corollary: a country with no codex slice can never be proposed (the gazetteer
395
- * holds `75001` in PL, and this pass will never return PL), which bounds the mechanism to the systems whose postcode
396
- * shapes are actually specified.
244
+ * It returns `null` when the address has a country node, when the default country is
245
+ * already consistent, or when more than one alternative qualifies.
397
246
  */
398
247
  export async function findPostcodeCountryScope(
399
248
  roots: readonly AddressNode[],
@@ -401,41 +250,24 @@ export async function findPostcodeCountryScope(
401
250
  opts: PostcodeCountryScopeOpts
402
251
  ): Promise<PostcodeCountryScope | null> {
403
252
  const postcode = opts.postcode.trim()
404
- const defaultCountry = opts.defaultCountry?.trim().toUpperCase() || undefined
253
+ const defaultCountry = opts.defaultCountry?.trim().toUpperCase() || null
405
254
 
406
255
  if (!postcode) return null
407
256
 
257
+ if (firstNodeWhere(roots, (n) => n.tag === "country" && n.value.trim())) return null
258
+
408
259
  const localities = localityValuesInDocumentOrder(roots)
409
260
 
410
- // Both halves of the pair are required. A postcode with no locality has nothing to be coherent WITH, which is what
411
- // keeps this pass inert on "Springfield, IL 62701" (the parser tags Springfield as a `street` — a separate defect)
412
- // and on every bare-postcode query.
413
261
  if (!localities.length) return null
414
262
 
415
263
  const thresholdKm = opts.thresholdKm ?? POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM
416
264
 
417
- // 1. Is the caller's own default country coherent with ANY of the address's locality values? If so we are done —
418
- // positive evidence for the default, no override, and the common domestic path (one locality value) costs two
419
- // lookups and changes nothing. With no default in force (the browser cascade) there is nothing to test — the
420
- // sweep below carries the whole verdict.
421
265
  if (defaultCountry) {
422
266
  for (const locality of localities) {
423
267
  if (await coherenceIn(defaultCountry, postcode, locality, backend, thresholdKm)) return null
424
268
  }
425
269
  }
426
270
 
427
- // 2. The default could not place this pair. Which countries could? Two sources, unioned:
428
- //
429
- // - the SHAPE list (`candidateSystemsForPostcode`, or the shape-coherence pass's narrowing when #31
430
- // Mechanism 1 supplied one — a pure subset of it), and
431
- // - the countries the GAZETTEER actually holds this postcode in (#24). Exhaustive at the measured
432
- // cardinality, and the only source that can name a country codex has no slice for — which was the
433
- // whole reason the CZ/CH/BE/DK/AT/NL block of the 2026-08-09 panel resolved to US namesakes while
434
- // their own postcodes sat in the shipped gazetteer within 4 km of truth.
435
- //
436
- // The union can only ADD countries, and every added one must still pass the same geometric pair test,
437
- // so this widens recall without weakening the verdict: a second coherent country turns a verdict into
438
- // an abstention (safe), never into a wrong answer.
439
271
  const pcHolders = await countriesHolding(backend, postcode, "postalcode", POSTCODE_HOLDER_FETCH)
440
272
 
441
273
  const shapeSystems = (
@@ -446,12 +278,6 @@ export async function findPostcodeCountryScope(
446
278
  .filter((country) => country !== defaultCountry)
447
279
  .slice(0, MAX_CANDIDATE_COUNTRIES)
448
280
 
449
- // 3. The pair sweep, per locality value in document order: the first value that produces evidence decides. A value
450
- // the band cannot see (`Aravaca`, a neighbourhood) yields zero coherent countries and the NEXT value gets its
451
- // turn — betting the verdict on a single value re-scoped that address to a US ZIP centroid (see
452
- // localityValuesInDocumentOrder). Exactly one coherent country is a verdict. Two coherent countries mean the
453
- // geometry genuinely does not decide, and guessing between them is precisely what this mechanism exists not to
454
- // do — a TIE is a hard abstention, never a fall-through to a later value or the weaker rungs below.
455
281
  for (const locality of localities) {
456
282
  const coherent: PostcodeCountryScope[] = []
457
283
 
@@ -468,41 +294,10 @@ export async function findPostcodeCountryScope(
468
294
  if (coherent.length > 1) return null
469
295
  }
470
296
 
471
- // The single-sided rungs below lean on the DEFAULT country as the domestic-plausibility guard
472
- // ("Vienna, VA" stays in Virginia because the default corroborates a half). With no default there
473
- // is no such anchor, so the no-default path ends at the pair rung: a pair verdict (Zabiče) is
474
- // in-scope, a single-sided guess is not.
475
297
  if (!defaultCountry) return null
476
298
 
477
- // 4. No country makes the PAIR consistent. On the 2026-08-09 panel that happened 10 times for two opposite
478
- // reasons, and in both the address's country was never in doubt — only unrepresentable as a pair:
479
- //
480
- // - the gazetteer holds no postcodes for the country at all (CH, BE), so the postcode half can never
481
- // agree with anything no matter how good the locality evidence is; or
482
- // - the locality is a name no admin gazetteer carries (`Praha 3`, `Praha 9` — municipal districts).
483
- //
484
- // So each half gets to speak alone, under conditions that keep this from becoming a guess. The
485
- // POSTCODE half is all-or-nothing: the default country holding this postcode makes the address
486
- // domestically plausible outright, and nothing foreign may be proposed. The LOCALITY half is
487
- // judged PER VALUE — a value the default country holds is domestic corroboration for THAT value
488
- // (it is neutralized as a foreign witness) without silencing its siblings. `14 Long St, Green
489
- // Point, Cape Town, 8001` is why: "Green Point" has pop-0 US namesakes, and letting that one
490
- // value abstain the whole pass handed a uniquely-ZA "Cape Town" to a hard US filter (the walk
491
- // answered Green Point, Pennsylvania). `123 Main St, Vienna, VA 22180` still holds in Virginia:
492
- // its ONLY locality value is domestic, so no foreign witness remains. The speaking value must
493
- // name EXACTLY ONE country in the entire gazetteer — the same uniqueness bar the pair rung uses,
494
- // applied to one side — and all speaking values must AGREE on that country.
495
299
  if (pcHolders.has(defaultCountry)) return null
496
300
 
497
- // 4a. A locality value names exactly one country. Stronger than the postcode rung — a place name is far
498
- // more discriminative than a four-digit code — so it is tried first. A verdict stands down when that
499
- // country's OWN postcode row contradicts the locality (outside the check): the two halves disagreeing
500
- // inside one country is exactly what the pair test exists to catch, and a single-sided rung must not
501
- // launder it.
502
- // PRIMARY-keyed rows only (#1626's re-reading discipline, applied to a country verdict): "the locality
503
- // names exactly one country" must mean a place NAMED that, never a place aliased to it — "NL"'s only
504
- // locality-band bearer was an exact ALIAS of Nal, Afghanistan, and a single alias row steered the whole
505
- // walk's country. The pair rung keeps aliases: there the postcode's own geometry corroborates them.
506
301
  let anyDomestic = false
507
302
  let anyLocalityKnown = false
508
303
  const verdicts = new Map<string, PostcodeCountryScope>()
@@ -528,55 +323,58 @@ export async function findPostcodeCountryScope(
528
323
  const ownPostcode = pcHolders.get(country)
529
324
 
530
325
  const contradicted =
531
- ownPostcode !== undefined &&
326
+ ownPostcode != null &&
532
327
  haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > thresholdKm
533
328
 
534
329
  if (country !== defaultCountry && !contradicted && !verdicts.has(country)) {
535
- verdicts.set(country, { country, postcode, locality, evidence: "locality", localityPlace })
330
+ verdicts.set(country, {
331
+ country,
332
+ postcode,
333
+ locality,
334
+ evidence: "locality",
335
+ distanceKm: null,
336
+ postcodePlace: null,
337
+ localityPlace,
338
+ })
536
339
  }
537
340
  }
538
341
 
539
- // Every speaking value must agree: two values uniquely naming DIFFERENT countries is a genuine
540
- // ambiguity, and guessing between them is what this mechanism exists not to do.
541
342
  if (verdicts.size === 1) return [...verdicts.values()][0]!
542
343
 
543
344
  if (verdicts.size > 1) return null
544
345
 
545
- // 4b. The postcode is held in exactly one country and the locality half is silent EVERYWHERE — no value
546
- // is domestic and no value names any country. `Biskupcova 1843/3, 13000 Praha 3`: `13000` is a CZ
547
- // code and nothing else, anywhere, and `Praha 3` (a municipal district) is in no admin gazetteer.
548
346
  if (!anyDomestic && !anyLocalityKnown && pcHolders.size === 1) {
549
347
  const [country, postcodePlace] = [...pcHolders.entries()][0]!
550
348
 
551
349
  if (country !== defaultCountry) {
552
- return { country, postcode, locality: localities[0]!, evidence: "postcode", postcodePlace }
350
+ return {
351
+ country,
352
+ postcode,
353
+ locality: localities[0]!,
354
+ evidence: "postcode",
355
+ distanceKm: null,
356
+ postcodePlace,
357
+ localityPlace: null,
358
+ }
553
359
  }
554
360
  }
555
361
 
556
362
  return null
557
363
  }
558
364
 
559
- /**
560
- * Does `country` hold an exact, coordinate-bearing locality row for `locality`? One scoped lookup — deliberately NOT
561
- * read off the unscoped holder window, which is population-first and truncated, so a small domestic bearer could fall
562
- * below its fold and let a foreign scope through.
563
- */
564
365
  async function holdsLocality(backend: ResolverBackend, locality: string, country: string): Promise<boolean> {
565
366
  try {
566
367
  const hits = await backend.findPlace({ text: locality, placetype: "locality", country, limit: 3 })
567
368
 
568
369
  return hits.some((hit) => hit.exactMatch && hasCoord(hit))
569
370
  } catch {
570
- // A backend hiccup must not be read as "the default country has nothing" — that would license a foreign
571
- // scope on no evidence. Treat it as corroboration and abstain.
572
371
  return true
573
372
  }
574
373
  }
575
374
 
576
375
  /**
577
- * Stamp the adopted scope onto the tree's postcode and locality nodes, so a consumer can see that the walk's country
578
- * was not the one the caller asked for — and which evidence bought the change. Additive: identity and coordinates are
579
- * untouched, this only writes `metadata`.
376
+ * Records an adopted country scope and its evidence in the `metadata` of the
377
+ * tree's postcode and locality nodes.
580
378
  */
581
379
  export function stampPostcodeCountryScope(roots: readonly AddressNode[], scope: PostcodeCountryScope): void {
582
380
  for (const n of walkNodes(roots)) {
@@ -585,12 +383,10 @@ export function stampPostcodeCountryScope(roots: readonly AddressNode[], scope:
585
383
  n.metadata = {
586
384
  ...n.metadata,
587
385
  postcode_country_scope: scope.country,
588
- // WHICH rung spoke — a two-sided agreement and a one-sided uniqueness claim are different evidence,
589
- // and a consumer that cannot tell them apart cannot weight them differently.
386
+
590
387
  postcode_country_scope_evidence: scope.evidence,
591
- // Only the `pair` rung measured a distance. Writing a 0 for the single-sided rungs would assert an
592
- // agreement nobody tested.
593
- ...(scope.distanceKm !== undefined ? { postcode_country_scope_km: scope.distanceKm } : {}),
388
+
389
+ ...(scope.distanceKm != null ? { postcode_country_scope_km: scope.distanceKm } : {}),
594
390
  }
595
391
  }
596
392
  }