@mailwoman/resolver 9.1.0 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +89 -0
  2. package/admin-coherence-passes.ts +435 -0
  3. package/admin-containment.ts +101 -0
  4. package/admin-winner.ts +178 -0
  5. package/backend-capabilities.ts +88 -0
  6. package/bare-toponym-race.ts +129 -0
  7. package/decorate-node.ts +127 -0
  8. package/fold-name.ts +19 -3
  9. package/index.ts +14 -0
  10. package/out/admin-coherence-passes.d.ts +70 -0
  11. package/out/admin-coherence-passes.d.ts.map +1 -0
  12. package/out/admin-coherence-passes.js +327 -0
  13. package/out/admin-coherence-passes.js.map +1 -0
  14. package/out/admin-containment.d.ts +48 -0
  15. package/out/admin-containment.d.ts.map +1 -0
  16. package/out/admin-containment.js +82 -0
  17. package/out/admin-containment.js.map +1 -0
  18. package/out/admin-winner.d.ts +109 -0
  19. package/out/admin-winner.d.ts.map +1 -0
  20. package/out/admin-winner.js +119 -0
  21. package/out/admin-winner.js.map +1 -0
  22. package/out/backend-capabilities.d.ts +37 -0
  23. package/out/backend-capabilities.d.ts.map +1 -0
  24. package/out/backend-capabilities.js +75 -0
  25. package/out/backend-capabilities.js.map +1 -0
  26. package/out/bare-toponym-race.d.ts +55 -0
  27. package/out/bare-toponym-race.d.ts.map +1 -0
  28. package/out/bare-toponym-race.js +110 -0
  29. package/out/bare-toponym-race.js.map +1 -0
  30. package/out/decorate-node.d.ts +24 -0
  31. package/out/decorate-node.d.ts.map +1 -0
  32. package/out/decorate-node.js +103 -0
  33. package/out/decorate-node.js.map +1 -0
  34. package/out/fold-name.d.ts +18 -3
  35. package/out/fold-name.d.ts.map +1 -1
  36. package/out/fold-name.js +19 -3
  37. package/out/fold-name.js.map +1 -1
  38. package/out/index.d.ts +4 -1
  39. package/out/index.d.ts.map +1 -1
  40. package/out/index.js +3 -1
  41. package/out/index.js.map +1 -1
  42. package/out/postcode-country-coherence.d.ts +31 -10
  43. package/out/postcode-country-coherence.d.ts.map +1 -1
  44. package/out/postcode-country-coherence.js +137 -56
  45. package/out/postcode-country-coherence.js.map +1 -1
  46. package/out/postcode-prefix.d.ts.map +1 -1
  47. package/out/postcode-prefix.js +3 -2
  48. package/out/postcode-prefix.js.map +1 -1
  49. package/out/postcode-shape-coherence.js.map +1 -1
  50. package/out/resolve.d.ts +1 -1
  51. package/out/resolve.d.ts.map +1 -1
  52. package/out/resolve.js +461 -416
  53. package/out/resolve.js.map +1 -1
  54. package/out/span-rescore.d.ts.map +1 -1
  55. package/out/span-rescore.js +55 -13
  56. package/out/span-rescore.js.map +1 -1
  57. package/out/street-evidence.js +1 -1
  58. package/out/street-evidence.js.map +1 -1
  59. package/out/street-tier.d.ts.map +1 -1
  60. package/out/street-tier.js +26 -5
  61. package/out/street-tier.js.map +1 -1
  62. package/out/toponym-prior.d.ts +42 -18
  63. package/out/toponym-prior.d.ts.map +1 -1
  64. package/out/toponym-prior.js +75 -7
  65. package/out/toponym-prior.js.map +1 -1
  66. package/package.json +98 -7
  67. package/postcode-country-coherence.ts +150 -58
  68. package/postcode-prefix.ts +3 -2
  69. package/postcode-shape-coherence.ts +1 -1
  70. package/resolve.ts +626 -531
  71. package/span-rescore.ts +64 -15
  72. package/street-evidence.ts +1 -1
  73. package/street-tier.ts +29 -5
  74. package/toponym-prior.ts +96 -7
@@ -41,7 +41,10 @@
41
41
  * rank population gave it while the scored rows reorder among themselves. On a candidate.db built
42
42
  * before the #28 `importance` column, nothing is scored, so {@link rankByImportance} is
43
43
  * byte-stable by construction.
44
- * 3. **Stable.** Equal keys keep their incoming order, so the backend's own ranking survives underneath.
44
+ * 3. **Stable.** Equal keys keep their incoming order, so the backend's own ranking survives underneath. That order
45
+ * carries decisions only the backend can make — the candidate backend's seat tiebreak
46
+ * (`resolver-wof-sqlite/primary-preference.ts`) reaches an end-to-end answer solely through this stability
47
+ * (#1729), so equal-key stability here is load-bearing, not cosmetic.
45
48
  */
46
49
  /**
47
50
  * Weight of the locale-country bonus, in the same log10-population units the candidate backend's `prominence` uses
@@ -72,7 +75,7 @@ export const DEFAULT_COUNTRY_PRIOR_WEIGHT = 2;
72
75
  * policy (ROAD_TO_V9) says: within a country the geocoder ranks referentially; the blended prior's job is the
73
76
  * cross-country question — which country's bearer a bare query meant.
74
77
  */
75
- export const SAME_COUNTRY_IMPORTANCE_TIE_BAND = 0.02;
78
+ const SAME_COUNTRY_IMPORTANCE_TIE_BAND = 0.02;
76
79
  /**
77
80
  * Partition into (exact, rest), sort each half with `key` DESC, and re-join. The partition is what keeps a soft prior
78
81
  * soft: it can only ever re-order candidates the backend already considers equally good matches. Backends that don't
@@ -84,7 +87,7 @@ function rankWithinTier(candidates, compare) {
84
87
  const rest = [];
85
88
  for (const c of candidates) {
86
89
  // `exactMatch` is TRI-STATE: true / false / undefined (a backend path that stamps no flag —
87
- // e.g. WOFSqlitePlaceLookup's postcode-area neighbours from #fetchLocalitiesByID). Only a
90
+ // e.g. WOFSQLitePlaceLookup's postcode-area neighbours from #fetchLocalitiesByID). Only a
88
91
  // stated TRUE earns the exact tier; undefined must not outrank a real fuzzy name match
89
92
  // (the 2026-08-10 de.native_locality incident: 75 Saxon towns lost to nameless neighbours).
90
93
  ;
@@ -191,10 +194,10 @@ function orderMeasuredByImportance(rows) {
191
194
  * fewer than two candidates are scored.
192
195
  *
193
196
  * The producer is the candidate build's `importance` column (#28) — the BLENDED prior (the concordance's
194
- * encyclopedia-derived channel where a concordance matched, a population-derived proxy elsewhere; see
195
- * `candidate-schema.ts` → `CandidateTable.importance` for why the strict channel is deliberately NOT what lands there).
196
- * On an artifact predating the column, `importance` is `undefined` on every candidate the backend produces and the
197
- * abstention below keeps the ranking byte-stable.
197
+ * encyclopedia-derived channel clamped around a population-derived base — `place-importance-schema.ts`'s
198
+ * `blendImportance`; see `candidate-schema.ts` → `CandidateTable.importance` for why the strict channel is deliberately
199
+ * NOT what lands there). On an artifact predating the column, `importance` is `undefined` on every candidate the
200
+ * backend produces and the abstention below keeps the ranking byte-stable.
198
201
  *
199
202
  * Flip decisions, ratified 2026-08-11: bare `Moscow`→Москва, `Manchester`→GB, `Fulda`→DE, `Cambridge`→GB are ACCEPTED
200
203
  * behavior — all cross-country contests, where this prior answers the question population cannot. Bare `Springfield`
@@ -237,4 +240,69 @@ export function rankByCountryPrior(candidates, country, weight = DEFAULT_COUNTRY
237
240
  const key = (c) => size(c) + (c.country?.toUpperCase() === target ? weight : 0);
238
241
  return rankWithinTier(candidates, (a, b) => key(b) - key(a));
239
242
  }
243
+ /**
244
+ * The level a candidate must hold to be PROMOTED: national capitals only. Admin-1 seats stay un-promoted, and that
245
+ * scope is forced by decided rows, not caution — a seat margin of even 1 log10 unit flips bare `Springfield` to
246
+ * Springfield, Illinois against the ratified 2026-08-11 referential decision
247
+ * ({@link SAME_COUNTRY_IMPORTANCE_TIE_BAND}), and sends bare `Hamilton` to the Waikato seat (Hamilton NZ, 2.8x smaller
248
+ * than Hamilton, Ontario), both measured on the shipped `candidate.db`. The reference still records seats; no consumer
249
+ * promotes on them.
250
+ */
251
+ const PROMOTABLE_CAPITAL_LEVEL = 2;
252
+ /**
253
+ * Margin a national capital may give away, in log10-population units: a namesake must be more than 10^2 = 100x more
254
+ * populous to hold the lead. Bare "San José" reaches the Costa Rican capital (342,188) over San Jose, California
255
+ * (969,655 — 2.8x); bare "Hamilton" stays on Hamilton, Ontario (519,949) over Bermuda's 902-person capital (576x).
256
+ */
257
+ export const NATIONAL_CAPITAL_MARGIN_LOG10 = 2;
258
+ /**
259
+ * Bounded capital promotion (#1880) — the third soft key for the bare-toponym class, applied AFTER
260
+ * {@link rankByImportance} because the fame prior is what decides this class and a capital signal parked below the
261
+ * deciding stage measurably never reaches an answer (the iteration-1 board run: the candidate-order bonus reordered
262
+ * `findPlace` on every target row and moved 0 of the 12).
263
+ *
264
+ * The rule: within the exact tier, take the first NATIONAL-capital row and walk it upward past each row it is within
265
+ * {@link NATIONAL_CAPITAL_MARGIN_LOG10} of, stopping at the first row over the margin or at another national capital.
266
+ * Same three house rules as the other keys — tier-safe (never crosses the exact/partial boundary; the cost is real and
267
+ * accepted: a capital that only PARTIALLY matched the query — Saint George's, Grenada for the abbreviated "St.
268
+ * George's" — stays behind every exact match, because crossing that line is how iteration 1 answered bare "Djibouti"
269
+ * with the capital city instead of the country), positive evidence only (no capital in the list → identity, and the
270
+ * margin reads the same `prominence ?? score` size every other key does), and stable (non-promoted rows keep their
271
+ * order).
272
+ *
273
+ * The margin deliberately re-uses log10-population units rather than the importance scale: the ratified importance flip
274
+ * decisions (Whitby/Windsor/Springfield) sit on gaps of 0.004–0.02, while the capital contests this key exists for sit
275
+ * on gaps of 0.21–0.24 — an importance-scale bonus big enough to win them would dwarf every ratified decision on the
276
+ * same scale.
277
+ */
278
+ export function promoteCapitals(candidates, level) {
279
+ if (!level || candidates.length < 2)
280
+ return [...candidates];
281
+ const exact = [];
282
+ const rest = [];
283
+ for (const c of candidates) {
284
+ // Tri-state exactMatch, same reading as rankWithinTier: only a stated TRUE earns the tier.
285
+ ;
286
+ (c.exactMatch === true ? exact : rest).push(c);
287
+ }
288
+ const tier = exact.length ? exact : rest;
289
+ const best = tier.findIndex((c) => level(c) >= PROMOTABLE_CAPITAL_LEVEL);
290
+ if (best <= 0)
291
+ return [...candidates];
292
+ let target = best;
293
+ while (target > 0) {
294
+ const above = tier[target - 1];
295
+ if (level(above) >= PROMOTABLE_CAPITAL_LEVEL)
296
+ break;
297
+ if (size(tier[best]) + NATIONAL_CAPITAL_MARGIN_LOG10 < size(above))
298
+ break;
299
+ target--;
300
+ }
301
+ if (target === best)
302
+ return [...candidates];
303
+ const reordered = [...tier];
304
+ const [capital] = reordered.splice(best, 1);
305
+ reordered.splice(target, 0, capital);
306
+ return exact.length ? [...reordered, ...rest] : reordered;
307
+ }
240
308
  //# sourceMappingURL=toponym-prior.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"toponym-prior.js","sourceRoot":"","sources":["../to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C,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;IACxC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,wBAAwB,CAAC,CAAA;IAExE,IAAI,IAAI,IAAI,CAAC;QAAE,OAAO,CAAC,GAAG,UAAU,CAAC,CAAA;IAErC,IAAI,MAAM,GAAG,IAAI,CAAA;IAEjB,OAAO,MAAM,GAAG,CAAC,EAAE,CAAC;QACnB,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,CAAA;QAE/B,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,wBAAwB;YAAE,MAAK;QAEnD,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAE,CAAC,GAAG,6BAA6B,GAAG,IAAI,CAAC,KAAK,CAAC;YAAE,MAAK;QAE1E,MAAM,EAAE,CAAA;IACT,CAAC;IAED,IAAI,MAAM,KAAK,IAAI;QAAE,OAAO,CAAC,GAAG,UAAU,CAAC,CAAA;IAE3C,MAAM,SAAS,GAAG,CAAC,GAAG,IAAI,CAAC,CAAA;IAC3B,MAAM,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IAE3C,SAAS,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,OAAQ,CAAC,CAAA;IAErC,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;AAC1D,CAAC"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@mailwoman/resolver",
3
- "version": "9.1.0",
3
+ "version": "9.2.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": {
7
7
  "type": "git",
8
8
  "url": "https://github.com/sister-software/mailwoman.git",
9
- "directory": "resolver"
9
+ "directory": "packages/resolver"
10
10
  },
11
11
  "files": [
12
12
  "out/**/*.js",
@@ -20,9 +20,11 @@
20
20
  "!*.test.ts",
21
21
  "!*.test.tsx",
22
22
  "!**/*.test.ts",
23
- "!**/*.test.tsx"
23
+ "!**/*.test.tsx",
24
+ "!test/**"
24
25
  ],
25
26
  "type": "module",
27
+ "imports": {},
26
28
  "exports": {
27
29
  "./package.json": "./package.json",
28
30
  ".": {
@@ -40,6 +42,50 @@
40
42
  "./span-rescore": {
41
43
  "types": "./out/span-rescore.d.ts",
42
44
  "default": "./out/span-rescore.js"
45
+ },
46
+ "./backend-capabilities": {
47
+ "types": "./out/backend-capabilities.d.ts",
48
+ "default": "./out/backend-capabilities.js"
49
+ },
50
+ "./admin-containment": {
51
+ "types": "./out/admin-containment.d.ts",
52
+ "default": "./out/admin-containment.js"
53
+ },
54
+ "./admin-winner": {
55
+ "types": "./out/admin-winner.d.ts",
56
+ "default": "./out/admin-winner.js"
57
+ },
58
+ "./decorate-node": {
59
+ "types": "./out/decorate-node.d.ts",
60
+ "default": "./out/decorate-node.js"
61
+ },
62
+ "./plausibility": {
63
+ "types": "./out/plausibility.d.ts",
64
+ "default": "./out/plausibility.js"
65
+ },
66
+ "./postcode-prefix": {
67
+ "types": "./out/postcode-prefix.d.ts",
68
+ "default": "./out/postcode-prefix.js"
69
+ },
70
+ "./postcode-shape-coherence": {
71
+ "types": "./out/postcode-shape-coherence.d.ts",
72
+ "default": "./out/postcode-shape-coherence.js"
73
+ },
74
+ "./remote-resolver": {
75
+ "types": "./out/remote-resolver.d.ts",
76
+ "default": "./out/remote-resolver.js"
77
+ },
78
+ "./rerank": {
79
+ "types": "./out/rerank.d.ts",
80
+ "default": "./out/rerank.js"
81
+ },
82
+ "./street-evidence": {
83
+ "types": "./out/street-evidence.d.ts",
84
+ "default": "./out/street-evidence.js"
85
+ },
86
+ "./toponym-prior": {
87
+ "types": "./out/toponym-prior.d.ts",
88
+ "default": "./out/toponym-prior.js"
43
89
  }
44
90
  },
45
91
  "publishConfig": {
@@ -61,12 +107,57 @@
61
107
  "./span-rescore": {
62
108
  "types": "./out/span-rescore.d.ts",
63
109
  "default": "./out/span-rescore.js"
110
+ },
111
+ "./backend-capabilities": {
112
+ "types": "./out/backend-capabilities.d.ts",
113
+ "default": "./out/backend-capabilities.js"
114
+ },
115
+ "./admin-containment": {
116
+ "types": "./out/admin-containment.d.ts",
117
+ "default": "./out/admin-containment.js"
118
+ },
119
+ "./admin-winner": {
120
+ "types": "./out/admin-winner.d.ts",
121
+ "default": "./out/admin-winner.js"
122
+ },
123
+ "./decorate-node": {
124
+ "types": "./out/decorate-node.d.ts",
125
+ "default": "./out/decorate-node.js"
126
+ },
127
+ "./plausibility": {
128
+ "types": "./out/plausibility.d.ts",
129
+ "default": "./out/plausibility.js"
130
+ },
131
+ "./postcode-prefix": {
132
+ "types": "./out/postcode-prefix.d.ts",
133
+ "default": "./out/postcode-prefix.js"
134
+ },
135
+ "./postcode-shape-coherence": {
136
+ "types": "./out/postcode-shape-coherence.d.ts",
137
+ "default": "./out/postcode-shape-coherence.js"
138
+ },
139
+ "./remote-resolver": {
140
+ "types": "./out/remote-resolver.d.ts",
141
+ "default": "./out/remote-resolver.js"
142
+ },
143
+ "./rerank": {
144
+ "types": "./out/rerank.d.ts",
145
+ "default": "./out/rerank.js"
146
+ },
147
+ "./street-evidence": {
148
+ "types": "./out/street-evidence.d.ts",
149
+ "default": "./out/street-evidence.js"
150
+ },
151
+ "./toponym-prior": {
152
+ "types": "./out/toponym-prior.d.ts",
153
+ "default": "./out/toponym-prior.js"
64
154
  }
65
- }
155
+ },
156
+ "imports": {}
66
157
  },
67
158
  "dependencies": {
68
- "@mailwoman/codex": "9.1.0",
69
- "@mailwoman/core": "9.1.0",
70
- "@mailwoman/spatial": "9.1.0"
159
+ "@mailwoman/codex": "9.2.0",
160
+ "@mailwoman/core": "9.2.0",
161
+ "@mailwoman/spatial": "9.2.0"
71
162
  }
72
163
  }
@@ -76,8 +76,10 @@
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
  *
@@ -90,9 +92,9 @@
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
100
  * both ways, returned zero newly-failing gated cases, and 56,000 pair evaluations across both
@@ -171,10 +173,12 @@ 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
183
  * Consistency gate radius in km. Defaults to {@link POSTCODE_COUNTRY_COHERENCE_GATE_KM}.
180
184
  */
@@ -200,23 +204,60 @@ function hasCoord(p: ResolvedPlace): boolean {
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 load-bearing, 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
+ }
236
+
237
+ return out.slice(0, MAX_LOCALITY_VALUES)
238
+ }
209
239
 
210
- while (stack.length) {
211
- const n = stack.pop()!
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
+ }
212
246
 
213
- if (n.tag === tag && n.value.trim().length) return n.value.trim()
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
  }
@@ -358,22 +400,28 @@ export async function findPostcodeCountryScope(
358
400
  opts: PostcodeCountryScopeOpts
359
401
  ): Promise<PostcodeCountryScope | null> {
360
402
  const postcode = opts.postcode.trim()
361
- const defaultCountry = opts.defaultCountry.trim().toUpperCase()
403
+ const defaultCountry = opts.defaultCountry?.trim().toUpperCase() || undefined
362
404
 
363
- if (!postcode || !defaultCountry) return null
405
+ if (!postcode) return null
364
406
 
365
- const locality = firstLocalityValue(roots)
407
+ const localities = localityValuesInDocumentOrder(roots)
366
408
 
367
409
  // Both halves of the pair are required. A postcode with no locality has nothing to be coherent WITH, which is what
368
410
  // keeps this pass inert on "Springfield, IL 62701" (the parser tags Springfield as a `street` — a separate defect)
369
411
  // and on every bare-postcode query.
370
- if (!locality) return null
412
+ if (!localities.length) return null
371
413
 
372
414
  const gateKm = opts.gateKm ?? POSTCODE_COUNTRY_COHERENCE_GATE_KM
373
415
 
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
416
+ // 1. Is the caller's own default country coherent with ANY of the address's locality values? If so we are done —
417
+ // positive evidence for the default, no override, and the common domestic path (one locality value) costs two
418
+ // lookups and changes nothing. With no default in force (the browser cascade) there is nothing to test — the
419
+ // sweep below carries the whole verdict.
420
+ if (defaultCountry) {
421
+ for (const locality of localities) {
422
+ if (await coherenceIn(defaultCountry, postcode, locality, backend, gateKm)) return null
423
+ }
424
+ }
377
425
 
378
426
  // 2. The default could not place this pair. Which countries could? Two sources, unioned:
379
427
  //
@@ -397,22 +445,33 @@ export async function findPostcodeCountryScope(
397
445
  .filter((country) => country !== defaultCountry)
398
446
  .slice(0, MAX_CANDIDATE_COUNTRIES)
399
447
 
400
- const coherent: PostcodeCountryScope[] = []
448
+ // 3. The pair sweep, per locality value in document order: the first value that produces evidence decides. A value
449
+ // the band cannot see (`Aravaca`, a neighbourhood) yields zero coherent countries and the NEXT value gets its
450
+ // turn — betting the verdict on a single value re-scoped that address to a US ZIP centroid (see
451
+ // localityValuesInDocumentOrder). Exactly one coherent country is a verdict. Two coherent countries mean the
452
+ // geometry genuinely does not decide, and guessing between them is precisely what this mechanism exists not to
453
+ // do — a TIE is a hard abstention, never a fall-through to a later value or the weaker rungs below.
454
+ for (const locality of localities) {
455
+ const coherent: PostcodeCountryScope[] = []
456
+
457
+ for (const country of candidates) {
458
+ const hit = await coherenceIn(country, postcode, locality, backend, gateKm, pcHolders.get(country))
459
+
460
+ if (hit) {
461
+ coherent.push({ country, postcode, locality, evidence: "pair", ...hit })
462
+ }
463
+ }
401
464
 
402
- for (const country of candidates) {
403
- const hit = await coherenceIn(country, postcode, locality, backend, gateKm, pcHolders.get(country))
465
+ if (coherent.length === 1) return coherent[0]!
404
466
 
405
- if (hit) {
406
- coherent.push({ country, postcode, locality, evidence: "pair", ...hit })
407
- }
467
+ if (coherent.length > 1) return null
408
468
  }
409
469
 
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
470
+ // The single-sided rungs below lean on the DEFAULT country as the domestic-plausibility guard
471
+ // ("Vienna, VA" stays in Virginia because the default corroborates a half). With no default there
472
+ // is no such anchor, so the no-default path ends at the pair rung: a pair verdict (Zabiče) is
473
+ // in-scope, a single-sided guess is not.
474
+ if (!defaultCountry) return null
416
475
 
417
476
  // 4. No country makes the PAIR consistent. On the 2026-08-09 panel that happened 10 times for two opposite
418
477
  // reasons, and in both the address's country was never in doubt — only unrepresentable as a pair:
@@ -421,23 +480,49 @@ export async function findPostcodeCountryScope(
421
480
  // agree with anything no matter how good the locality evidence is; or
422
481
  // - the locality is a name no admin gazetteer carries (`Praha 3`, `Praha 9` — municipal districts).
423
482
  //
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.
483
+ // So each half gets to speak alone, under conditions that keep this from becoming a guess. The
484
+ // POSTCODE half is all-or-nothing: the default country holding this postcode makes the address
485
+ // domestically plausible outright, and nothing foreign may be proposed. The LOCALITY half is
486
+ // judged PER VALUE — a value the default country holds is domestic corroboration for THAT value
487
+ // (it is neutralized as a foreign witness) without silencing its siblings. `14 Long St, Green
488
+ // Point, Cape Town, 8001` is why: "Green Point" has pop-0 US namesakes, and letting that one
489
+ // value abstain the whole pass handed a uniquely-ZA "Cape Town" to a hard US filter (the walk
490
+ // answered Green Point, Pennsylvania). `123 Main St, Vienna, VA 22180` still holds in Virginia:
491
+ // its ONLY locality value is domestic, so no foreign witness remains. The speaking value must
492
+ // name EXACTLY ONE country in the entire gazetteer — the same uniqueness bar the pair rung uses,
493
+ // applied to one side — and all speaking values must AGREE on that country.
430
494
  if (pcHolders.has(defaultCountry)) return null
431
495
 
432
- if (await holdsLocality(backend, locality, defaultCountry)) return null
496
+ // 4a. A locality value names exactly one country. Stronger than the postcode rung — a place name is far
497
+ // more discriminative than a four-digit code — so it is tried first. A verdict stands down when that
498
+ // country's OWN postcode row contradicts the locality (outside the gate): the two halves disagreeing
499
+ // inside one country is exactly what the pair test exists to catch, and a single-sided rung must not
500
+ // launder it.
501
+ // PRIMARY-keyed rows only (#1626's re-reading discipline, applied to a country verdict): "the locality
502
+ // names exactly one country" must mean a place NAMED that, never a place aliased to it — "NL"'s only
503
+ // locality-band bearer was an exact ALIAS of Nal, Afghanistan, and a single alias row steered the whole
504
+ // walk's country. The pair rung keeps aliases: there the postcode's own geometry corroborates them.
505
+ let anyDomestic = false
506
+ let anyLocalityKnown = false
507
+ const verdicts = new Map<string, PostcodeCountryScope>()
508
+
509
+ for (const locality of localities) {
510
+ if (await holdsLocality(backend, locality, defaultCountry)) {
511
+ anyDomestic = true
512
+
513
+ continue
514
+ }
515
+
516
+ const locHolders = await countriesHolding(backend, locality, "locality", LOCALITY_HOLDER_FETCH, {
517
+ primaryOnly: true,
518
+ })
519
+
520
+ if (locHolders.size) {
521
+ anyLocalityKnown = true
522
+ }
433
523
 
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)
524
+ if (locHolders.size !== 1) continue
439
525
 
440
- if (locHolders.size === 1) {
441
526
  const [country, localityPlace] = [...locHolders.entries()][0]!
442
527
  const ownPostcode = pcHolders.get(country)
443
528
 
@@ -445,18 +530,25 @@ export async function findPostcodeCountryScope(
445
530
  ownPostcode !== undefined &&
446
531
  haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > gateKm
447
532
 
448
- if (country !== defaultCountry && !contradicted) {
449
- return { country, postcode, locality, evidence: "locality", localityPlace }
533
+ if (country !== defaultCountry && !contradicted && !verdicts.has(country)) {
534
+ verdicts.set(country, { country, postcode, locality, evidence: "locality", localityPlace })
450
535
  }
451
536
  }
452
537
 
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) {
538
+ // Every speaking value must agree: two values uniquely naming DIFFERENT countries is a genuine
539
+ // ambiguity, and guessing between them is what this mechanism exists not to do.
540
+ if (verdicts.size === 1) return [...verdicts.values()][0]!
541
+
542
+ if (verdicts.size > 1) return null
543
+
544
+ // 4b. The postcode is held in exactly one country and the locality half is silent EVERYWHERE — no value
545
+ // is domestic and no value names any country. `Biskupcova 1843/3, 13000 Praha 3`: `13000` is a CZ
546
+ // code and nothing else, anywhere, and `Praha 3` (a municipal district) is in no admin gazetteer.
547
+ if (!anyDomestic && !anyLocalityKnown && pcHolders.size === 1) {
456
548
  const [country, postcodePlace] = [...pcHolders.entries()][0]!
457
549
 
458
550
  if (country !== defaultCountry) {
459
- return { country, postcode, locality, evidence: "postcode", postcodePlace }
551
+ return { country, postcode, locality: localities[0]!, evidence: "postcode", postcodePlace }
460
552
  }
461
553
  }
462
554
 
@@ -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:
@@ -74,7 +74,7 @@
74
74
  * false exclusions; kill on any B1-3 δ).
75
75
  */
76
76
 
77
- import { candidateSystemsForPostcode, type SystemCode } from "@mailwoman/codex"
77
+ import { candidateSystemsForPostcode } from "@mailwoman/codex"
78
78
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
79
79
  import { isUSStateAbbreviation } from "@mailwoman/codex/us"
80
80
  import type { AddressNode } from "@mailwoman/core/decoder"