@mailwoman/resolver 9.0.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 (79) 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 +91 -14
  43. package/out/postcode-country-coherence.d.ts.map +1 -1
  44. package/out/postcode-country-coherence.js +279 -42
  45. package/out/postcode-country-coherence.js.map +1 -1
  46. package/out/postcode-prefix.d.ts +101 -0
  47. package/out/postcode-prefix.d.ts.map +1 -0
  48. package/out/postcode-prefix.js +125 -0
  49. package/out/postcode-prefix.js.map +1 -0
  50. package/out/postcode-shape-coherence.d.ts +113 -0
  51. package/out/postcode-shape-coherence.d.ts.map +1 -0
  52. package/out/postcode-shape-coherence.js +193 -0
  53. package/out/postcode-shape-coherence.js.map +1 -0
  54. package/out/resolve.d.ts +1 -1
  55. package/out/resolve.d.ts.map +1 -1
  56. package/out/resolve.js +592 -410
  57. package/out/resolve.js.map +1 -1
  58. package/out/span-rescore.d.ts +28 -0
  59. package/out/span-rescore.d.ts.map +1 -1
  60. package/out/span-rescore.js +151 -17
  61. package/out/span-rescore.js.map +1 -1
  62. package/out/street-evidence.js +1 -1
  63. package/out/street-evidence.js.map +1 -1
  64. package/out/street-tier.d.ts.map +1 -1
  65. package/out/street-tier.js +28 -5
  66. package/out/street-tier.js.map +1 -1
  67. package/out/toponym-prior.d.ts +139 -0
  68. package/out/toponym-prior.d.ts.map +1 -0
  69. package/out/toponym-prior.js +308 -0
  70. package/out/toponym-prior.js.map +1 -0
  71. package/package.json +98 -7
  72. package/postcode-country-coherence.ts +355 -50
  73. package/postcode-prefix.ts +166 -0
  74. package/postcode-shape-coherence.ts +248 -0
  75. package/resolve.ts +809 -527
  76. package/span-rescore.ts +206 -19
  77. package/street-evidence.ts +1 -1
  78. package/street-tier.ts +31 -5
  79. package/toponym-prior.ts +367 -0
package/span-rescore.ts CHANGED
@@ -29,6 +29,9 @@ import type { AddressNode } from "@mailwoman/core/decoder"
29
29
  import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
30
30
  import { haversineKm } from "@mailwoman/spatial"
31
31
 
32
+ import { foldName } from "./fold-name.ts"
33
+ import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
34
+
32
35
  export interface SpanRescoreOptions {
33
36
  /**
34
37
  * ISO-3166 alpha-2 country to constrain the gazetteer match (the parse's detected/ default country).
@@ -60,6 +63,17 @@ export interface SpanRescoreOptions {
60
63
  * France" guard). Default false.
61
64
  */
62
65
  postalCompoundRecovery?: boolean
66
+ /**
67
+ * #17 bare-toponym soft country. When the span covers the WHOLE unqualified input, treat {@link country} as an
68
+ * additive prior instead of a hard gazetteer filter (see the block comment on {@link findRescoreCandidate}'s bare
69
+ * branch). Default true; `false` restores the hard filter byte-for-byte.
70
+ */
71
+ bareToponymSoftCountry?: boolean
72
+ /**
73
+ * Weight of that prior, in log10-population units. Default {@link DEFAULT_COUNTRY_PRIOR_WEIGHT} (2). A large value
74
+ * makes the country effectively hard again without changing the code path; 0 removes the locale's say entirely.
75
+ */
76
+ bareToponymCountryWeight?: number
63
77
  }
64
78
 
65
79
  /**
@@ -88,19 +102,25 @@ export interface RescoreCandidate {
88
102
  * calibrated 0.83 must not be confused with a rescore plug-in estimate).
89
103
  */
90
104
  gated: boolean
105
+ /**
106
+ * The SAME-SPAN namesake runner-ups — the other exact-name matches this recovery's own lookup already returned, in
107
+ * the backend's rank order, minus the winner and minus anything the postcode gate rejected. Empty when the span named
108
+ * exactly one place.
109
+ *
110
+ * #1537: these were being discarded. A name the model reads as a `street` ("Springfield", "Berlin", "Manchester",
111
+ * "Moscow", "Fulda") never reaches the admin walk, so the whole tree comes back unresolved and THIS tier is what
112
+ * recovers it — and it decorated the injected node with no alternatives at all. The result was that the geocode
113
+ * path's `candidates` array held one entry, and the top-1-vs-top-2 dominance margin that `declared_ambiguity` reads
114
+ * was uncomputable, for exactly the famous-homonym class that marker exists for. Measured on the shipped candidate
115
+ * backend, 2026-08-07: those five queries returned 1 candidate each while `Cambridge`/`Athens`/`Paris` — the same
116
+ * class, but parsed as `locality` — returned 4-5.
117
+ *
118
+ * The winner is unchanged by their presence: the pick is still the first gate-passing exact match, and these are the
119
+ * ones that came after it. This costs no extra query — they were in the same `findPlace` response.
120
+ */
121
+ alternatives: ResolvedPlace[]
91
122
  }
92
123
 
93
- /**
94
- * Normalize for exact comparison: lowercase, strip diacritics + punctuation, collapse whitespace.
95
- */
96
- const norm = (s: string): string =>
97
- s
98
- .toLowerCase()
99
- .normalize("NFD")
100
- .replaceAll(/[^a-z0-9 ]/g, " ")
101
- .replaceAll(/\s+/g, " ")
102
- .trim()
103
-
104
124
  interface RawTok {
105
125
  text: string
106
126
  start: number
@@ -135,6 +155,44 @@ export function postcodeCodeSubset(postcode: string): string {
135
155
  .trim()
136
156
  }
137
157
 
158
+ /**
159
+ * Over-fetch for the #17 bare-toponym probe. Without a country filter the top 5 worldwide bearers of a common name are
160
+ * often all in one country, and the candidate the soft prior exists to promote sits below the fold — "Warwick" puts
161
+ * five US rows ahead of Warwick, Warwickshire. The backend orders by the same population key either way, so a wider
162
+ * window only admits more of the same list.
163
+ */
164
+ const BARE_TOPONYM_FETCH = 20
165
+
166
+ /**
167
+ * True when the tree names its OWN admin context — a region, subregion, country, postcode or house number the parser
168
+ * read out of the input. Such a query is not relying on a locale guess, so the #17 soft-country prior stands down and
169
+ * the hard filter keeps its say: this is what holds 'Berlin, Wisconsin' on Berlin, Wisconsin.
170
+ */
171
+ function hasAdminQualifier(roots: readonly AddressNode[]): boolean {
172
+ const stack: AddressNode[] = [...roots]
173
+
174
+ while (stack.length) {
175
+ const n = stack.pop()!
176
+
177
+ if (
178
+ (n.tag === "region" ||
179
+ n.tag === "subregion" ||
180
+ n.tag === "country" ||
181
+ n.tag === "postcode" ||
182
+ n.tag === "house_number") &&
183
+ n.value.trim().length
184
+ ) {
185
+ return true
186
+ }
187
+
188
+ if (n.children?.length) {
189
+ stack.push(...n.children)
190
+ }
191
+ }
192
+
193
+ return false
194
+ }
195
+
138
196
  /**
139
197
  * True if any node in the tree already carries a resolved place id — the #685 brake.
140
198
  */
@@ -160,6 +218,41 @@ export function hasResolvedPlace(roots: readonly AddressNode[]): boolean {
160
218
  * NY" is a street suffix, not a locality, and without this guard the recovery exact-matches it against a same-named
161
219
  * place ("Ave", France) and injects a bogus locality.
162
220
  */
221
+ /**
222
+ * Ranges of MULTI-TOKEN `country` / `region` spans, used to block their INTERIOR tokens from being re-read as
223
+ * standalone places. The whole span itself stays probeable — only proper sub-spans are refused.
224
+ *
225
+ * The parse grouping is the claim: when the model binds `Papua`, `New` and `Guinea` into one country span, `New` is a
226
+ * modifier inside a name, not a name. Probing it anyway matches a real US place (`New`, wof:1276997945) and pins the
227
+ * address to Kentucky — an answer strictly worse than none, because it is confident and wrong.
228
+ *
229
+ * Deliberately NOT confidence-gated, unlike {@link confidentRanges}. The country node in that case carries 0.68, under
230
+ * the 0.7 bar, and a low-confidence GROUPING is still a grouping: the tokens were read as one name either way, and the
231
+ * interior of a name the parse doubts is not thereby a better standalone candidate. Single-token spans are excluded —
232
+ * there is no interior to protect.
233
+ */
234
+ function multiTokenNameInteriors(roots: readonly AddressNode[], raw: string): Array<[number, number]> {
235
+ const out: Array<[number, number]> = []
236
+ const stack: AddressNode[] = [...roots]
237
+
238
+ while (stack.length) {
239
+ const n = stack.pop()!
240
+
241
+ if (
242
+ (n.tag === "country" || n.tag === "region") &&
243
+ Number.isFinite(n.start) &&
244
+ Number.isFinite(n.end) &&
245
+ tokenizeRaw(raw.slice(n.start, n.end)).length > 1
246
+ ) {
247
+ out.push([n.start, n.end])
248
+ }
249
+
250
+ stack.push(...n.children)
251
+ }
252
+
253
+ return out
254
+ }
255
+
163
256
  function confidentRanges(
164
257
  roots: readonly AddressNode[],
165
258
  threshold: number,
@@ -255,6 +348,11 @@ export async function findRescoreCandidate(
255
348
  const toks = tokenizeRaw(raw)
256
349
  const avoid = confidentRanges(roots, threshold, raw, opts.postalCompoundRecovery ?? false)
257
350
  const overlapsAvoid = (s: number, e: number) => avoid.some(([as, ae]) => s < ae && as < e)
351
+ // Proper sub-spans of a multi-token country/region name are refused; the whole span is not.
352
+ const nameInteriors = multiTokenNameInteriors(roots, raw)
353
+
354
+ const isNameInterior = (s: number, e: number) =>
355
+ nameInteriors.some(([ns, ne]) => s >= ns && e <= ne && !(s === ns && e === ne))
258
356
 
259
357
  // Enumerate contiguous spans, LONGEST first — the gold locality is usually the more-specific
260
358
  // (longer) name; longest-wins lets it beat its own ambiguous prefix.
@@ -273,25 +371,106 @@ export async function findRescoreCandidate(
273
371
  const end = toks[i + len - 1]!.end
274
372
 
275
373
  if (overlapsAvoid(start, end)) continue
374
+
375
+ if (isNameInterior(start, end)) continue
276
376
  spans.push({ text: raw.slice(start, end), start, end, len })
277
377
  }
278
378
  }
279
379
 
280
380
  spans.sort((a, b) => b.len - a.len)
281
381
 
382
+ // #17 bare-toponym soft country. The caller's `country` is a LOCALE DEFAULT, not knowledge — the #961
383
+ // block below already says so, and for a bare city name it is the ONLY country signal there is, which
384
+ // makes hard-filtering on it the worst possible use of it. Measured through the compiled CLI on
385
+ // 2026-08-10: `--locale en-US 'Zürich'` returned Zurich, Kansas (population 81) 8,043 km off, and
386
+ // `--locale en-GB 'Zürich'` returned nothing at all, because GB holds no Zurich to filter down to.
387
+ //
388
+ // So for this ONE query shape the filter is demoted to an additive prior: probe the gazetteer
389
+ // unscoped, then rank with `rankByCountryPrior` so an in-country place may be up to 100x smaller and
390
+ // still win. This is the #912 lever ("Paris under en-US must not be hard-scoped to Paris, Texas")
391
+ // applied at the tier that actually decides the class — #912 lives upstream in the CLI and keys on a
392
+ // `locality`-tagged tree, but the model reads a bare famous name as a `street`, so the shape that
393
+ // needs it most is exactly the shape that guard cannot see.
394
+ //
395
+ // The shape gate is deliberately narrow. `qualified` below is the D-rule guard: a postcode, a region,
396
+ // a country or a house number in the tree means the address named its own context and a locale guess
397
+ // is no longer the only evidence — 'Berlin, Wisconsin' keeps resolving to Berlin, Wisconsin. And the
398
+ // span must cover the WHOLE input: a sub-span of a longer query is not a bare toponym, so
399
+ // "Weimar Thüringen" falls back to the country-scoped probe that lands the gold.
400
+ const softCountry = opts.bareToponymSoftCountry !== false
401
+ const countryWeight = opts.bareToponymCountryWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT
402
+ const qualified = !!postcode || hasAdminQualifier(roots)
403
+ const wholeInput = toks.length ? { start: toks[0]!.start, end: toks.at(-1)!.end } : null
404
+ // Everything the prior needs EXCEPT the span itself — hoisted so the per-span test is one comparison.
405
+ const softCountryEligible = softCountry && !!country && !qualified && !!wholeInput
406
+
282
407
  for (const sp of spans) {
283
- const key = norm(sp.text)
408
+ const key = foldName(sp.text)
284
409
 
285
410
  if (key.length < 2 || /^\d+$/.test(key)) continue // skip bare numbers / empties
286
- const hits = await backend.findPlace({ text: sp.text, country, postcode, placetype: "locality", limit: 5 })
287
- const exact = hits.filter((h) => h.exactMatch && norm(h.name) === key && (h.lat !== 0 || h.lon !== 0))
411
+ // Whole-input coverage and the soft-country prior are SEPARATE gates. `bare` (the prior) also
412
+ // needs an unqualified tree + a caller country; `wholeSpan` alone decides the alias tier below —
413
+ // a scope-less bare "Riyadh"/"Frankfurt" is still a NAMING (their Latin surfaces live in alias
414
+ // rows: الرياض / Frankfurt am Main), and conflating the two gates cost exactly those rows on the
415
+ // 2026-08-15 board before this line split them.
416
+ const wholeSpan = !!wholeInput && sp.start === wholeInput.start && sp.end === wholeInput.end
417
+ const bare = softCountryEligible && wholeSpan
418
+
419
+ const hits = bare
420
+ ? rankByCountryPrior(
421
+ await backend.findPlace({ text: sp.text, postcode, placetype: "locality", limit: BARE_TOPONYM_FETCH }),
422
+ country,
423
+ countryWeight
424
+ )
425
+ : // A SUB-span probe is a RE-READING of a token the parse classified into a longer span — it
426
+ // never NAMED an alias, so alias-keyed rows are off for it (`primaryOnly`, the #1632
427
+ // Savile→Rhu door). A whole-input span keeps the alias tier regardless of scope (the
428
+ // Москва/Riyadh-class exonym recall, #1546).
429
+ await backend.findPlace({
430
+ text: sp.text,
431
+ country,
432
+ postcode,
433
+ placetype: "locality",
434
+ limit: 5,
435
+ ...(wholeSpan ? {} : { primaryOnly: true }),
436
+ })
437
+
438
+ // #1546: NO primary-name re-check here — the backend's `exactMatch` IS the name-OR-alias surface
439
+ // equality (the names table / alt_names bag), so a query matches a place when ANY stored name
440
+ // equals it. Re-comparing only the PRIMARY name folded to [a-z0-9 ] excluded exactly the
441
+ // non-Latin-primary class: Москва folds to "" and could never equal "moscow", so Moscow RU never
442
+ // entered the list and Moscow, Idaho won by default among the Latin-named bearers — population-
443
+ // first ranking starved, not violated. The alias surface is the recall; ranking then does its job.
444
+ // The postcode gate below still applies to every admitted candidate, Moscow RU included.
445
+ //
446
+ // #17: importance-first WITHIN the admitted set. The key is the #28 blended fame prior
447
+ // (`PlaceCandidate.importance`, produced by the candidate build) — the only key that separates
448
+ // the bare GB panel rows; on an artifact predating the column it abstains and changes no pick.
449
+ // See `toponym-prior.ts`. It runs after the country prior deliberately: fame is the stronger
450
+ // signal when it has been measured, and leaves an unscored candidate exactly where population
451
+ // put it.
452
+ const exact = rankByImportance(hits.filter((h) => h.exactMatch && (h.lat !== 0 || h.lon !== 0)))
453
+
454
+ const withinGate = (p: ResolvedPlace): boolean =>
455
+ !anchor || gateKm <= 0 || haversineKm(anchor.lat, anchor.lon, p.lat, p.lon) <= gateKm
288
456
 
289
457
  for (const h of exact) {
290
- if (anchor && gateKm > 0 && haversineKm(anchor.lat, anchor.lon, h.lat, h.lon) > gateKm) continue
458
+ if (!withinGate(h)) continue
291
459
 
292
460
  // gated = the postcode anchor existed AND validated this match (within gateKm). When no anchor
293
461
  // (no postcode→point coverage), the match is ungated — returned, but flagged lower-precision.
294
- return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: anchor !== null }
462
+ //
463
+ // #1537: carry the rest of the SAME lookup's exact matches as the namesake runner-ups. Gate-filtered on the
464
+ // same rule as the winner — a candidate the postcode gate rejected is not a namesake worth offering, it is a
465
+ // place the evidence already excluded. Rank order is the backend's, preserved by `filter`.
466
+ return {
467
+ text: sp.text,
468
+ start: sp.start,
469
+ end: sp.end,
470
+ place: h,
471
+ gated: anchor !== null,
472
+ alternatives: exact.filter((a) => a !== h && withinGate(a)),
473
+ }
295
474
  }
296
475
  }
297
476
 
@@ -308,11 +487,14 @@ export async function findRescoreCandidate(
308
487
  const code = postcodeCodeSubset(postcode) || postcode.trim()
309
488
 
310
489
  for (const sp of spans) {
311
- const key = norm(sp.text)
490
+ const key = foldName(sp.text)
312
491
 
313
492
  if (key.length < 2 || /^\d+$/.test(key)) continue
314
493
  const hits = await backend.findPlace({ text: sp.text, placetype: "locality", limit: 5 })
315
- const exact = hits.filter((h) => h.exactMatch && norm(h.name) === key && (h.lat !== 0 || h.lon !== 0))
494
+ // #1546: same alias-surface admission as the scoped pass — `exactMatch` is name-OR-alias, so a
495
+ // non-Latin primary (Москва) admitted via its Latin alias stays eligible here too. The
496
+ // per-candidate postcode verification below remains the sole admission bar.
497
+ const exact = hits.filter((h) => h.exactMatch && (h.lat !== 0 || h.lon !== 0))
316
498
 
317
499
  for (const h of exact) {
318
500
  if (!h.country || h.country === country) continue
@@ -328,7 +510,12 @@ export async function findRescoreCandidate(
328
510
  const verified = pcHits.find((p) => p.lat !== 0 || p.lon !== 0)
329
511
 
330
512
  if (verified && haversineKm(verified.lat, verified.lon, h.lat, h.lon) <= gateKm) {
331
- return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: true }
513
+ // No alternatives from this pass, deliberately. Admission here is per-candidate postcode
514
+ // verification — one `findPlace` per runner-up — and the class it serves is the opposite of the
515
+ // namesake one: a postcode is present and has already picked the country, so there is nothing
516
+ // ambiguous left to declare. The bare-toponym queries #1537 is about never reach this branch (it
517
+ // requires a postcode).
518
+ return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: true, alternatives: [] }
332
519
  }
333
520
  }
334
521
  }
@@ -113,7 +113,7 @@ const FR_STREET_TYPE_WORDS: ReadonlySet<string> = new Set([
113
113
  * True when the folded surface contains no token outside {@link FR_STREET_TYPE_WORDS} — i.e. it is pure type/particle.
114
114
  */
115
115
  export function isPureTypeVocabulary(foldedSurface: string): boolean {
116
- const tokens = foldedSurface.split(" ").filter(Boolean)
116
+ const tokens = foldedSurface.split(" ").filter((value) => value.length > 0)
117
117
 
118
118
  if (!tokens.length) return true
119
119
 
package/street-tier.ts CHANGED
@@ -15,7 +15,6 @@
15
15
  import { isStreetDirectionalToken } from "@mailwoman/codex/us"
16
16
  import type { AddressNode } from "@mailwoman/core/decoder"
17
17
  import type { AddressPointLookup, InterpolationLookup, StreetCentroidLookup } from "@mailwoman/core/resolver"
18
- import { haversineKm } from "@mailwoman/spatial"
19
18
 
20
19
  import { foldName } from "./fold-name.ts"
21
20
 
@@ -118,6 +117,8 @@ export function applyAddressPoint(roots: AddressNode[], lookup: AddressPointLook
118
117
 
119
118
  if (!street || !houseNumber) return
120
119
 
120
+ if (street.metadata?.["resolution_tier"] === "address_point") return
121
+
121
122
  // #247 OSM bbox fall-through: when enabled (an OSM shard is wired) and the locality resolved to a
122
123
  // coordinate, scope a final `(street, number)` probe by the locality's box — recovering OSM points that
123
124
  // carry no postcode/locality tag of their own. US situs never enables it, so its probes are byte-identical.
@@ -144,7 +145,16 @@ export function applyAddressPoint(roots: AddressNode[], lookup: AddressPointLook
144
145
 
145
146
  street.metadata = {
146
147
  ...street.metadata,
147
- address_point: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
148
+ address_point: {
149
+ lat: hit.lat,
150
+ lon: hit.lon,
151
+ source: hit.source,
152
+ release: hit.release,
153
+ // The register row's OWN scope tags, when carried — a rooftop consumer can decorate the
154
+ // commune/postcode the register attests even when the query never named them.
155
+ ...(hit.localityNorm ? { locality_norm: hit.localityNorm } : {}),
156
+ ...(hit.postcode ? { postcode: hit.postcode } : {}),
157
+ },
148
158
  resolution_tier: "address_point",
149
159
  }
150
160
  }
@@ -165,6 +175,7 @@ export function applyInterpolation(
165
175
  let houseNumber: AddressNode | undefined
166
176
  let directionalUnit: AddressNode | undefined
167
177
  let postcode: string | undefined
178
+ let localityCoord: { lat: number; lon: number } | undefined
168
179
  const stack = [...roots]
169
180
 
170
181
  while (stack.length) {
@@ -186,6 +197,13 @@ export function applyInterpolation(
186
197
  postcode = n.value.trim()
187
198
  }
188
199
 
200
+ // The resolved locality's coordinate — the `near` tie-breaker the interpolator may consult when
201
+ // the query carries no postcode and the covering ranges span several ZIPs (the borough-namesake
202
+ // class). Only a RESOLVED locality qualifies; an unresolved one contributes nothing.
203
+ if (n.tag === "locality" && !localityCoord && n.lat != null && n.lon != null) {
204
+ localityCoord = { lat: n.lat, lon: n.lon }
205
+ }
206
+
189
207
  stack.push(...n.children)
190
208
  }
191
209
 
@@ -193,7 +211,15 @@ export function applyInterpolation(
193
211
 
194
212
  // The fall-through gate: an exact situs point already won — never override it with an estimate.
195
213
  if (street.metadata?.["resolution_tier"] === "address_point") return
196
- const hit = lookup.find({ street: assembleStreetValue(street, directionalUnit), number: houseNumber.value, postcode })
214
+
215
+ const near = postcode ? undefined : localityCoord
216
+
217
+ const hit = lookup.find({
218
+ street: assembleStreetValue(street, directionalUnit),
219
+ number: houseNumber.value,
220
+ postcode,
221
+ ...(near ? { near } : {}),
222
+ })
197
223
 
198
224
  if (!hit) return
199
225
  // Conformal-calibrated radius (#374): the raw half-segment heuristic underestimates the true spread
@@ -286,7 +312,7 @@ function foldVoieTokens(s: string): string[] {
286
312
  .replaceAll(/[.,'’]/g, "")
287
313
  .replaceAll("-", " ")
288
314
  .split(/\s+/)
289
- .filter(Boolean)
315
+ .filter((token) => token.length > 0)
290
316
  }
291
317
 
292
318
  /**
@@ -389,7 +415,7 @@ export function applyStreetCentroid(
389
415
  const rawSegments = raw
390
416
  .split(",")
391
417
  .map((s) => s.trim())
392
- .filter(Boolean)
418
+ .filter((segment) => segment.length > 0)
393
419
 
394
420
  const CAP = 5
395
421