@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
package/index.ts CHANGED
@@ -40,6 +40,14 @@ export type {
40
40
  StreetLocalityEvidence,
41
41
  } from "./street-evidence.ts"
42
42
 
43
+ export {
44
+ findPostcodeCountryScope,
45
+ firstLocalityValue,
46
+ POSTCODE_COUNTRY_COHERENCE_GATE_KM,
47
+ stampPostcodeCountryScope,
48
+ } from "./postcode-country-coherence.ts"
49
+
50
+ export type { PostcodeCountryScope, PostcodeCountryScopeOpts } from "./postcode-country-coherence.ts"
43
51
  export { findRescoreCandidate, hasResolvedPlace } from "./span-rescore.ts"
44
52
  export type { RescoreCandidate, SpanRescoreOptions } from "./span-rescore.ts"
45
53
 
package/out/index.d.ts CHANGED
@@ -17,6 +17,8 @@ export { COUNTRY_BBOX, finestResolvedCoordinate, isImplausibleResolution, outsid
17
17
  export type { PlausibilityOpts, PlausibilityVerdict, ResolvedCoordinate } from "./plausibility.ts";
18
18
  export { foldStreetSurface, isPureTypeVocabulary, pickByStreetEvidence } from "./street-evidence.ts";
19
19
  export type { PickByStreetEvidenceOpts, StreetCandidate, StreetEvidencePick, StreetEvidenceScope, StreetLocalityEvidence, } from "./street-evidence.ts";
20
+ export { findPostcodeCountryScope, firstLocalityValue, POSTCODE_COUNTRY_COHERENCE_GATE_KM, stampPostcodeCountryScope, } from "./postcode-country-coherence.ts";
21
+ export type { PostcodeCountryScope, PostcodeCountryScopeOpts } from "./postcode-country-coherence.ts";
20
22
  export { findRescoreCandidate, hasResolvedPlace } from "./span-rescore.ts";
21
23
  export type { RescoreCandidate, SpanRescoreOptions } from "./span-rescore.ts";
22
24
  export * from "@mailwoman/core/resolver";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAA;AAE9E,YAAY,EACX,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,uBAAuB,GACvB,MAAM,sBAAsB,CAAA;AAE7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAEhD,OAAO,EACN,YAAY,EACZ,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,mBAAmB,CAAA;AAE1B,YAAY,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AAClG,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAEpG,YAAY,EACX,wBAAwB,EACxB,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,sBAAsB,GACtB,MAAM,sBAAsB,CAAA;AAE7B,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAC1E,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AAI7E,cAAc,0BAA0B,CAAA;AAExC,cAAc,aAAa,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAA;AAE9E,YAAY,EACX,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,uBAAuB,GACvB,MAAM,sBAAsB,CAAA;AAE7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAEhD,OAAO,EACN,YAAY,EACZ,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,mBAAmB,CAAA;AAE1B,YAAY,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AAClG,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAEpG,YAAY,EACX,wBAAwB,EACxB,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,sBAAsB,GACtB,MAAM,sBAAsB,CAAA;AAE7B,OAAO,EACN,wBAAwB,EACxB,kBAAkB,EAClB,kCAAkC,EAClC,yBAAyB,GACzB,MAAM,iCAAiC,CAAA;AAExC,YAAY,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAA;AACrG,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAC1E,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AAI7E,cAAc,0BAA0B,CAAA;AAExC,cAAc,aAAa,CAAA"}
package/out/index.js CHANGED
@@ -14,6 +14,7 @@ export { RemoteResolver, serializableResolveOpts } from "./remote-resolver.js";
14
14
  export { createWOFResolver } from "./resolve.js";
15
15
  export { COUNTRY_BBOX, finestResolvedCoordinate, isImplausibleResolution, outsideExpectedCountry, } from "./plausibility.js";
16
16
  export { foldStreetSurface, isPureTypeVocabulary, pickByStreetEvidence } from "./street-evidence.js";
17
+ export { findPostcodeCountryScope, firstLocalityValue, POSTCODE_COUNTRY_COHERENCE_GATE_KM, stampPostcodeCountryScope, } from "./postcode-country-coherence.js";
17
18
  export { findRescoreCandidate, hasResolvedPlace } from "./span-rescore.js";
18
19
  // The type contract + placetype helpers live in core (pure types, keep core a leaf). Re-export so
19
20
  // consumers get the whole surface from `@mailwoman/resolver`.
package/out/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAA;AAS9E,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAEhD,OAAO,EACN,YAAY,EACZ,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,mBAAmB,CAAA;AAG1B,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAUpG,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAG1E,kGAAkG;AAClG,8DAA8D;AAC9D,cAAc,0BAA0B,CAAA;AAExC,cAAc,aAAa,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAA;AAS9E,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAEhD,OAAO,EACN,YAAY,EACZ,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,GACtB,MAAM,mBAAmB,CAAA;AAG1B,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAUpG,OAAO,EACN,wBAAwB,EACxB,kBAAkB,EAClB,kCAAkC,EAClC,yBAAyB,GACzB,MAAM,iCAAiC,CAAA;AAGxC,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAG1E,kGAAkG;AAClG,8DAA8D;AAC9D,cAAc,0BAA0B,CAAA;AAExC,cAAc,aAAa,CAAA"}
@@ -0,0 +1,211 @@
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
+ import type { AddressNode } from "@mailwoman/core/decoder";
104
+ import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver";
105
+ /**
106
+ * Default gate radius (km) for the postcode↔locality consistency test. 25 km is what the 800-pair scale run measured;
107
+ * the confound board returned identical verdicts at 15, 25 and 50, so this is a floor choice, not a tuned one.
108
+ */
109
+ export declare const POSTCODE_COUNTRY_COHERENCE_GATE_KM = 25;
110
+ /**
111
+ * Which half (or halves) of the address bought the verdict — the firing receipt, so a reader of a scoped result can
112
+ * tell a two-sided agreement from a one-sided uniqueness claim without re-deriving it.
113
+ *
114
+ * - `pair` — postcode AND locality both resolve in this country, within the gate. The strongest rung and the only one
115
+ * that existed before #24.
116
+ * - `locality` — the locality names exactly one country in the whole gazetteer, and the postcode names none that
117
+ * contradict it. This is the CH/BE class: the gazetteer carries no Swiss or Belgian postcodes at all, so the pair
118
+ * test can never fire there no matter how good the locality evidence is.
119
+ * - `postcode` — the postcode is held in exactly one country and the locality is in no gazetteer at all. The `Praha 3`
120
+ * class: a municipal district nobody's admin gazetteer names.
121
+ */
122
+ export type PostcodeCountryScopeEvidence = "pair" | "locality" | "postcode";
123
+ /**
124
+ * A country in which the address's own evidence is geographically consistent.
125
+ */
126
+ export interface PostcodeCountryScope {
127
+ /**
128
+ * ISO-3166 alpha-2, upper-case.
129
+ */
130
+ country: string;
131
+ /**
132
+ * The postcode string the verdict was reached on (as it appears in the tree).
133
+ */
134
+ postcode: string;
135
+ /**
136
+ * The locality string the verdict was reached on.
137
+ */
138
+ locality: string;
139
+ /**
140
+ * Which evidence carried the verdict. See {@link PostcodeCountryScopeEvidence}.
141
+ */
142
+ evidence: PostcodeCountryScopeEvidence;
143
+ /**
144
+ * Distance between the resolved postcode point and the nearest same-named locality, in km. Always `<= gateKm`.
145
+ * Present ONLY for the `pair` rung — a single-sided verdict has no two points to measure between, and reporting a `0`
146
+ * there would assert an agreement nobody tested (the meaning-of-zero rule).
147
+ */
148
+ distanceKm?: number;
149
+ /**
150
+ * The postcode place that anchored the verdict. Absent on the `locality` rung.
151
+ */
152
+ postcodePlace?: ResolvedPlace;
153
+ /**
154
+ * The locality place that anchored the verdict. Absent on the `postcode` rung.
155
+ */
156
+ localityPlace?: ResolvedPlace;
157
+ }
158
+ export interface PostcodeCountryScopeOpts {
159
+ /**
160
+ * The postcode string from the tree (the resolver already pre-scans for it — pass `state.postcode` so this pass and
161
+ * the walk can never disagree about WHICH postcode is the address's).
162
+ */
163
+ postcode: string;
164
+ /**
165
+ * The country the caller's `defaultCountry` would hard-filter to. Required: this pass exists to correct a wrong one,
166
+ * so with no default there is nothing to correct and the caller should not be calling.
167
+ */
168
+ defaultCountry: string;
169
+ /**
170
+ * Consistency gate radius in km. Defaults to {@link POSTCODE_COUNTRY_COHERENCE_GATE_KM}.
171
+ */
172
+ gateKm?: number;
173
+ /**
174
+ * Optional narrowing of the SHAPE half of the candidate-country set — the shape-coherence pass's intersection for a
175
+ * CONFIRMED postcode span (see `resolver/postcode-shape-coherence.ts`, #31 Mechanism 1). When present it REPLACES
176
+ * `candidateSystemsForPostcode`'s own list; it is a pure subset of that list (codex systems ∩ confident sibling
177
+ * systems). Upper-case ISO-3166 alpha-2, e.g. `["US"]` for a 5-digit code whose siblings all say US.
178
+ *
179
+ * It narrows the shape half only. Since #24 the candidate set also carries the countries the GAZETTEER holds this
180
+ * postcode in, and that half is not narrowable — it is the artifact reporting what it contains, which is the same
181
+ * class of evidence the pair test itself runs on. Every candidate from either half still has to pass that test.
182
+ */
183
+ candidateSystems?: readonly string[];
184
+ }
185
+ /**
186
+ * The address's locality string: the first `locality` node anywhere in the tree, else the first `dependent_locality`.
187
+ * Two passes so a real locality always beats a dependent one regardless of tree order.
188
+ */
189
+ export declare function firstLocalityValue(roots: readonly AddressNode[]): string | undefined;
190
+ /**
191
+ * The country in which this address's postcode and locality are geographically consistent — or `null` to abstain.
192
+ *
193
+ * Order matters and is the whole safety argument. The caller's `defaultCountry` is tested FIRST; a coherent default
194
+ * short-circuits with `null` (nothing to correct, ≤2 lookups spent, the walk unchanged). Only when the default cannot
195
+ * make the pair consistent are the codex shape's other candidate systems tried, and only a UNIQUE coherent alternative
196
+ * produces a verdict — zero (no evidence) and two-or-more (a genuine tie) both abstain.
197
+ *
198
+ * The candidate set is `candidateSystemsForPostcode` — a model-free SHAPE test over each codex slice's own postcode
199
+ * pattern, no safelist and no prior. Its `SystemCode` values are ISO-3166 alpha-2 in lower case, so the upper-casing
200
+ * below is the whole conversion. Note the corollary: a country with no codex slice can never be proposed (the gazetteer
201
+ * holds `75001` in PL, and this pass will never return PL), which bounds the mechanism to the systems whose postcode
202
+ * shapes are actually specified.
203
+ */
204
+ export declare function findPostcodeCountryScope(roots: readonly AddressNode[], backend: ResolverBackend, opts: PostcodeCountryScopeOpts): Promise<PostcodeCountryScope | null>;
205
+ /**
206
+ * Stamp the adopted scope onto the tree's postcode and locality nodes, so a consumer can see that the walk's country
207
+ * was not the one the caller asked for — and which evidence bought the change. Additive: identity and coordinates are
208
+ * untouched, this only writes `metadata`.
209
+ */
210
+ export declare function stampPostcodeCountryScope(roots: readonly AddressNode[], scope: PostcodeCountryScope): void;
211
+ //# sourceMappingURL=postcode-country-coherence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postcode-country-coherence.d.ts","sourceRoot":"","sources":["../postcode-country-coherence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqGG;AAKH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAG9E;;;GAGG;AACH,eAAO,MAAM,kCAAkC,KAAK,CAAA;AAEpD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,4BAA4B,GAAG,MAAM,GAAG,UAAU,GAAG,UAAU,CAAA;AAE3E;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACpC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAA;IACf;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAA;IAChB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAA;IAChB;;OAEG;IACH,QAAQ,EAAE,4BAA4B,CAAA;IACtC;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;;OAEG;IACH,aAAa,CAAC,EAAE,aAAa,CAAA;IAC7B;;OAEG;IACH,aAAa,CAAC,EAAE,aAAa,CAAA;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACxC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;IAChB;;;OAGG;IACH,cAAc,EAAE,MAAM,CAAA;IACtB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CACpC;AASD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,GAAG,MAAM,GAAG,SAAS,CAcpF;AAyHD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,wBAAwB,CAC7C,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,EACxB,IAAI,EAAE,wBAAwB,GAC5B,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAyGtC;AAmBD;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,EAAE,KAAK,EAAE,oBAAoB,GAAG,IAAI,CAqB1G"}
@@ -0,0 +1,369 @@
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
+ // `postcode-systems` has no dedicated export subpath; the barrel is where every other consumer
104
+ // (`neural/postcode-anchor.ts`) reaches it from.
105
+ import { candidateSystemsForPostcode } from "@mailwoman/codex";
106
+ import { haversineKm } from "@mailwoman/spatial";
107
+ /**
108
+ * Default gate radius (km) for the postcode↔locality consistency test. 25 km is what the 800-pair scale run measured;
109
+ * the confound board returned identical verdicts at 15, 25 and 50, so this is a floor choice, not a tuned one.
110
+ */
111
+ export const POSTCODE_COUNTRY_COHERENCE_GATE_KM = 25;
112
+ /**
113
+ * A usable coordinate — the gazetteer stores an unlocated row as 0,0, which haversine would happily measure against.
114
+ */
115
+ function hasCoord(p) {
116
+ return p.lat !== 0 || p.lon !== 0;
117
+ }
118
+ /**
119
+ * The address's locality string: the first `locality` node anywhere in the tree, else the first `dependent_locality`.
120
+ * Two passes so a real locality always beats a dependent one regardless of tree order.
121
+ */
122
+ export function firstLocalityValue(roots) {
123
+ for (const tag of ["locality", "dependent_locality"]) {
124
+ const stack = [...roots];
125
+ while (stack.length) {
126
+ const n = stack.pop();
127
+ if (n.tag === tag && n.value.trim().length)
128
+ return n.value.trim();
129
+ stack.push(...n.children);
130
+ }
131
+ }
132
+ return undefined;
133
+ }
134
+ /**
135
+ * Over-fetch for the UNSCOPED holder probes (#24). Postcodes are bounded and small — the 2026-08-10 candidate
136
+ * gazetteer's most-shared code carries 12 rows across 8 countries — so 20 sees every bearer and the postcode holder set
137
+ * is COMPLETE, not a sample. Locality names are not bounded that way (`rampur` has 1,096 rows, `bara` spans 42
138
+ * countries), so 30 is a population-first WINDOW: it can only ever hide a country, which turns a "more than one
139
+ * country" abstention into a false "exactly one". The explicit default-country probe below is what closes that gap for
140
+ * the case that matters (the address is domestic after all).
141
+ */
142
+ const POSTCODE_HOLDER_FETCH = 20;
143
+ const LOCALITY_HOLDER_FETCH = 30;
144
+ /**
145
+ * Upper bound on countries the pair rung will test, so a pathological name can't turn one incoherent parse into a
146
+ * hundred lookups. The postcode holder set is ≤8 countries in the measured artifact and the codex shape list is ≤8, so
147
+ * this only ever binds on a gazetteer very unlike today's.
148
+ */
149
+ const MAX_CANDIDATE_COUNTRIES = 12;
150
+ /**
151
+ * Countries that hold an exact, coordinate-bearing row for `text` at `placetype`, mapped to their best (first) such
152
+ * row. One UNSCOPED lookup.
153
+ *
154
+ * This is the #24 candidate source, and it replaces a proxy with the thing itself. The pass used to ask codex "which
155
+ * address SYSTEMS could this shape be?" — a model-free shape test over the eight slices codex specifies. That answer is
156
+ * correct and useless for two thirds of Europe: `13000` shapes as `[us, de, fr]`, the gazetteer holds it in exactly one
157
+ * country (CZ), and CZ has no codex slice, so the pass could not propose the only country that could possibly be right.
158
+ * Membership in the gazetteer is positive evidence of the same kind the pair test already runs on, available for one
159
+ * lookup, and it is EXHAUSTIVE for postcodes at the measured cardinality.
160
+ *
161
+ * `exactMatch !== false` is the admission bar: a fuzzy postcode hit is a DIFFERENT postcode (the 2026-08-05 Code-Point
162
+ * lesson — `BT3 9QQ` trigram-matching Sheffield's `S3 9QQ`), and a fuzzy locality hit is evidence about the index, not
163
+ * about the country. Backends that do not stamp the flag leave it undefined and still contribute.
164
+ */
165
+ async function countriesHolding(backend, text, placetype, limit) {
166
+ const out = new Map();
167
+ let hits;
168
+ try {
169
+ hits = await backend.findPlace({ text, placetype, limit });
170
+ }
171
+ catch {
172
+ return out; // a backend hiccup degrades to "no evidence", never to a crashed resolve
173
+ }
174
+ for (const hit of hits) {
175
+ const country = hit.country?.trim().toUpperCase();
176
+ if (!country || hit.exactMatch === false || !hasCoord(hit))
177
+ continue;
178
+ if (!out.has(country)) {
179
+ out.set(country, hit);
180
+ }
181
+ }
182
+ return out;
183
+ }
184
+ /**
185
+ * Is the (postcode, locality) pair geographically consistent in `country`? Returns the winning pair and its distance,
186
+ * or `null` when the postcode does not resolve there, no same-named locality exists there, or the nearest one is
187
+ * outside the gate. Costs one postcode lookup plus (only if that hit) one locality lookup — or just the locality lookup
188
+ * when the caller already knows the country's postcode row (`knownPostcodePlace`, from the exhaustive unscoped probe).
189
+ */
190
+ async function coherenceIn(country, postcode, locality, backend, gateKm, knownPostcodePlace) {
191
+ let postcodePlace = knownPostcodePlace;
192
+ if (!postcodePlace) {
193
+ let postcodeHits;
194
+ try {
195
+ postcodeHits = await backend.findPlace({ text: postcode, placetype: "postalcode", country, limit: 3 });
196
+ }
197
+ catch {
198
+ return null; // a backend hiccup degrades to "no evidence here", never to a crashed resolve
199
+ }
200
+ postcodePlace = postcodeHits.find(hasCoord);
201
+ }
202
+ if (!postcodePlace)
203
+ return null;
204
+ let localityHits;
205
+ try {
206
+ localityHits = await backend.findPlace({ text: locality, placetype: "locality", country, limit: 5 });
207
+ }
208
+ catch {
209
+ return null;
210
+ }
211
+ // EXACT matches only. A fuzzy same-country hit ("Paris" → "Parish") is not evidence that the postcode
212
+ // belongs to this country; it is evidence that the FTS index is generous. Backends that do not stamp
213
+ // `exactMatch` therefore contribute nothing here rather than contributing noise.
214
+ let best = null;
215
+ for (const candidate of localityHits) {
216
+ if (!candidate.exactMatch || !hasCoord(candidate))
217
+ continue;
218
+ const distanceKm = haversineKm(postcodePlace.lat, postcodePlace.lon, candidate.lat, candidate.lon);
219
+ if (distanceKm > gateKm)
220
+ continue;
221
+ if (!best || distanceKm < best.distanceKm) {
222
+ best = { localityPlace: candidate, distanceKm };
223
+ }
224
+ }
225
+ return best ? { postcodePlace, ...best } : null;
226
+ }
227
+ /**
228
+ * The country in which this address's postcode and locality are geographically consistent — or `null` to abstain.
229
+ *
230
+ * Order matters and is the whole safety argument. The caller's `defaultCountry` is tested FIRST; a coherent default
231
+ * short-circuits with `null` (nothing to correct, ≤2 lookups spent, the walk unchanged). Only when the default cannot
232
+ * make the pair consistent are the codex shape's other candidate systems tried, and only a UNIQUE coherent alternative
233
+ * produces a verdict — zero (no evidence) and two-or-more (a genuine tie) both abstain.
234
+ *
235
+ * The candidate set is `candidateSystemsForPostcode` — a model-free SHAPE test over each codex slice's own postcode
236
+ * pattern, no safelist and no prior. Its `SystemCode` values are ISO-3166 alpha-2 in lower case, so the upper-casing
237
+ * below is the whole conversion. Note the corollary: a country with no codex slice can never be proposed (the gazetteer
238
+ * holds `75001` in PL, and this pass will never return PL), which bounds the mechanism to the systems whose postcode
239
+ * shapes are actually specified.
240
+ */
241
+ export async function findPostcodeCountryScope(roots, backend, opts) {
242
+ const postcode = opts.postcode.trim();
243
+ const defaultCountry = opts.defaultCountry.trim().toUpperCase();
244
+ if (!postcode || !defaultCountry)
245
+ return null;
246
+ const locality = firstLocalityValue(roots);
247
+ // Both halves of the pair are required. A postcode with no locality has nothing to be coherent WITH, which is what
248
+ // keeps this pass inert on "Springfield, IL 62701" (the parser tags Springfield as a `street` — a separate defect)
249
+ // and on every bare-postcode query.
250
+ if (!locality)
251
+ return null;
252
+ const gateKm = opts.gateKm ?? POSTCODE_COUNTRY_COHERENCE_GATE_KM;
253
+ // 1. Is the caller's own default country coherent? If so we are done — positive evidence for the default,
254
+ // no override, and the common domestic path costs two lookups and changes nothing.
255
+ if (await coherenceIn(defaultCountry, postcode, locality, backend, gateKm))
256
+ return null;
257
+ // 2. The default could not place this pair. Which countries could? Two sources, unioned:
258
+ //
259
+ // - the SHAPE list (`candidateSystemsForPostcode`, or the shape-coherence pass's narrowing when #31
260
+ // Mechanism 1 supplied one — a pure subset of it), and
261
+ // - the countries the GAZETTEER actually holds this postcode in (#24). Exhaustive at the measured
262
+ // cardinality, and the only source that can name a country codex has no slice for — which was the
263
+ // whole reason the CZ/CH/BE/DK/AT/NL block of the 2026-08-09 panel resolved to US namesakes while
264
+ // their own postcodes sat in the shipped gazetteer within 4 km of truth.
265
+ //
266
+ // The union can only ADD countries, and every added one must still pass the same geometric pair test,
267
+ // so this widens recall without weakening the verdict: a second coherent country turns a verdict into
268
+ // an abstention (safe), never into a wrong answer.
269
+ const pcHolders = await countriesHolding(backend, postcode, "postalcode", POSTCODE_HOLDER_FETCH);
270
+ const shapeSystems = (opts.candidateSystems ?? candidateSystemsForPostcode(postcode).map((system) => system.toUpperCase())).map((country) => country.trim().toUpperCase());
271
+ const candidates = [...new Set([...shapeSystems, ...pcHolders.keys()])]
272
+ .filter((country) => country !== defaultCountry)
273
+ .slice(0, MAX_CANDIDATE_COUNTRIES);
274
+ const coherent = [];
275
+ for (const country of candidates) {
276
+ const hit = await coherenceIn(country, postcode, locality, backend, gateKm, pcHolders.get(country));
277
+ if (hit) {
278
+ coherent.push({ country, postcode, locality, evidence: "pair", ...hit });
279
+ }
280
+ }
281
+ // 3. Exactly one country makes the pair consistent, or we fall through. Two coherent countries mean the geometry
282
+ // genuinely does not decide, and guessing between them is precisely what this mechanism exists not to do — so a
283
+ // TIE is a hard abstention, never a fall-through to the weaker rungs below.
284
+ if (coherent.length === 1)
285
+ return coherent[0];
286
+ if (coherent.length > 1)
287
+ return null;
288
+ // 4. No country makes the PAIR consistent. On the 2026-08-09 panel that happened 10 times for two opposite
289
+ // reasons, and in both the address's country was never in doubt — only unrepresentable as a pair:
290
+ //
291
+ // - the gazetteer holds no postcodes for the country at all (CH, BE), so the postcode half can never
292
+ // agree with anything no matter how good the locality evidence is; or
293
+ // - the locality is a name no admin gazetteer carries (`Praha 3`, `Praha 9` — municipal districts).
294
+ //
295
+ // So each half gets to speak alone, under two conditions that keep this from becoming a guess. First, the
296
+ // DEFAULT country must corroborate NEITHER half — if the address's own city or its own postcode exists at
297
+ // home, the address is domestically plausible and nothing foreign may be proposed (this is what holds
298
+ // `123 Main St, Vienna, VA 22180` in Virginia even though Wien is the vastly more prominent Vienna).
299
+ // Second, the speaking half must name EXACTLY ONE country in the entire gazetteer — the same uniqueness bar
300
+ // the pair rung uses, applied to one side.
301
+ if (pcHolders.has(defaultCountry))
302
+ return null;
303
+ if (await holdsLocality(backend, locality, defaultCountry))
304
+ return null;
305
+ // 4a. The locality names exactly one country. Stronger than the postcode rung — a place name is far more
306
+ // discriminative than a four-digit code — so it is tried first. It stands down when that country's OWN
307
+ // postcode row contradicts the locality (outside the gate): the two halves disagreeing inside one country
308
+ // is exactly what the pair test exists to catch, and a single-sided rung must not launder it.
309
+ const locHolders = await countriesHolding(backend, locality, "locality", LOCALITY_HOLDER_FETCH);
310
+ if (locHolders.size === 1) {
311
+ const [country, localityPlace] = [...locHolders.entries()][0];
312
+ const ownPostcode = pcHolders.get(country);
313
+ const contradicted = ownPostcode !== undefined &&
314
+ haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > gateKm;
315
+ if (country !== defaultCountry && !contradicted) {
316
+ return { country, postcode, locality, evidence: "locality", localityPlace };
317
+ }
318
+ }
319
+ // 4b. The locality is in no gazetteer (or names several countries) and the postcode is held in exactly one.
320
+ // `Biskupcova 1843/3, 13000 Praha 3`: `13000` is a CZ code and nothing else, anywhere.
321
+ if (!locHolders.size && pcHolders.size === 1) {
322
+ const [country, postcodePlace] = [...pcHolders.entries()][0];
323
+ if (country !== defaultCountry) {
324
+ return { country, postcode, locality, evidence: "postcode", postcodePlace };
325
+ }
326
+ }
327
+ return null;
328
+ }
329
+ /**
330
+ * Does `country` hold an exact, coordinate-bearing locality row for `locality`? One scoped lookup — deliberately NOT
331
+ * read off the unscoped holder window, which is population-first and truncated, so a small domestic bearer could fall
332
+ * below its fold and let a foreign scope through.
333
+ */
334
+ async function holdsLocality(backend, locality, country) {
335
+ try {
336
+ const hits = await backend.findPlace({ text: locality, placetype: "locality", country, limit: 3 });
337
+ return hits.some((hit) => hit.exactMatch && hasCoord(hit));
338
+ }
339
+ catch {
340
+ // A backend hiccup must not be read as "the default country has nothing" — that would license a foreign
341
+ // scope on no evidence. Treat it as corroboration and abstain.
342
+ return true;
343
+ }
344
+ }
345
+ /**
346
+ * Stamp the adopted scope onto the tree's postcode and locality nodes, so a consumer can see that the walk's country
347
+ * was not the one the caller asked for — and which evidence bought the change. Additive: identity and coordinates are
348
+ * untouched, this only writes `metadata`.
349
+ */
350
+ export function stampPostcodeCountryScope(roots, scope) {
351
+ const stack = [...roots];
352
+ while (stack.length) {
353
+ const n = stack.pop();
354
+ stack.push(...n.children);
355
+ if (n.tag !== "postcode" && n.tag !== "locality" && n.tag !== "dependent_locality")
356
+ continue;
357
+ n.metadata = {
358
+ ...n.metadata,
359
+ postcode_country_scope: scope.country,
360
+ // WHICH rung spoke — a two-sided agreement and a one-sided uniqueness claim are different evidence,
361
+ // and a consumer that cannot tell them apart cannot weight them differently.
362
+ postcode_country_scope_evidence: scope.evidence,
363
+ // Only the `pair` rung measured a distance. Writing a 0 for the single-sided rungs would assert an
364
+ // agreement nobody tested.
365
+ ...(scope.distanceKm !== undefined ? { postcode_country_scope_km: scope.distanceKm } : {}),
366
+ };
367
+ }
368
+ }
369
+ //# sourceMappingURL=postcode-country-coherence.js.map