@mailwoman/resolver 8.6.0 → 9.1.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 (39) hide show
  1. package/index.ts +8 -0
  2. package/out/index.d.ts +2 -0
  3. package/out/index.d.ts.map +1 -1
  4. package/out/index.js +1 -0
  5. package/out/index.js.map +1 -1
  6. package/out/postcode-country-coherence.d.ts +211 -0
  7. package/out/postcode-country-coherence.d.ts.map +1 -0
  8. package/out/postcode-country-coherence.js +369 -0
  9. package/out/postcode-country-coherence.js.map +1 -0
  10. package/out/postcode-prefix.d.ts +101 -0
  11. package/out/postcode-prefix.d.ts.map +1 -0
  12. package/out/postcode-prefix.js +124 -0
  13. package/out/postcode-prefix.js.map +1 -0
  14. package/out/postcode-shape-coherence.d.ts +113 -0
  15. package/out/postcode-shape-coherence.d.ts.map +1 -0
  16. package/out/postcode-shape-coherence.js +193 -0
  17. package/out/postcode-shape-coherence.js.map +1 -0
  18. package/out/resolve.d.ts.map +1 -1
  19. package/out/resolve.js +183 -17
  20. package/out/resolve.js.map +1 -1
  21. package/out/span-rescore.d.ts +28 -0
  22. package/out/span-rescore.d.ts.map +1 -1
  23. package/out/span-rescore.js +98 -6
  24. package/out/span-rescore.js.map +1 -1
  25. package/out/street-tier.d.ts.map +1 -1
  26. package/out/street-tier.js +2 -0
  27. package/out/street-tier.js.map +1 -1
  28. package/out/toponym-prior.d.ts +115 -0
  29. package/out/toponym-prior.d.ts.map +1 -0
  30. package/out/toponym-prior.js +240 -0
  31. package/out/toponym-prior.js.map +1 -0
  32. package/package.json +12 -4
  33. package/postcode-country-coherence.ts +509 -0
  34. package/postcode-prefix.ts +165 -0
  35. package/postcode-shape-coherence.ts +248 -0
  36. package/resolve.ts +247 -23
  37. package/span-rescore.ts +144 -6
  38. package/street-tier.ts +2 -0
  39. package/toponym-prior.ts +278 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toponym-prior.js","sourceRoot":"","sources":["../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AC,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IAChD,CAAC;IAED,OAAO,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,yBAAyB,CAAC,EAAE,GAAG,eAAe,CAAC,IAAI,EAAE,yBAAyB,CAAC,CAAC,CAAA;AACnH,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,kBAAkB,CACjC,UAAwB,EACxB,OAA2B,EAC3B,SAAiB,4BAA4B;IAE7C,IAAI,CAAC,OAAO,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,CAAC,GAAG,UAAU,CAAC,CAAA;IAC7D,MAAM,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAA;IAEpC,MAAM,GAAG,GAAG,CAAC,CAAI,EAAU,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,EAAE,WAAW,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAE1F,OAAO,cAAc,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;AAC7D,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mailwoman/resolver",
3
- "version": "8.6.0",
3
+ "version": "9.1.0",
4
4
  "description": "The address resolver: walk an AddressTree, decorate nodes with gazetteer-supplied coordinates + attribution. Backend-agnostic (any ResolverBackend), with the span-rescore + postcode-consistency levers. Lifted out of @mailwoman/core so it can depend on @mailwoman/spatial (haversine) + @mailwoman/codex (USPS directionals) instead of reinventing them; the type contract stays in core so the pipeline composes it without a cycle.",
5
5
  "license": "AGPL-3.0-only OR LicenseRef-Commercial",
6
6
  "repository": {
@@ -33,6 +33,10 @@
33
33
  "types": "./out/resolve.d.ts",
34
34
  "default": "./out/resolve.js"
35
35
  },
36
+ "./postcode-country-coherence": {
37
+ "types": "./out/postcode-country-coherence.d.ts",
38
+ "default": "./out/postcode-country-coherence.js"
39
+ },
36
40
  "./span-rescore": {
37
41
  "types": "./out/span-rescore.d.ts",
38
42
  "default": "./out/span-rescore.js"
@@ -50,6 +54,10 @@
50
54
  "types": "./out/resolve.d.ts",
51
55
  "default": "./out/resolve.js"
52
56
  },
57
+ "./postcode-country-coherence": {
58
+ "types": "./out/postcode-country-coherence.d.ts",
59
+ "default": "./out/postcode-country-coherence.js"
60
+ },
53
61
  "./span-rescore": {
54
62
  "types": "./out/span-rescore.d.ts",
55
63
  "default": "./out/span-rescore.js"
@@ -57,8 +65,8 @@
57
65
  }
58
66
  },
59
67
  "dependencies": {
60
- "@mailwoman/codex": "8.6.0",
61
- "@mailwoman/core": "8.6.0",
62
- "@mailwoman/spatial": "8.6.0"
68
+ "@mailwoman/codex": "9.1.0",
69
+ "@mailwoman/core": "9.1.0",
70
+ "@mailwoman/spatial": "9.1.0"
63
71
  }
64
72
  }
@@ -0,0 +1,509 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
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 shards 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 gate (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 lever 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 gate)
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, and any corroboration at home — the
80
+ * address's own city or its own postcode existing in the default country — stops the pass dead.
81
+ *
82
+ * ## Evidence
83
+ *
84
+ * Prototyped out-of-tree against the live gazetteer over the public `findPlace` surface (2026-08-03):
85
+ * 400 real US (ZIP, city) pairs from `postalcode-us.db` + 400 real FR (CP, commune) pairs from
86
+ * `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
88
+ * 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
90
+ * below is the 25 km the scale run measured.
91
+ *
92
+ * 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.
96
+ *
97
+ * **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
99
+ * backends returned zero false positives. `ResolveOpts.postcodeCountryCoherence: false` opts out,
100
+ * and the walk is byte-stable then. Receipts:
101
+ * `docs/records/evals/2026-08-05-postcode-coherence-default-on-evidence.md`.
102
+ */
103
+
104
+ // `postcode-systems` has no dedicated export subpath; the barrel is where every other consumer
105
+ // (`neural/postcode-anchor.ts`) reaches it from.
106
+ import { candidateSystemsForPostcode } from "@mailwoman/codex"
107
+ import type { AddressNode } from "@mailwoman/core/decoder"
108
+ import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
109
+ import { haversineKm } from "@mailwoman/spatial"
110
+
111
+ /**
112
+ * Default gate radius (km) for the postcode↔locality consistency test. 25 km is what the 800-pair scale run measured;
113
+ * the confound board returned identical verdicts at 15, 25 and 50, so this is a floor choice, not a tuned one.
114
+ */
115
+ export const POSTCODE_COUNTRY_COHERENCE_GATE_KM = 25
116
+
117
+ /**
118
+ * Which half (or halves) of the address bought the verdict — the firing receipt, so a reader of a scoped result can
119
+ * tell a two-sided agreement from a one-sided uniqueness claim without re-deriving it.
120
+ *
121
+ * - `pair` — postcode AND locality both resolve in this country, within the gate. The strongest rung and the only one
122
+ * that existed before #24.
123
+ * - `locality` — the locality names exactly one country in the whole gazetteer, and the postcode names none that
124
+ * contradict it. This is the CH/BE class: the gazetteer carries no Swiss or Belgian postcodes at all, so the pair
125
+ * test can never fire there no matter how good the locality evidence is.
126
+ * - `postcode` — the postcode is held in exactly one country and the locality is in no gazetteer at all. The `Praha 3`
127
+ * class: a municipal district nobody's admin gazetteer names.
128
+ */
129
+ export type PostcodeCountryScopeEvidence = "pair" | "locality" | "postcode"
130
+
131
+ /**
132
+ * A country in which the address's own evidence is geographically consistent.
133
+ */
134
+ export interface PostcodeCountryScope {
135
+ /**
136
+ * ISO-3166 alpha-2, upper-case.
137
+ */
138
+ country: string
139
+ /**
140
+ * The postcode string the verdict was reached on (as it appears in the tree).
141
+ */
142
+ postcode: string
143
+ /**
144
+ * The locality string the verdict was reached on.
145
+ */
146
+ locality: string
147
+ /**
148
+ * Which evidence carried the verdict. See {@link PostcodeCountryScopeEvidence}.
149
+ */
150
+ evidence: PostcodeCountryScopeEvidence
151
+ /**
152
+ * Distance between the resolved postcode point and the nearest same-named locality, in km. Always `<= gateKm`.
153
+ * Present ONLY for the `pair` rung — a single-sided verdict has no two points to measure between, and reporting a `0`
154
+ * there would assert an agreement nobody tested (the meaning-of-zero rule).
155
+ */
156
+ distanceKm?: number
157
+ /**
158
+ * The postcode place that anchored the verdict. Absent on the `locality` rung.
159
+ */
160
+ postcodePlace?: ResolvedPlace
161
+ /**
162
+ * The locality place that anchored the verdict. Absent on the `postcode` rung.
163
+ */
164
+ localityPlace?: ResolvedPlace
165
+ }
166
+
167
+ export interface PostcodeCountryScopeOpts {
168
+ /**
169
+ * The postcode string from the tree (the resolver already pre-scans for it — pass `state.postcode` so this pass and
170
+ * the walk can never disagree about WHICH postcode is the address's).
171
+ */
172
+ postcode: string
173
+ /**
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
+ */
177
+ defaultCountry: string
178
+ /**
179
+ * Consistency gate radius in km. Defaults to {@link POSTCODE_COUNTRY_COHERENCE_GATE_KM}.
180
+ */
181
+ gateKm?: number
182
+ /**
183
+ * Optional narrowing of the SHAPE half of the candidate-country set — the shape-coherence pass's intersection for a
184
+ * CONFIRMED postcode span (see `resolver/postcode-shape-coherence.ts`, #31 Mechanism 1). When present it REPLACES
185
+ * `candidateSystemsForPostcode`'s own list; it is a pure subset of that list (codex systems ∩ confident sibling
186
+ * systems). Upper-case ISO-3166 alpha-2, e.g. `["US"]` for a 5-digit code whose siblings all say US.
187
+ *
188
+ * It narrows the shape half only. Since #24 the candidate set also carries the countries the GAZETTEER holds this
189
+ * postcode in, and that half is not narrowable — it is the artifact reporting what it contains, which is the same
190
+ * class of evidence the pair test itself runs on. Every candidate from either half still has to pass that test.
191
+ */
192
+ candidateSystems?: readonly string[]
193
+ }
194
+
195
+ /**
196
+ * A usable coordinate — the gazetteer stores an unlocated row as 0,0, which haversine would happily measure against.
197
+ */
198
+ function hasCoord(p: ResolvedPlace): boolean {
199
+ return p.lat !== 0 || p.lon !== 0
200
+ }
201
+
202
+ /**
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.
205
+ */
206
+ export function firstLocalityValue(roots: readonly AddressNode[]): string | undefined {
207
+ for (const tag of ["locality", "dependent_locality"] as const) {
208
+ const stack = [...roots]
209
+
210
+ while (stack.length) {
211
+ const n = stack.pop()!
212
+
213
+ if (n.tag === tag && n.value.trim().length) return n.value.trim()
214
+
215
+ stack.push(...n.children)
216
+ }
217
+ }
218
+
219
+ return undefined
220
+ }
221
+
222
+ /**
223
+ * Over-fetch for the UNSCOPED holder probes (#24). Postcodes are bounded and small — the 2026-08-10 candidate
224
+ * gazetteer's most-shared code carries 12 rows across 8 countries — so 20 sees every bearer and the postcode holder set
225
+ * is COMPLETE, not a sample. Locality names are not bounded that way (`rampur` has 1,096 rows, `bara` spans 42
226
+ * countries), so 30 is a population-first WINDOW: it can only ever hide a country, which turns a "more than one
227
+ * country" abstention into a false "exactly one". The explicit default-country probe below is what closes that gap for
228
+ * the case that matters (the address is domestic after all).
229
+ */
230
+ const POSTCODE_HOLDER_FETCH = 20
231
+ const LOCALITY_HOLDER_FETCH = 30
232
+
233
+ /**
234
+ * Upper bound on countries the pair rung will test, so a pathological name can't turn one incoherent parse into a
235
+ * hundred lookups. The postcode holder set is ≤8 countries in the measured artifact and the codex shape list is ≤8, so
236
+ * this only ever binds on a gazetteer very unlike today's.
237
+ */
238
+ const MAX_CANDIDATE_COUNTRIES = 12
239
+
240
+ /**
241
+ * Countries that hold an exact, coordinate-bearing row for `text` at `placetype`, mapped to their best (first) such
242
+ * row. One UNSCOPED lookup.
243
+ *
244
+ * This is the #24 candidate source, and it replaces a proxy with the thing itself. The pass used to ask codex "which
245
+ * address SYSTEMS could this shape be?" — a model-free shape test over the eight slices codex specifies. That answer is
246
+ * correct and useless for two thirds of Europe: `13000` shapes as `[us, de, fr]`, the gazetteer holds it in exactly one
247
+ * country (CZ), and CZ has no codex slice, so the pass could not propose the only country that could possibly be right.
248
+ * Membership in the gazetteer is positive evidence of the same kind the pair test already runs on, available for one
249
+ * lookup, and it is EXHAUSTIVE for postcodes at the measured cardinality.
250
+ *
251
+ * `exactMatch !== false` is the admission bar: a fuzzy postcode hit is a DIFFERENT postcode (the 2026-08-05 Code-Point
252
+ * lesson — `BT3 9QQ` trigram-matching Sheffield's `S3 9QQ`), and a fuzzy locality hit is evidence about the index, not
253
+ * about the country. Backends that do not stamp the flag leave it undefined and still contribute.
254
+ */
255
+ async function countriesHolding(
256
+ backend: ResolverBackend,
257
+ text: string,
258
+ placetype: "postalcode" | "locality",
259
+ limit: number
260
+ ): Promise<Map<string, ResolvedPlace>> {
261
+ const out = new Map<string, ResolvedPlace>()
262
+
263
+ let hits: ResolvedPlace[]
264
+
265
+ try {
266
+ hits = await backend.findPlace({ text, placetype, limit })
267
+ } catch {
268
+ return out // a backend hiccup degrades to "no evidence", never to a crashed resolve
269
+ }
270
+
271
+ for (const hit of hits) {
272
+ const country = hit.country?.trim().toUpperCase()
273
+
274
+ if (!country || hit.exactMatch === false || !hasCoord(hit)) continue
275
+
276
+ if (!out.has(country)) {
277
+ out.set(country, hit)
278
+ }
279
+ }
280
+
281
+ return out
282
+ }
283
+
284
+ /**
285
+ * Is the (postcode, locality) pair geographically consistent in `country`? Returns the winning pair and its distance,
286
+ * 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).
289
+ */
290
+ async function coherenceIn(
291
+ country: string,
292
+ postcode: string,
293
+ locality: string,
294
+ backend: ResolverBackend,
295
+ gateKm: number,
296
+ knownPostcodePlace?: ResolvedPlace
297
+ ): Promise<{ postcodePlace: ResolvedPlace; localityPlace: ResolvedPlace; distanceKm: number } | null> {
298
+ let postcodePlace = knownPostcodePlace
299
+
300
+ if (!postcodePlace) {
301
+ let postcodeHits: ResolvedPlace[]
302
+
303
+ try {
304
+ postcodeHits = await backend.findPlace({ text: postcode, placetype: "postalcode", country, limit: 3 })
305
+ } catch {
306
+ return null // a backend hiccup degrades to "no evidence here", never to a crashed resolve
307
+ }
308
+
309
+ postcodePlace = postcodeHits.find(hasCoord)
310
+ }
311
+
312
+ if (!postcodePlace) return null
313
+
314
+ let localityHits: ResolvedPlace[]
315
+
316
+ try {
317
+ localityHits = await backend.findPlace({ text: locality, placetype: "locality", country, limit: 5 })
318
+ } catch {
319
+ return null
320
+ }
321
+
322
+ // EXACT matches only. A fuzzy same-country hit ("Paris" → "Parish") is not evidence that the postcode
323
+ // belongs to this country; it is evidence that the FTS index is generous. Backends that do not stamp
324
+ // `exactMatch` therefore contribute nothing here rather than contributing noise.
325
+ let best: { localityPlace: ResolvedPlace; distanceKm: number } | null = null
326
+
327
+ for (const candidate of localityHits) {
328
+ if (!candidate.exactMatch || !hasCoord(candidate)) continue
329
+ const distanceKm = haversineKm(postcodePlace.lat, postcodePlace.lon, candidate.lat, candidate.lon)
330
+
331
+ if (distanceKm > gateKm) continue
332
+
333
+ if (!best || distanceKm < best.distanceKm) {
334
+ best = { localityPlace: candidate, distanceKm }
335
+ }
336
+ }
337
+
338
+ return best ? { postcodePlace, ...best } : null
339
+ }
340
+
341
+ /**
342
+ * The country in which this address's postcode and locality are geographically consistent — or `null` to abstain.
343
+ *
344
+ * Order matters and is the whole safety argument. The caller's `defaultCountry` is tested FIRST; a coherent default
345
+ * short-circuits with `null` (nothing to correct, ≤2 lookups spent, the walk unchanged). Only when the default cannot
346
+ * make the pair consistent are the codex shape's other candidate systems tried, and only a UNIQUE coherent alternative
347
+ * produces a verdict — zero (no evidence) and two-or-more (a genuine tie) both abstain.
348
+ *
349
+ * The candidate set is `candidateSystemsForPostcode` — a model-free SHAPE test over each codex slice's own postcode
350
+ * pattern, no safelist and no prior. Its `SystemCode` values are ISO-3166 alpha-2 in lower case, so the upper-casing
351
+ * below is the whole conversion. Note the corollary: a country with no codex slice can never be proposed (the gazetteer
352
+ * holds `75001` in PL, and this pass will never return PL), which bounds the mechanism to the systems whose postcode
353
+ * shapes are actually specified.
354
+ */
355
+ export async function findPostcodeCountryScope(
356
+ roots: readonly AddressNode[],
357
+ backend: ResolverBackend,
358
+ opts: PostcodeCountryScopeOpts
359
+ ): Promise<PostcodeCountryScope | null> {
360
+ const postcode = opts.postcode.trim()
361
+ const defaultCountry = opts.defaultCountry.trim().toUpperCase()
362
+
363
+ if (!postcode || !defaultCountry) return null
364
+
365
+ const locality = firstLocalityValue(roots)
366
+
367
+ // Both halves of the pair are required. A postcode with no locality has nothing to be coherent WITH, which is what
368
+ // keeps this pass inert on "Springfield, IL 62701" (the parser tags Springfield as a `street` — a separate defect)
369
+ // and on every bare-postcode query.
370
+ if (!locality) return null
371
+
372
+ const gateKm = opts.gateKm ?? POSTCODE_COUNTRY_COHERENCE_GATE_KM
373
+
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
377
+
378
+ // 2. The default could not place this pair. Which countries could? Two sources, unioned:
379
+ //
380
+ // - the SHAPE list (`candidateSystemsForPostcode`, or the shape-coherence pass's narrowing when #31
381
+ // Mechanism 1 supplied one — a pure subset of it), and
382
+ // - the countries the GAZETTEER actually holds this postcode in (#24). Exhaustive at the measured
383
+ // cardinality, and the only source that can name a country codex has no slice for — which was the
384
+ // whole reason the CZ/CH/BE/DK/AT/NL block of the 2026-08-09 panel resolved to US namesakes while
385
+ // their own postcodes sat in the shipped gazetteer within 4 km of truth.
386
+ //
387
+ // The union can only ADD countries, and every added one must still pass the same geometric pair test,
388
+ // so this widens recall without weakening the verdict: a second coherent country turns a verdict into
389
+ // an abstention (safe), never into a wrong answer.
390
+ const pcHolders = await countriesHolding(backend, postcode, "postalcode", POSTCODE_HOLDER_FETCH)
391
+
392
+ const shapeSystems = (
393
+ opts.candidateSystems ?? candidateSystemsForPostcode(postcode).map((system) => system.toUpperCase())
394
+ ).map((country) => country.trim().toUpperCase())
395
+
396
+ const candidates = [...new Set([...shapeSystems, ...pcHolders.keys()])]
397
+ .filter((country) => country !== defaultCountry)
398
+ .slice(0, MAX_CANDIDATE_COUNTRIES)
399
+
400
+ const coherent: PostcodeCountryScope[] = []
401
+
402
+ for (const country of candidates) {
403
+ const hit = await coherenceIn(country, postcode, locality, backend, gateKm, pcHolders.get(country))
404
+
405
+ if (hit) {
406
+ coherent.push({ country, postcode, locality, evidence: "pair", ...hit })
407
+ }
408
+ }
409
+
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
416
+
417
+ // 4. No country makes the PAIR consistent. On the 2026-08-09 panel that happened 10 times for two opposite
418
+ // reasons, and in both the address's country was never in doubt — only unrepresentable as a pair:
419
+ //
420
+ // - the gazetteer holds no postcodes for the country at all (CH, BE), so the postcode half can never
421
+ // agree with anything no matter how good the locality evidence is; or
422
+ // - the locality is a name no admin gazetteer carries (`Praha 3`, `Praha 9` — municipal districts).
423
+ //
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.
430
+ if (pcHolders.has(defaultCountry)) return null
431
+
432
+ if (await holdsLocality(backend, locality, defaultCountry)) return null
433
+
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)
439
+
440
+ if (locHolders.size === 1) {
441
+ const [country, localityPlace] = [...locHolders.entries()][0]!
442
+ const ownPostcode = pcHolders.get(country)
443
+
444
+ const contradicted =
445
+ ownPostcode !== undefined &&
446
+ haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > gateKm
447
+
448
+ if (country !== defaultCountry && !contradicted) {
449
+ return { country, postcode, locality, evidence: "locality", localityPlace }
450
+ }
451
+ }
452
+
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) {
456
+ const [country, postcodePlace] = [...pcHolders.entries()][0]!
457
+
458
+ if (country !== defaultCountry) {
459
+ return { country, postcode, locality, evidence: "postcode", postcodePlace }
460
+ }
461
+ }
462
+
463
+ return null
464
+ }
465
+
466
+ /**
467
+ * Does `country` hold an exact, coordinate-bearing locality row for `locality`? One scoped lookup — deliberately NOT
468
+ * read off the unscoped holder window, which is population-first and truncated, so a small domestic bearer could fall
469
+ * below its fold and let a foreign scope through.
470
+ */
471
+ async function holdsLocality(backend: ResolverBackend, locality: string, country: string): Promise<boolean> {
472
+ try {
473
+ const hits = await backend.findPlace({ text: locality, placetype: "locality", country, limit: 3 })
474
+
475
+ return hits.some((hit) => hit.exactMatch && hasCoord(hit))
476
+ } catch {
477
+ // A backend hiccup must not be read as "the default country has nothing" — that would license a foreign
478
+ // scope on no evidence. Treat it as corroboration and abstain.
479
+ return true
480
+ }
481
+ }
482
+
483
+ /**
484
+ * Stamp the adopted scope onto the tree's postcode and locality nodes, so a consumer can see that the walk's country
485
+ * was not the one the caller asked for — and which evidence bought the change. Additive: identity and coordinates are
486
+ * untouched, this only writes `metadata`.
487
+ */
488
+ 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
+
496
+ if (n.tag !== "postcode" && n.tag !== "locality" && n.tag !== "dependent_locality") continue
497
+
498
+ n.metadata = {
499
+ ...n.metadata,
500
+ postcode_country_scope: scope.country,
501
+ // WHICH rung spoke — a two-sided agreement and a one-sided uniqueness claim are different evidence,
502
+ // and a consumer that cannot tell them apart cannot weight them differently.
503
+ postcode_country_scope_evidence: scope.evidence,
504
+ // Only the `pair` rung measured a distance. Writing a 0 for the single-sided rungs would assert an
505
+ // agreement nobody tested.
506
+ ...(scope.distanceKm !== undefined ? { postcode_country_scope_km: scope.distanceKm } : {}),
507
+ }
508
+ }
509
+ }