@mailwoman/resolver 9.1.0 → 9.3.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 (142) hide show
  1. package/README.md +89 -0
  2. package/lib/admin/coherence-passes.ts +435 -0
  3. package/lib/admin/containment.ts +92 -0
  4. package/lib/admin/index.ts +10 -0
  5. package/lib/admin/jp-municipality.ts +97 -0
  6. package/lib/admin/winner.ts +189 -0
  7. package/lib/backend-capabilities.ts +88 -0
  8. package/lib/bare-toponym-race.ts +129 -0
  9. package/lib/decorate-node.ts +127 -0
  10. package/lib/fold-name.ts +36 -0
  11. package/{index.ts → lib/index.ts} +27 -18
  12. package/{plausibility.ts → lib/plausibility.ts} +5 -4
  13. package/{postcode-country-coherence.ts → lib/postcode/country-coherence.ts} +173 -86
  14. package/lib/postcode/index.ts +9 -0
  15. package/{postcode-prefix.ts → lib/postcode/prefix.ts} +7 -6
  16. package/{postcode-shape-coherence.ts → lib/postcode/shape-coherence.ts} +10 -24
  17. package/{remote-resolver.ts → lib/remote-resolver.ts} +13 -4
  18. package/{rerank.ts → lib/rerank.ts} +2 -2
  19. package/lib/resolve/index.ts +982 -0
  20. package/lib/resolve/passes.ts +544 -0
  21. package/{span-rescore.ts → lib/span-rescore.ts} +114 -99
  22. package/{street-evidence.ts → lib/street/evidence.ts} +40 -7
  23. package/lib/street/index.ts +8 -0
  24. package/{street-tier.ts → lib/street/tier.ts} +138 -99
  25. package/{toponym-prior.ts → lib/toponym-prior.ts} +97 -8
  26. package/out/admin/coherence-passes.d.ts +70 -0
  27. package/out/admin/coherence-passes.d.ts.map +1 -0
  28. package/out/admin/coherence-passes.js +327 -0
  29. package/out/admin/coherence-passes.js.map +1 -0
  30. package/out/admin/containment.d.ts +48 -0
  31. package/out/admin/containment.d.ts.map +1 -0
  32. package/out/admin/containment.js +76 -0
  33. package/out/admin/containment.js.map +1 -0
  34. package/out/admin/index.d.ts +10 -0
  35. package/out/admin/index.d.ts.map +1 -0
  36. package/out/admin/index.js +10 -0
  37. package/out/admin/index.js.map +1 -0
  38. package/out/admin/jp-municipality.d.ts +50 -0
  39. package/out/admin/jp-municipality.d.ts.map +1 -0
  40. package/out/admin/jp-municipality.js +54 -0
  41. package/out/admin/jp-municipality.js.map +1 -0
  42. package/out/admin/winner.d.ts +114 -0
  43. package/out/admin/winner.d.ts.map +1 -0
  44. package/out/admin/winner.js +130 -0
  45. package/out/admin/winner.js.map +1 -0
  46. package/out/backend-capabilities.d.ts +37 -0
  47. package/out/backend-capabilities.d.ts.map +1 -0
  48. package/out/backend-capabilities.js +75 -0
  49. package/out/backend-capabilities.js.map +1 -0
  50. package/out/bare-toponym-race.d.ts +55 -0
  51. package/out/bare-toponym-race.d.ts.map +1 -0
  52. package/out/bare-toponym-race.js +110 -0
  53. package/out/bare-toponym-race.js.map +1 -0
  54. package/out/decorate-node.d.ts +24 -0
  55. package/out/decorate-node.d.ts.map +1 -0
  56. package/out/decorate-node.js +103 -0
  57. package/out/decorate-node.js.map +1 -0
  58. package/out/fold-name.d.ts +18 -3
  59. package/out/fold-name.d.ts.map +1 -1
  60. package/out/fold-name.js +19 -3
  61. package/out/fold-name.js.map +1 -1
  62. package/out/index.d.ts +15 -12
  63. package/out/index.d.ts.map +1 -1
  64. package/out/index.js +9 -7
  65. package/out/index.js.map +1 -1
  66. package/out/plausibility.d.ts +5 -4
  67. package/out/plausibility.d.ts.map +1 -1
  68. package/out/plausibility.js +5 -4
  69. package/out/plausibility.js.map +1 -1
  70. package/out/{postcode-country-coherence.d.ts → postcode/country-coherence.d.ts} +46 -25
  71. package/out/postcode/country-coherence.d.ts.map +1 -0
  72. package/out/{postcode-country-coherence.js → postcode/country-coherence.js} +157 -77
  73. package/out/postcode/country-coherence.js.map +1 -0
  74. package/out/postcode/index.d.ts +9 -0
  75. package/out/postcode/index.d.ts.map +1 -0
  76. package/out/postcode/index.js +9 -0
  77. package/out/postcode/index.js.map +1 -0
  78. package/out/{postcode-prefix.d.ts → postcode/prefix.d.ts} +4 -4
  79. package/out/postcode/prefix.d.ts.map +1 -0
  80. package/out/{postcode-prefix.js → postcode/prefix.js} +7 -6
  81. package/out/postcode/prefix.js.map +1 -0
  82. package/out/{postcode-shape-coherence.d.ts → postcode/shape-coherence.d.ts} +3 -3
  83. package/out/postcode/shape-coherence.d.ts.map +1 -0
  84. package/out/{postcode-shape-coherence.js → postcode/shape-coherence.js} +11 -20
  85. package/out/postcode/shape-coherence.js.map +1 -0
  86. package/out/remote-resolver.d.ts +18 -3
  87. package/out/remote-resolver.d.ts.map +1 -1
  88. package/out/remote-resolver.js +2 -2
  89. package/out/remote-resolver.js.map +1 -1
  90. package/out/rerank.d.ts +1 -1
  91. package/out/rerank.d.ts.map +1 -1
  92. package/out/rerank.js +2 -2
  93. package/out/rerank.js.map +1 -1
  94. package/out/{resolve.d.ts → resolve/index.d.ts} +2 -2
  95. package/out/resolve/index.d.ts.map +1 -0
  96. package/out/resolve/index.js +795 -0
  97. package/out/resolve/index.js.map +1 -0
  98. package/out/resolve/passes.d.ts +218 -0
  99. package/out/resolve/passes.d.ts.map +1 -0
  100. package/out/resolve/passes.js +333 -0
  101. package/out/resolve/passes.js.map +1 -0
  102. package/out/span-rescore.d.ts +16 -16
  103. package/out/span-rescore.d.ts.map +1 -1
  104. package/out/span-rescore.js +87 -71
  105. package/out/span-rescore.js.map +1 -1
  106. package/out/{street-evidence.d.ts → street/evidence.d.ts} +18 -3
  107. package/out/street/evidence.d.ts.map +1 -0
  108. package/out/{street-evidence.js → street/evidence.js} +23 -7
  109. package/out/street/evidence.js.map +1 -0
  110. package/out/street/index.d.ts +8 -0
  111. package/out/street/index.d.ts.map +1 -0
  112. package/out/street/index.js +8 -0
  113. package/out/street/index.js.map +1 -0
  114. package/out/{street-tier.d.ts → street/tier.d.ts} +14 -3
  115. package/out/street/tier.d.ts.map +1 -0
  116. package/out/{street-tier.js → street/tier.js} +127 -90
  117. package/out/street/tier.js.map +1 -0
  118. package/out/toponym-prior.d.ts +43 -19
  119. package/out/toponym-prior.d.ts.map +1 -1
  120. package/out/toponym-prior.js +76 -8
  121. package/out/toponym-prior.js.map +1 -1
  122. package/package.json +167 -19
  123. package/vitest.config.ts +5 -6
  124. package/fold-name.ts +0 -20
  125. package/out/postcode-country-coherence.d.ts.map +0 -1
  126. package/out/postcode-country-coherence.js.map +0 -1
  127. package/out/postcode-prefix.d.ts.map +0 -1
  128. package/out/postcode-prefix.js.map +0 -1
  129. package/out/postcode-shape-coherence.d.ts.map +0 -1
  130. package/out/postcode-shape-coherence.js.map +0 -1
  131. package/out/resolve.d.ts.map +0 -1
  132. package/out/resolve.js +0 -1049
  133. package/out/resolve.js.map +0 -1
  134. package/out/street-evidence.d.ts.map +0 -1
  135. package/out/street-evidence.js.map +0 -1
  136. package/out/street-tier.d.ts.map +0 -1
  137. package/out/street-tier.js.map +0 -1
  138. package/out/vitest.config.d.ts +0 -16
  139. package/out/vitest.config.d.ts.map +0 -1
  140. package/out/vitest.config.js +0 -36
  141. package/out/vitest.config.js.map +0 -1
  142. package/resolve.ts +0 -1369
@@ -11,26 +11,21 @@
11
11
  * what used to be `@mailwoman/core/resolver`.
12
12
  */
13
13
 
14
- export { RemoteResolver, serializableResolveOpts } from "./remote-resolver.ts"
14
+ export { RemoteResolver, serializableResolveOpts } from "#remote-resolver"
15
15
 
16
16
  export type {
17
17
  RemoteResolverOpts,
18
18
  ResolveTreeRequest,
19
19
  ResolveTreeResponse,
20
20
  SerializableResolveOpts,
21
- } from "./remote-resolver.ts"
21
+ } from "#remote-resolver"
22
22
 
23
- export { createWOFResolver } from "./resolve.ts"
23
+ export { createWOFResolver } from "#resolve"
24
24
 
25
- export {
26
- COUNTRY_BBOX,
27
- finestResolvedCoordinate,
28
- isImplausibleResolution,
29
- outsideExpectedCountry,
30
- } from "./plausibility.ts"
25
+ export { COUNTRY_BBOX, finestResolvedCoordinate, isImplausibleResolution, outsideExpectedCountry } from "#plausibility"
31
26
 
32
- export type { PlausibilityOpts, PlausibilityVerdict, ResolvedCoordinate } from "./plausibility.ts"
33
- export { foldStreetSurface, isPureTypeVocabulary, pickByStreetEvidence } from "./street-evidence.ts"
27
+ export type { PlausibilityOpts, PlausibilityVerdict, ResolvedCoordinate } from "#plausibility"
28
+ export { foldStreetSurface, isPureTypeVocabulary, pickByStreetEvidence } from "#street/evidence"
34
29
 
35
30
  export type {
36
31
  PickByStreetEvidenceOpts,
@@ -38,21 +33,35 @@ export type {
38
33
  StreetEvidencePick,
39
34
  StreetEvidenceScope,
40
35
  StreetLocalityEvidence,
41
- } from "./street-evidence.ts"
36
+ } from "#street/evidence"
42
37
 
43
38
  export {
44
39
  findPostcodeCountryScope,
45
40
  firstLocalityValue,
46
- POSTCODE_COUNTRY_COHERENCE_GATE_KM,
41
+ localityValuesInDocumentOrder,
42
+ POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM,
47
43
  stampPostcodeCountryScope,
48
- } from "./postcode-country-coherence.ts"
44
+ } from "#postcode/country-coherence"
45
+
46
+ export type { PostcodeCountryScope, PostcodeCountryScopeOpts } from "#postcode/country-coherence"
47
+ export { findRescoreCandidate, hasResolvedPlace } from "#span-rescore"
48
+ export type { RescoreCandidate, SpanRescoreOptions } from "#span-rescore"
49
+ export { adminContainmentVerdict, partitionByContainment } from "#admin/containment"
50
+
51
+ export {
52
+ ADMIN_LADDER_LOCALITY_FIRST,
53
+ ADMIN_LADDER_POSTCODE_FIRST,
54
+ adminLadderFor,
55
+ adminLadderForNodes,
56
+ AREA_GRADE_POSTALCODE_SPECIFICITY,
57
+ mostSpecificResolved,
58
+ resolvedSpecificity,
59
+ } from "#admin/winner"
49
60
 
50
- export type { PostcodeCountryScope, PostcodeCountryScopeOpts } from "./postcode-country-coherence.ts"
51
- export { findRescoreCandidate, hasResolvedPlace } from "./span-rescore.ts"
52
- export type { RescoreCandidate, SpanRescoreOptions } from "./span-rescore.ts"
61
+ export type { ResolvedPostcodeHit, ResolvedSpecificityInput } from "#admin/winner"
53
62
 
54
63
  // The type contract + placetype helpers live in core (pure types, keep core a leaf). Re-export so
55
64
  // consumers get the whole surface from `@mailwoman/resolver`.
56
65
  export * from "@mailwoman/core/resolver"
57
66
 
58
- export * from "./rerank.ts"
67
+ export * from "#rerank"
@@ -188,10 +188,11 @@ export interface PlausibilityOpts {
188
188
  }
189
189
 
190
190
  /**
191
- * Decide whether a resolved tree's geocode is implausible for a structured address — the cheap guard the v7 hybrid gate
192
- * runs after routing an input to the neural parser (#38). Trips when the finest resolved place is a bare `country`
193
- * centroid (guard A), or — when the caller supplies `expectedCountry` — when the served coordinate falls outside that
194
- * country's coarse bbox (guard B). An unresolved tree (nothing to serve) is plausible: there is no garbage to serve.
191
+ * Decide whether a resolved tree's geocode is implausible for a structured address — the cheap guard the v7 hybrid
192
+ * check runs after routing an input to the neural parser (#38). Trips when the finest resolved place is a bare
193
+ * `country` centroid (guard A), or — when the caller supplies `expectedCountry` — when the served coordinate falls
194
+ * outside that country's coarse bbox (guard B). An unresolved tree (nothing to serve) is plausible: there is no garbage
195
+ * to serve.
195
196
  */
196
197
  export function isImplausibleResolution(tree: AddressTree, opts: PlausibilityOpts = {}): PlausibilityVerdict {
197
198
  const coordinate = finestResolvedCoordinate(tree)
@@ -11,13 +11,13 @@
11
11
  * turns THAT into a hard `spr.country = 'US'` WHERE clause. The candidate pool is all-US before
12
12
  * ranking begins, so a coarse placer that already called this address FR at confidence
13
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 shards attached
14
+ * construction. Population then picks Paris, Texas (pop 24,969). With the postal extracts attached
15
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 gate (the nearest is
16
+ * Addison TX), `applyPostcodeConsistency` finds no Paris within its 50 km check (the nearest is
17
17
  * 143.8 km), and falls the locality coordinate back to the ZIP point. See
18
18
  * `docs/records/evals/2026-08-03-postcode-locality-scoping.md` for the instrumented diagnosis.
19
19
  *
20
- * No pattern-only lever can fix this. `75001` is NOT unambiguously French:
20
+ * No pattern-only change can fix this. `75001` is NOT unambiguously French:
21
21
  * `candidateSystemsForPostcode("75001")` returns `["us", "de", "fr"]`, and the 2026-08-04
22
22
  * candidate gazetteer holds the literal string in FOUR countries — FR 48.863,2.336 (Paris 1er),
23
23
  * US 32.960,-96.838 (Addison TX), DE 48.844,9.367, PL 54.190,16.188 (×2 rows). The SHAPE is
@@ -40,7 +40,7 @@
40
40
  * `state.defaultCountry` for the whole walk. Everything downstream — including the three post-walk
41
41
  * coherence passes and the street/rooftop tiers — then sees the corrected country.
42
42
  *
43
- * ## Why it is not a hard veto (the doctrine gate)
43
+ * ## Why it is not a hard veto (the doctrine check)
44
44
  *
45
45
  * Registries are SOFT priors here, positive evidence only. Two properties keep this one honest:
46
46
  *
@@ -76,26 +76,28 @@
76
76
  * the whole gazetteer. See {@link PostcodeCountryScopeEvidence}.
77
77
  *
78
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, and any corroboration at home — the
80
- * address's own city or its own postcode existing in the default country — stops the pass dead.
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).
81
83
  *
82
84
  * ## Evidence
83
85
  *
84
86
  * Prototyped out-of-tree against the live gazetteer over the public `findPlace` surface (2026-08-03):
85
87
  * 400 real US (ZIP, city) pairs from `postalcode-us.db` + 400 real FR (CP, commune) pairs from
86
88
  * `postcode-locality-fr.db` — 800 pairs, **zero** border crossings, at both the 15 km and 25 km
87
- * gates. The 22 US abstentions were pairs whose ZIP parent name is not an exact-matching locality
89
+ * checks. The 22 US abstentions were pairs whose ZIP parent name is not an exact-matching locality
88
90
  * in the admin gazetteer (a recall gap; abstention is the safe outcome). The confound board's
89
- * verdicts were identical at 15, 25 AND 50 km, so the mechanism is not gate-tuned; the default
91
+ * verdicts were identical at 15, 25 AND 50 km, so the mechanism is not check-tuned; the default
90
92
  * below is the 25 km the scale run measured.
91
93
  *
92
94
  * Cost: 2 lookups on the byte-stable path (postcode + locality under the default country), and at
93
- * most `2 × |candidateSystems|` — bounded at 8, since a numeric shape matches at most `us`/`de`/`fr`
94
- * — when the default is incoherent. Nothing runs at all unless a `defaultCountry` is in force AND
95
- * the tree carries both a postcode and a locality.
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.
96
98
  *
97
99
  * **Default-ON** since the operator promotion of 2026-08-05 (#1477) — the resolver gauntlet, pinned
98
- * both ways, returned zero newly-failing gated cases, and 56,000 pair evaluations across both
100
+ * both ways, returned zero newly-failing conditional cases, and 56,000 pair evaluations across both
99
101
  * backends returned zero false positives. `ResolveOpts.postcodeCountryCoherence: false` opts out,
100
102
  * and the walk is byte-stable then. Receipts:
101
103
  * `docs/records/evals/2026-08-05-postcode-coherence-default-on-evidence.md`.
@@ -104,21 +106,21 @@
104
106
  // `postcode-systems` has no dedicated export subpath; the barrel is where every other consumer
105
107
  // (`neural/postcode-anchor.ts`) reaches it from.
106
108
  import { candidateSystemsForPostcode } from "@mailwoman/codex"
107
- import type { AddressNode } from "@mailwoman/core/decoder"
109
+ import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
108
110
  import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
109
111
  import { haversineKm } from "@mailwoman/spatial"
110
112
 
111
113
  /**
112
- * Default gate radius (km) for the postcode↔locality consistency test. 25 km is what the 800-pair scale run measured;
114
+ * Default check radius (km) for the postcode↔locality consistency test. 25 km is what the 800-pair scale run measured;
113
115
  * the confound board returned identical verdicts at 15, 25 and 50, so this is a floor choice, not a tuned one.
114
116
  */
115
- export const POSTCODE_COUNTRY_COHERENCE_GATE_KM = 25
117
+ export const POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM = 25
116
118
 
117
119
  /**
118
120
  * Which half (or halves) of the address bought the verdict — the firing receipt, so a reader of a scoped result can
119
121
  * tell a two-sided agreement from a one-sided uniqueness claim without re-deriving it.
120
122
  *
121
- * - `pair` — postcode AND locality both resolve in this country, within the gate. The strongest rung and the only one
123
+ * - `pair` — postcode AND locality both resolve in this country, within the radius. The strongest rung and the only one
122
124
  * that existed before #24.
123
125
  * - `locality` — the locality names exactly one country in the whole gazetteer, and the postcode names none that
124
126
  * contradict it. This is the CH/BE class: the gazetteer carries no Swiss or Belgian postcodes at all, so the pair
@@ -149,7 +151,7 @@ export interface PostcodeCountryScope {
149
151
  */
150
152
  evidence: PostcodeCountryScopeEvidence
151
153
  /**
152
- * Distance between the resolved postcode point and the nearest same-named locality, in km. Always `<= gateKm`.
154
+ * Distance between the resolved postcode point and the nearest same-named locality, in km. Always `<= thresholdKm`.
153
155
  * Present ONLY for the `pair` rung — a single-sided verdict has no two points to measure between, and reporting a `0`
154
156
  * there would assert an agreement nobody tested (the meaning-of-zero rule).
155
157
  */
@@ -171,14 +173,16 @@ export interface PostcodeCountryScopeOpts {
171
173
  */
172
174
  postcode: string
173
175
  /**
174
- * The country the caller's `defaultCountry` would hard-filter to. Required: this pass exists to correct a wrong one,
175
- * so with no default there is nothing to correct and the caller should not be calling.
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.
176
180
  */
177
- defaultCountry: string
181
+ defaultCountry: string | undefined
178
182
  /**
179
- * Consistency gate radius in km. Defaults to {@link POSTCODE_COUNTRY_COHERENCE_GATE_KM}.
183
+ * Consistency check radius in km. Defaults to {@link POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM}.
180
184
  */
181
- gateKm?: number
185
+ thresholdKm?: number
182
186
  /**
183
187
  * Optional narrowing of the SHAPE half of the candidate-country set — the shape-coherence pass's intersection for a
184
188
  * CONFIRMED postcode span (see `resolver/postcode-shape-coherence.ts`, #31 Mechanism 1). When present it REPLACES
@@ -193,30 +197,67 @@ export interface PostcodeCountryScopeOpts {
193
197
  }
194
198
 
195
199
  /**
196
- * A usable coordinate — the gazetteer stores an unlocated row as 0,0, which haversine would happily measure against.
200
+ * A usable coordinate — the gazetteer stores an unlocated row as 0,0, which haversine would measure against.
197
201
  */
198
202
  function hasCoord(p: ResolvedPlace): boolean {
199
203
  return p.lat !== 0 || p.lon !== 0
200
204
  }
201
205
 
202
206
  /**
203
- * The address's locality string: the first `locality` node anywhere in the tree, else the first `dependent_locality`.
204
- * Two passes so a real locality always beats a dependent one regardless of tree order.
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.
205
209
  */
206
- export function firstLocalityValue(roots: readonly AddressNode[]): string | undefined {
210
+ const MAX_LOCALITY_VALUES = 3
211
+
212
+ /**
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.
216
+ *
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.
228
+ */
229
+ export function localityValuesInDocumentOrder(roots: readonly AddressNode[]): string[] {
230
+ const out: string[] = []
231
+ const seen = new Set<string>()
232
+
207
233
  for (const tag of ["locality", "dependent_locality"] as const) {
208
- const stack = [...roots]
234
+ collectInDocumentOrder(roots, tag, out, seen)
235
+ }
209
236
 
210
- while (stack.length) {
211
- const n = stack.pop()!
237
+ return out.slice(0, MAX_LOCALITY_VALUES)
238
+ }
212
239
 
213
- if (n.tag === tag && n.value.trim().length) return n.value.trim()
240
+ /**
241
+ * The first of {@link localityValuesInDocumentOrder} — the locality the address is about.
242
+ */
243
+ export function firstLocalityValue(roots: readonly AddressNode[]): string | undefined {
244
+ return localityValuesInDocumentOrder(roots)[0]
245
+ }
246
+
247
+ function collectInDocumentOrder(nodes: readonly AddressNode[], tag: string, out: string[], seen: Set<string>): void {
248
+ for (const n of nodes) {
249
+ if (n.tag === tag && n.value.trim().length) {
250
+ const value = n.value.trim()
251
+ const key = value.toLowerCase()
214
252
 
215
- stack.push(...n.children)
253
+ if (!seen.has(key)) {
254
+ seen.add(key)
255
+ out.push(value)
256
+ }
216
257
  }
217
- }
218
258
 
219
- return undefined
259
+ collectInDocumentOrder(n.children, tag, out, seen)
260
+ }
220
261
  }
221
262
 
222
263
  /**
@@ -256,14 +297,15 @@ async function countriesHolding(
256
297
  backend: ResolverBackend,
257
298
  text: string,
258
299
  placetype: "postalcode" | "locality",
259
- limit: number
300
+ limit: number,
301
+ opts?: { primaryOnly?: boolean }
260
302
  ): Promise<Map<string, ResolvedPlace>> {
261
303
  const out = new Map<string, ResolvedPlace>()
262
304
 
263
305
  let hits: ResolvedPlace[]
264
306
 
265
307
  try {
266
- hits = await backend.findPlace({ text, placetype, limit })
308
+ hits = await backend.findPlace({ text, placetype, limit, ...(opts?.primaryOnly ? { primaryOnly: true } : {}) })
267
309
  } catch {
268
310
  return out // a backend hiccup degrades to "no evidence", never to a crashed resolve
269
311
  }
@@ -284,15 +326,16 @@ async function countriesHolding(
284
326
  /**
285
327
  * Is the (postcode, locality) pair geographically consistent in `country`? Returns the winning pair and its distance,
286
328
  * or `null` when the postcode does not resolve there, no same-named locality exists there, or the nearest one is
287
- * outside the gate. Costs one postcode lookup plus (only if that hit) one locality lookup — or just the locality lookup
288
- * when the caller already knows the country's postcode row (`knownPostcodePlace`, from the exhaustive unscoped probe).
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).
289
332
  */
290
333
  async function coherenceIn(
291
334
  country: string,
292
335
  postcode: string,
293
336
  locality: string,
294
337
  backend: ResolverBackend,
295
- gateKm: number,
338
+ thresholdKm: number,
296
339
  knownPostcodePlace?: ResolvedPlace
297
340
  ): Promise<{ postcodePlace: ResolvedPlace; localityPlace: ResolvedPlace; distanceKm: number } | null> {
298
341
  let postcodePlace = knownPostcodePlace
@@ -328,7 +371,7 @@ async function coherenceIn(
328
371
  if (!candidate.exactMatch || !hasCoord(candidate)) continue
329
372
  const distanceKm = haversineKm(postcodePlace.lat, postcodePlace.lon, candidate.lat, candidate.lon)
330
373
 
331
- if (distanceKm > gateKm) continue
374
+ if (distanceKm > thresholdKm) continue
332
375
 
333
376
  if (!best || distanceKm < best.distanceKm) {
334
377
  best = { localityPlace: candidate, distanceKm }
@@ -358,22 +401,28 @@ export async function findPostcodeCountryScope(
358
401
  opts: PostcodeCountryScopeOpts
359
402
  ): Promise<PostcodeCountryScope | null> {
360
403
  const postcode = opts.postcode.trim()
361
- const defaultCountry = opts.defaultCountry.trim().toUpperCase()
404
+ const defaultCountry = opts.defaultCountry?.trim().toUpperCase() || undefined
362
405
 
363
- if (!postcode || !defaultCountry) return null
406
+ if (!postcode) return null
364
407
 
365
- const locality = firstLocalityValue(roots)
408
+ const localities = localityValuesInDocumentOrder(roots)
366
409
 
367
410
  // Both halves of the pair are required. A postcode with no locality has nothing to be coherent WITH, which is what
368
411
  // keeps this pass inert on "Springfield, IL 62701" (the parser tags Springfield as a `street` — a separate defect)
369
412
  // and on every bare-postcode query.
370
- if (!locality) return null
413
+ if (!localities.length) return null
371
414
 
372
- const gateKm = opts.gateKm ?? POSTCODE_COUNTRY_COHERENCE_GATE_KM
415
+ const thresholdKm = opts.thresholdKm ?? POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM
373
416
 
374
- // 1. Is the caller's own default country coherent? If so we are done — positive evidence for the default,
375
- // no override, and the common domestic path costs two lookups and changes nothing.
376
- if (await coherenceIn(defaultCountry, postcode, locality, backend, gateKm)) return null
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
+ if (defaultCountry) {
422
+ for (const locality of localities) {
423
+ if (await coherenceIn(defaultCountry, postcode, locality, backend, thresholdKm)) return null
424
+ }
425
+ }
377
426
 
378
427
  // 2. The default could not place this pair. Which countries could? Two sources, unioned:
379
428
  //
@@ -397,22 +446,33 @@ export async function findPostcodeCountryScope(
397
446
  .filter((country) => country !== defaultCountry)
398
447
  .slice(0, MAX_CANDIDATE_COUNTRIES)
399
448
 
400
- const coherent: PostcodeCountryScope[] = []
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
+ for (const locality of localities) {
456
+ const coherent: PostcodeCountryScope[] = []
457
+
458
+ for (const country of candidates) {
459
+ const hit = await coherenceIn(country, postcode, locality, backend, thresholdKm, pcHolders.get(country))
460
+
461
+ if (hit) {
462
+ coherent.push({ country, postcode, locality, evidence: "pair", ...hit })
463
+ }
464
+ }
401
465
 
402
- for (const country of candidates) {
403
- const hit = await coherenceIn(country, postcode, locality, backend, gateKm, pcHolders.get(country))
466
+ if (coherent.length === 1) return coherent[0]!
404
467
 
405
- if (hit) {
406
- coherent.push({ country, postcode, locality, evidence: "pair", ...hit })
407
- }
468
+ if (coherent.length > 1) return null
408
469
  }
409
470
 
410
- // 3. Exactly one country makes the pair consistent, or we fall through. Two coherent countries mean the geometry
411
- // genuinely does not decide, and guessing between them is precisely what this mechanism exists not to do — so a
412
- // TIE is a hard abstention, never a fall-through to the weaker rungs below.
413
- if (coherent.length === 1) return coherent[0]!
414
-
415
- if (coherent.length > 1) return null
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
+ if (!defaultCountry) return null
416
476
 
417
477
  // 4. No country makes the PAIR consistent. On the 2026-08-09 panel that happened 10 times for two opposite
418
478
  // reasons, and in both the address's country was never in doubt — only unrepresentable as a pair:
@@ -421,42 +481,75 @@ export async function findPostcodeCountryScope(
421
481
  // agree with anything no matter how good the locality evidence is; or
422
482
  // - the locality is a name no admin gazetteer carries (`Praha 3`, `Praha 9` — municipal districts).
423
483
  //
424
- // So each half gets to speak alone, under two conditions that keep this from becoming a guess. First, the
425
- // DEFAULT country must corroborate NEITHER half — if the address's own city or its own postcode exists at
426
- // home, the address is domestically plausible and nothing foreign may be proposed (this is what holds
427
- // `123 Main St, Vienna, VA 22180` in Virginia even though Wien is the vastly more prominent Vienna).
428
- // Second, the speaking half must name EXACTLY ONE country in the entire gazetteer — the same uniqueness bar
429
- // the pair rung uses, applied to one side.
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.
430
495
  if (pcHolders.has(defaultCountry)) return null
431
496
 
432
- if (await holdsLocality(backend, locality, defaultCountry)) return null
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
+ let anyDomestic = false
507
+ let anyLocalityKnown = false
508
+ const verdicts = new Map<string, PostcodeCountryScope>()
509
+
510
+ for (const locality of localities) {
511
+ if (await holdsLocality(backend, locality, defaultCountry)) {
512
+ anyDomestic = true
513
+
514
+ continue
515
+ }
433
516
 
434
- // 4a. The locality names exactly one country. Stronger than the postcode rung — a place name is far more
435
- // discriminative than a four-digit code — so it is tried first. It stands down when that country's OWN
436
- // postcode row contradicts the locality (outside the gate): the two halves disagreeing inside one country
437
- // is exactly what the pair test exists to catch, and a single-sided rung must not launder it.
438
- const locHolders = await countriesHolding(backend, locality, "locality", LOCALITY_HOLDER_FETCH)
517
+ const locHolders = await countriesHolding(backend, locality, "locality", LOCALITY_HOLDER_FETCH, {
518
+ primaryOnly: true,
519
+ })
520
+
521
+ if (locHolders.size) {
522
+ anyLocalityKnown = true
523
+ }
524
+
525
+ if (locHolders.size !== 1) continue
439
526
 
440
- if (locHolders.size === 1) {
441
527
  const [country, localityPlace] = [...locHolders.entries()][0]!
442
528
  const ownPostcode = pcHolders.get(country)
443
529
 
444
530
  const contradicted =
445
531
  ownPostcode !== undefined &&
446
- haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > gateKm
532
+ haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > thresholdKm
447
533
 
448
- if (country !== defaultCountry && !contradicted) {
449
- return { country, postcode, locality, evidence: "locality", localityPlace }
534
+ if (country !== defaultCountry && !contradicted && !verdicts.has(country)) {
535
+ verdicts.set(country, { country, postcode, locality, evidence: "locality", localityPlace })
450
536
  }
451
537
  }
452
538
 
453
- // 4b. The locality is in no gazetteer (or names several countries) and the postcode is held in exactly one.
454
- // `Biskupcova 1843/3, 13000 Praha 3`: `13000` is a CZ code and nothing else, anywhere.
455
- if (!locHolders.size && pcHolders.size === 1) {
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
+ if (verdicts.size === 1) return [...verdicts.values()][0]!
542
+
543
+ if (verdicts.size > 1) return null
544
+
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
+ if (!anyDomestic && !anyLocalityKnown && pcHolders.size === 1) {
456
549
  const [country, postcodePlace] = [...pcHolders.entries()][0]!
457
550
 
458
551
  if (country !== defaultCountry) {
459
- return { country, postcode, locality, evidence: "postcode", postcodePlace }
552
+ return { country, postcode, locality: localities[0]!, evidence: "postcode", postcodePlace }
460
553
  }
461
554
  }
462
555
 
@@ -486,13 +579,7 @@ async function holdsLocality(backend: ResolverBackend, locality: string, country
486
579
  * untouched, this only writes `metadata`.
487
580
  */
488
581
  export function stampPostcodeCountryScope(roots: readonly AddressNode[], scope: PostcodeCountryScope): void {
489
- const stack: AddressNode[] = [...roots]
490
-
491
- while (stack.length) {
492
- const n = stack.pop()!
493
-
494
- stack.push(...n.children)
495
-
582
+ for (const n of walkNodes(roots)) {
496
583
  if (n.tag !== "postcode" && n.tag !== "locality" && n.tag !== "dependent_locality") continue
497
584
 
498
585
  n.metadata = {
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "#postcode/country-coherence"
8
+ export * from "#postcode/prefix"
9
+ export * from "#postcode/shape-coherence"
@@ -29,7 +29,7 @@
29
29
  * acquisition) — the branch exists so the law is tested before the data.
30
30
  * - **Anything else** — abstain (null).
31
31
  *
32
- * ## The probe's country gate
32
+ * ## The probe's country restriction
33
33
  *
34
34
  * The index is country-specific EVIDENCE: it is only probed when its `country` matches the
35
35
  * query's country scope (or the scope is absent). A GB index must not speak under a US scope —
@@ -63,7 +63,7 @@ import type { PostcodePrefixIndexLike, PostcodePrefixNode, ResolvedPlace } from
63
63
  * even the 0,0 unlocated sentinel), and the prefix prior's ancestry-only tier must express absence as `undefined`
64
64
  * instead — B3-3: inventing a centroid would reproduce the `BT3 9QQ` → Sheffield defect #1480. `decorateNode` copies
65
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`.
66
+ * Widened ONLY at this boundary: gazetteer places (always coordinate-bearing) remain plain `ResolvedPlace`.
67
67
  */
68
68
  export type CoordinateOptionalPlace = Omit<ResolvedPlace, "lat" | "lon"> & { lat?: number; lon?: number }
69
69
 
@@ -92,8 +92,9 @@ export function derivePostcodePrefix(code: string, country?: string): string | n
92
92
  // "BT93GS" → "BT9"). Exactly 3 — never a greedy regex, the build-side twin is `outwardOf`.
93
93
  case "GB":
94
94
  return compact.length >= MIN_GB_OUTWARD_CODE_LENGTH ? compact.slice(0, -3) : null
95
- // The 3-digit section ("94043" → "940"). No US artifact ships yet (B3-4 is ZCTA acquisition);
96
- // the law is tested ahead of the data.
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.
97
98
  case "US":
98
99
  return compact.length >= MIN_US_SECTION_CODE_LENGTH ? compact.slice(0, 3) : null
99
100
  default:
@@ -116,7 +117,7 @@ export interface PostcodePrefixProbeResult {
116
117
  }
117
118
 
118
119
  /**
119
- * Probe the index for `code`'s prefix. Two abstention gates, in order: the index's country must match the query's
120
+ * Probe the index for `code`'s prefix. Two abstention checks, in order: the index's country must match the query's
120
121
  * country scope (or the scope is absent), and the derivation law must yield a prefix the index carries. Returns null to
121
122
  * abstain — never throws, never guesses.
122
123
  */
@@ -127,7 +128,7 @@ export function probePostcodePrefix(
127
128
  ): PostcodePrefixProbeResult | null {
128
129
  const indexCountry = index.country?.toUpperCase()
129
130
 
130
- // Country gate: the index is evidence FOR its own country only. A GB index under a US scope stays
131
+ // Country check: the index is evidence FOR its own country only. A GB index under a US scope stays
131
132
  // silent — the walk's country filter is the caller's declared universe.
132
133
  if (queryCountry && indexCountry && queryCountry.toUpperCase() !== indexCountry) return null
133
134