@mailwoman/resolver 8.0.0 → 8.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 (45) hide show
  1. package/fold-name.ts +20 -0
  2. package/index.ts +13 -2
  3. package/out/fold-name.d.ts +13 -0
  4. package/out/fold-name.d.ts.map +1 -0
  5. package/out/fold-name.js +20 -0
  6. package/out/fold-name.js.map +1 -0
  7. package/out/index.d.ts +2 -2
  8. package/out/index.d.ts.map +1 -1
  9. package/out/index.js +1 -1
  10. package/out/index.js.map +1 -1
  11. package/out/plausibility.d.ts +40 -6
  12. package/out/plausibility.d.ts.map +1 -1
  13. package/out/plausibility.js +24 -5
  14. package/out/plausibility.js.map +1 -1
  15. package/out/remote-resolver.d.ts +21 -7
  16. package/out/remote-resolver.d.ts.map +1 -1
  17. package/out/remote-resolver.js +3 -1
  18. package/out/remote-resolver.js.map +1 -1
  19. package/out/rerank.d.ts +30 -10
  20. package/out/rerank.d.ts.map +1 -1
  21. package/out/rerank.js +2 -2
  22. package/out/rerank.js.map +1 -1
  23. package/out/resolve.d.ts.map +1 -1
  24. package/out/resolve.js +29 -410
  25. package/out/resolve.js.map +1 -1
  26. package/out/span-rescore.d.ts +18 -6
  27. package/out/span-rescore.d.ts.map +1 -1
  28. package/out/span-rescore.js +13 -6
  29. package/out/span-rescore.js.map +1 -1
  30. package/out/street-evidence.d.ts +30 -10
  31. package/out/street-evidence.d.ts.map +1 -1
  32. package/out/street-evidence.js +8 -6
  33. package/out/street-evidence.js.map +1 -1
  34. package/out/street-tier.d.ts +39 -0
  35. package/out/street-tier.d.ts.map +1 -0
  36. package/out/street-tier.js +415 -0
  37. package/out/street-tier.js.map +1 -0
  38. package/package.json +4 -4
  39. package/plausibility.ts +51 -9
  40. package/remote-resolver.ts +23 -7
  41. package/rerank.ts +37 -12
  42. package/resolve.ts +80 -481
  43. package/span-rescore.ts +33 -11
  44. package/street-evidence.ts +36 -15
  45. package/street-tier.ts +498 -0
package/resolve.ts CHANGED
@@ -30,7 +30,9 @@ import {
30
30
  } from "@mailwoman/core/resolver"
31
31
  import { haversineKm } from "@mailwoman/spatial"
32
32
 
33
+ import { foldName } from "./fold-name.ts"
33
34
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.ts"
35
+ import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.ts"
34
36
 
35
37
  /**
36
38
  * Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
@@ -52,26 +54,38 @@ interface ResolutionState {
52
54
  * can inject postcode-proximal locality candidates.
53
55
  */
54
56
  postcode?: string
55
- /** Proximity-bias points (viewport, user location) — forwarded to every primary lookup. */
57
+ /**
58
+ * Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
59
+ */
56
60
  bias?: Array<{ lat: number; lon: number; weight?: number }>
57
- /** Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default). */
61
+ /**
62
+ * Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default).
63
+ */
58
64
  anchorPosterior?: Record<string, number>
59
- /** Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set. */
65
+ /**
66
+ * Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
67
+ */
60
68
  anchorWeight: number
61
69
  /**
62
70
  * #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
63
71
  */
64
72
  hardCountry?: string
65
- /** Dual-role hierarchy completion (#405). Off by default → byte-stable. */
73
+ /**
74
+ * Dual-role hierarchy completion (#405). Off by default → byte-stable.
75
+ */
66
76
  hierarchyCompletion: boolean
67
- /** Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable. */
77
+ /**
78
+ * Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
79
+ */
68
80
  includeAncestors: boolean
69
81
  /**
70
82
  * Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
71
83
  * fires when the parser emitted no locality at all, never to override one.
72
84
  */
73
85
  localityNodePresent: boolean
74
- /** The first region that resolved (its place — for the coincident-roles lookup). */
86
+ /**
87
+ * The first region that resolved (its place — for the coincident-roles lookup).
88
+ */
75
89
  resolvedRegion: ResolvedPlace | null
76
90
  /**
77
91
  * The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
@@ -87,9 +101,10 @@ interface ResolutionState {
87
101
  * population AND distance) ABSTAINS rather than guess.
88
102
  */
89
103
  function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
90
- if (candidates.length === 0) return null
104
+ if (!candidates.length) return null
91
105
 
92
106
  if (candidates.length === 1) return candidates[0]!
107
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
93
108
  const ranked = [...candidates].sort((a, b) => b.population - a.population || a.distanceKm - b.distanceKm)
94
109
  const [first, second] = ranked
95
110
 
@@ -105,476 +120,16 @@ function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLo
105
120
  function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
106
121
  const stack = [...roots]
107
122
 
108
- while (stack.length > 0) {
123
+ while (stack.length) {
109
124
  const n = stack.pop()!
110
125
 
111
- if (n.tag === "postcode" && n.value.trim().length > 0) return n.value.trim()
126
+ if (n.tag === "postcode" && n.value.trim().length) return n.value.trim()
112
127
  stack.push(...n.children)
113
128
  }
114
129
 
115
130
  return undefined
116
131
  }
117
132
 
118
- /** Street-name component tags that, with the street node itself, reconstruct the full street string. */
119
- const STREET_NAME_TAGS = new Set(["street", "street_prefix", "street_prefix_particle", "street_suffix"])
120
-
121
- /**
122
- * Reassemble the full street string from the street node's subtree (#483 coverage fix). The parser nests the
123
- * directional/suffix as `street_prefix`/`street_suffix` CHILDREN of `street` (containment.ts), so `street.value` alone
124
- * is the bare base name ("Sheldon" for "East Sheldon Rd") — which misses the coordinate shards keyed on the FULL
125
- * normalized name. Collect street + its prefix/particle/suffix descendants (NOT house_number/unit, which also nest
126
- * under street), order by span offset, and join.
127
- */
128
- function assembleStreetValue(streetNode: AddressNode, directionalUnit?: AddressNode): string {
129
- const parts: AddressNode[] = []
130
- const stack = [streetNode]
131
-
132
- while (stack.length > 0) {
133
- const n = stack.pop()!
134
-
135
- if (STREET_NAME_TAGS.has(n.tag) && n.value.trim()) {
136
- parts.push(n)
137
- }
138
- stack.push(...n.children)
139
- }
140
-
141
- // #718 admin-tail: a directional quadrant the model mis-tagged `unit` ("1532 Taylor Street NE" →
142
- // [unit] "NE") folds back into the street key by span order, so the situs/interp lookup matches the
143
- // shard's "taylor street northeast" (the lookup normalizer expands the abbreviation). Lookup-key
144
- // only — the parse output and admin resolution are untouched. Byte-stable when absent (undefined).
145
- if (directionalUnit && directionalUnit.value.trim()) {
146
- parts.push(directionalUnit)
147
- }
148
- parts.sort((a, b) => a.start - b.start)
149
-
150
- return parts.map((n) => n.value.trim()).join(" ")
151
- }
152
-
153
- /**
154
- * Directional quadrant values the model sometimes emits as a `unit` node instead of inside the street subtree (#718
155
- * admin-tail diagnostic: ~19% of the admin-fallback tail, 83% of DC). Folded into the street lookup key by
156
- * {@link assembleStreetValue}; the situs/interp lookup normalizer expands the abbreviation ("ne" → "northeast") so the
157
- * shard's full street name matches.
158
- */
159
- // The 8 USPS cardinals/intercardinals (abbrev or name) — @codex/us owns the canonical table (#215).
160
- const isDirectionalUnit = (value: string): boolean => isStreetDirectionalToken(value.replace(/\./g, ""))
161
-
162
- /**
163
- * Address-point tier (#476): find `street` + `house_number` in the tree (first occurrence, depth-first), scope by the
164
- * tree's postcode/locality values, and on an exact hit stamp the point onto the STREET node's metadata. Additive only —
165
- * admin resolution is never altered.
166
- */
167
- /**
168
- * Half-width (degrees) of the bbox derived from a resolved locality centroid for the #247 OSM bbox fall-through. ~0.25°
169
- * ≈ 28 km N–S — generous enough for a large metro whose centroid sits off the queried point, while the EXACT `(street,
170
- * number)` match keeps a cross-commune collision rare. The proper fix is per-point scope backfill (the OSM association
171
- * / point-in-polygon pass, #250); this is the coverage stopgap until then.
172
- */
173
- const LOCALITY_BBOX_RADIUS_DEG = 0.25
174
-
175
- function applyAddressPoint(roots: AddressNode[], lookup: AddressPointLookup, bboxFallback?: boolean): void {
176
- let street: AddressNode | undefined
177
- let houseNumber: AddressNode | undefined
178
- let directionalUnit: AddressNode | undefined
179
- let localityNode: AddressNode | undefined
180
- let locality: string | undefined
181
- let postcode: string | undefined
182
- const stack = [...roots]
183
-
184
- while (stack.length > 0) {
185
- const n = stack.pop()!
186
-
187
- if (n.tag === "street" && !street) {
188
- street = n
189
- }
190
-
191
- if (n.tag === "house_number" && !houseNumber) {
192
- houseNumber = n
193
- }
194
-
195
- if (n.tag === "unit" && !directionalUnit && isDirectionalUnit(n.value)) {
196
- directionalUnit = n
197
- }
198
-
199
- if (n.tag === "locality" && !localityNode && n.value.trim()) {
200
- localityNode = n
201
- locality = n.value.trim()
202
- }
203
-
204
- if (n.tag === "postcode" && !postcode && n.value.trim()) {
205
- postcode = n.value.trim()
206
- }
207
- stack.push(...n.children)
208
- }
209
-
210
- if (!street || !houseNumber) return
211
-
212
- // #247 OSM bbox fall-through: when enabled (an OSM shard is wired) and the locality resolved to a
213
- // coordinate, scope a final `(street, number)` probe by the locality's box — recovering OSM points that
214
- // carry no postcode/locality tag of their own. US situs never enables it, so its probes are byte-identical.
215
- let bbox: { minLat: number; maxLat: number; minLon: number; maxLon: number } | undefined
216
-
217
- if (bboxFallback && localityNode?.lat != null && localityNode.lon != null) {
218
- bbox = {
219
- minLat: localityNode.lat - LOCALITY_BBOX_RADIUS_DEG,
220
- maxLat: localityNode.lat + LOCALITY_BBOX_RADIUS_DEG,
221
- minLon: localityNode.lon - LOCALITY_BBOX_RADIUS_DEG,
222
- maxLon: localityNode.lon + LOCALITY_BBOX_RADIUS_DEG,
223
- }
224
- }
225
-
226
- const hit = lookup.find({
227
- street: assembleStreetValue(street, directionalUnit),
228
- number: houseNumber.value,
229
- postcode,
230
- locality,
231
- bbox,
232
- })
233
-
234
- if (!hit) return
235
- street.metadata = {
236
- ...street.metadata,
237
- address_point: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
238
- resolution_tier: "address_point",
239
- }
240
- }
241
-
242
- /**
243
- * House-number interpolation tier (#483): the third rung, consulted ONLY when the exact address-point tier
244
- * ({@link applyAddressPoint}) did NOT already stamp the street node (`resolution_tier === "address_point"`). That gate
245
- * IS the "after the exact-point fall-through" — an estimate never overwrites a real situs point. Postcode-scoped (no
246
- * locality — the interpolators abstain statewide without a postcode). Stamps a DISTINCT metadata key
247
- * (`interpolated_point`, never `address_point`). Additive only — admin resolution is untouched.
248
- */
249
- function applyInterpolation(roots: AddressNode[], lookup: InterpolationLookup, radiusCalibration?: number): void {
250
- let street: AddressNode | undefined
251
- let houseNumber: AddressNode | undefined
252
- let directionalUnit: AddressNode | undefined
253
- let postcode: string | undefined
254
- const stack = [...roots]
255
-
256
- while (stack.length > 0) {
257
- const n = stack.pop()!
258
-
259
- if (n.tag === "street" && !street) {
260
- street = n
261
- }
262
-
263
- if (n.tag === "house_number" && !houseNumber) {
264
- houseNumber = n
265
- }
266
-
267
- if (n.tag === "unit" && !directionalUnit && isDirectionalUnit(n.value)) {
268
- directionalUnit = n
269
- }
270
-
271
- if (n.tag === "postcode" && !postcode && n.value.trim()) {
272
- postcode = n.value.trim()
273
- }
274
- stack.push(...n.children)
275
- }
276
-
277
- if (!street || !houseNumber) return
278
-
279
- // The fall-through gate: an exact situs point already won — never override it with an estimate.
280
- if (street.metadata?.["resolution_tier"] === "address_point") return
281
- const hit = lookup.find({ street: assembleStreetValue(street, directionalUnit), number: houseNumber.value, postcode })
282
-
283
- if (!hit) return
284
- // Conformal-calibrated radius when the caller supplies a multiplier (#374): the raw half-segment
285
- // heuristic underestimates the true spread (~72% coverage on Travis); ×1.70 → a 90% bound. Default
286
- // (no multiplier) keeps the raw value, byte-stable. Preserve the raw radius for transparency.
287
- const calibrated = radiusCalibration ? Math.round(hit.uncertaintyM * radiusCalibration) : hit.uncertaintyM
288
- street.metadata = {
289
- ...street.metadata,
290
- interpolated_point: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
291
- resolution_tier: "interpolated",
292
- uncertainty_m: calibrated,
293
- ...(radiusCalibration ? { uncertainty_raw_m: hit.uncertaintyM, uncertainty_calibration: radiusCalibration } : {}),
294
- interpolation_method: hit.method,
295
- ...(hit.parityMatched !== undefined ? { parity_matched: hit.parityMatched } : {}),
296
- ...(hit.bracket !== undefined ? { interpolation_bracket: hit.bracket } : {}),
297
- }
298
- }
299
-
300
- /**
301
- * French thoroughfare (voie) type tokens — the leading word that marks a street-only span as a THOROUGHFARE rather than
302
- * a place name ("Place Bellecour", "Cours de l'Intendance", "Quai des Bateliers"). Used by the #1042 street-centroid
303
- * tier to recognize a thoroughfare that the model mis-parsed as a `locality` (the FR no-street class, #901).
304
- * Deliberately generous — a false positive simply misses the exact street-centroid lookup and no-ops; the lookup is the
305
- * real gate.
306
- */
307
- const FR_VOIE_TYPES: ReadonlySet<string> = new Set([
308
- "rue",
309
- "ruelle",
310
- "venelle",
311
- "avenue",
312
- "av",
313
- "ave",
314
- "boulevard",
315
- "bd",
316
- "bld",
317
- "bvd",
318
- "boul",
319
- "place",
320
- "pl",
321
- "cours",
322
- "quai",
323
- "impasse",
324
- "imp",
325
- "allee",
326
- "all",
327
- "chemin",
328
- "ch",
329
- "che",
330
- "passage",
331
- "pas",
332
- "square",
333
- "sq",
334
- "faubourg",
335
- "fg",
336
- "fbg",
337
- "route",
338
- "rte",
339
- "esplanade",
340
- "promenade",
341
- "sentier",
342
- "sente",
343
- "villa",
344
- "cite",
345
- "hameau",
346
- "montee",
347
- "chaussee",
348
- "traverse",
349
- "mail",
350
- "clos",
351
- "voie",
352
- "quartier",
353
- "lotissement",
354
- "residence",
355
- "rond",
356
- ])
357
-
358
- /** Fold to lower-case, diacritic-stripped, punctuation-free tokens — mirrors `street-normalize.ts`'s `fold`. */
359
- function foldVoieTokens(s: string): string[] {
360
- return s
361
- .normalize("NFKD")
362
- .replace(/[̀-ͯ]/g, "")
363
- .toLowerCase()
364
- .replace(/[.,'’]/g, "")
365
- .replace(/-/g, " ")
366
- .split(/\s+/)
367
- .filter(Boolean)
368
- }
369
-
370
- /** Does a string START with a French thoroughfare type token ("Rue …", "Place …")? */
371
- function isVoieShaped(s: string): boolean {
372
- const first = foldVoieTokens(s)[0]
373
-
374
- return first !== undefined && FR_VOIE_TYPES.has(first)
375
- }
376
-
377
- /** Push `v` (trimmed, non-empty, deduped, capped) onto `list`. */
378
- function pushCandidate(list: string[], v: string | undefined, cap: number): void {
379
- const t = v?.trim()
380
-
381
- if (t && list.length < cap && !list.includes(t)) {
382
- list.push(t)
383
- }
384
- }
385
-
386
- /**
387
- * Street-centroid tier (#1042): the street-level rung BELOW the exact/interpolation tiers and ABOVE admin-centroid
388
- * resolution. For a STREET-ONLY query (a thoroughfare with NO house number), stamp the street's centroid onto a
389
- * `street` node so a consumer gets a street-level coordinate instead of the commune centroid (or a wrong namesake).
390
- *
391
- * The FR no-street class mis-parses the thoroughfare — "Place Bellecour, Lyon" parses `region=Lyon`, `locality="Place
392
- * Bellecour"`; "Avenue des Champs-Élysées" truncates — so this recovers the thoroughfare + commune RAW-TEXT-first (the
393
- * same substrate as span-rescore), preferring parsed nodes and falling back to the comma-split raw query. A
394
- * thoroughfare is recognized by its leading voie type ({@link isVoieShaped}); the commune is any non-voie span. Every
395
- * (thoroughfare, commune) pair is probed against the exact street-centroid lookup, first hit wins — a false candidate
396
- * simply misses. Additive only: fires ONLY when no house number is present (rooftop tiers untouched) and no
397
- * street-level coordinate already resolved, and never alters admin resolution.
398
- */
399
- function applyStreetCentroid(
400
- roots: AddressNode[],
401
- raw: string,
402
- provider: (country: string) => StreetCentroidLookup | undefined,
403
- hints: readonly string[]
404
- ): void {
405
- let streetNode: AddressNode | undefined
406
- let houseNumber = false
407
- let postcode: string | undefined
408
- const adminValues: string[] = [] // region / locality values, in tree order (thoroughfare and commune both hide here)
409
- const resolvedCountries: string[] = [] // countries the tree actually resolved to — a post-resolution country hint
410
- const stack = [...roots]
411
-
412
- while (stack.length > 0) {
413
- const n = stack.pop()!
414
-
415
- if (n.tag === "house_number") {
416
- houseNumber = true
417
- }
418
-
419
- if (n.tag === "street" && !streetNode) {
420
- streetNode = n
421
- }
422
-
423
- // Never shadow a real street-level coordinate the exact/interp tiers already stamped.
424
- if (n.metadata?.["resolution_tier"] === "address_point" || n.metadata?.["resolution_tier"] === "interpolated") {
425
- return
426
- }
427
-
428
- if (!postcode && n.tag === "postcode" && n.value.trim()) {
429
- postcode = n.value.trim()
430
- }
431
-
432
- if ((n.tag === "region" || n.tag === "locality" || n.tag === "dependent_locality") && n.value.trim()) {
433
- adminValues.push(n.value.trim())
434
- }
435
- const rc = (n.metadata?.["resolver_country"] as string | undefined)?.trim().toLowerCase()
436
-
437
- if (rc && !resolvedCountries.includes(rc)) {
438
- resolvedCountries.push(rc)
439
- }
440
- stack.push(...n.children)
441
- }
442
-
443
- if (houseNumber) return // street-only tier — a numbered address is the rooftop tiers' job
444
-
445
- // Candidate countries: pre-resolution hints (defaultCountry + ungated placer) then the resolved countries. BAN is
446
- // FR-only, so a non-FR candidate simply yields no lookup; the exact (street, base-commune) match is the real filter.
447
- const countries: string[] = []
448
-
449
- for (const c of [...hints, ...resolvedCountries]) {
450
- const cc = c?.trim().toLowerCase()
451
-
452
- if (cc && !countries.includes(cc)) {
453
- countries.push(cc)
454
- }
455
- }
456
- const lookups = countries.map((c) => provider(c)).filter((l): l is StreetCentroidLookup => l != null)
457
-
458
- if (lookups.length === 0) return
459
-
460
- const rawSegments = raw
461
- .split(",")
462
- .map((s) => s.trim())
463
- .filter(Boolean)
464
- const CAP = 5
465
-
466
- // Thoroughfare candidates (parsed-first, then raw): the assembled street node, any voie-shaped parsed value, any
467
- // voie-shaped raw comma-segment. The parse often truncates these (Champs-Élysées → "Avenue des Champs"), so the raw
468
- // segment is the recovery — a candidate that misses just advances to the next.
469
- const thoroughfares: string[] = []
470
-
471
- if (streetNode) {
472
- pushCandidate(thoroughfares, assembleStreetValue(streetNode), CAP)
473
- }
474
-
475
- for (const v of adminValues) {
476
- if (isVoieShaped(v)) {
477
- pushCandidate(thoroughfares, v, CAP)
478
- }
479
- }
480
-
481
- for (const s of rawSegments) {
482
- if (isVoieShaped(s)) {
483
- pushCandidate(thoroughfares, s, CAP)
484
- }
485
- }
486
-
487
- if (thoroughfares.length === 0) return
488
-
489
- // Commune candidates: non-voie parsed admin values, then non-voie raw segments (a truncated/garbled parse loses the
490
- // commune — "Rue de la République, Marseille" parses `locality="e"` — so the raw "Marseille" is the recovery).
491
- const communes: string[] = []
492
-
493
- for (const v of adminValues) {
494
- if (!isVoieShaped(v)) {
495
- pushCandidate(communes, v, CAP)
496
- }
497
- }
498
-
499
- for (const s of rawSegments) {
500
- if (!isVoieShaped(s) && !thoroughfares.includes(s)) {
501
- pushCandidate(communes, s, CAP)
502
- }
503
- }
504
-
505
- for (const lookup of lookups) {
506
- for (const street of thoroughfares) {
507
- let hit = postcode ? lookup.find({ street, postcode }) : null
508
- let matchedCommune: string | undefined
509
-
510
- for (let i = 0; !hit && i < communes.length; i++) {
511
- hit = lookup.find({ street, locality: communes[i]! })
512
-
513
- if (hit) {
514
- matchedCommune = communes[i]
515
- }
516
- }
517
-
518
- if (!hit) continue
519
-
520
- const target =
521
- streetNode ??
522
- (() => {
523
- const injected: AddressNode = {
524
- tag: "street",
525
- value: street,
526
- start: 0,
527
- end: 0,
528
- confidence: 0.5,
529
- children: [],
530
- }
531
- roots.push(injected)
532
-
533
- return injected
534
- })()
535
- target.metadata = {
536
- ...target.metadata,
537
- street_centroid: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
538
- resolution_tier: "street",
539
- uncertainty_m: hit.uncertaintyM,
540
- }
541
-
542
- // #1058: a commune-scoped hit is REGISTER evidence of the street's locality — record it for
543
- // the geocode layer's locality/city decoration, and drop any span-rescored locality that
544
- // contradicts it. Span-rescore injects SPECULATIVELY (a low-confidence street prefix like
545
- // "Rue" exact-matches the commune Rue in Somme); the register's exact (street, commune)
546
- // match is strictly stronger, so the injected token-of-the-street must not survive as the
547
- // result's city.
548
- if (matchedCommune) {
549
- target.metadata = { ...target.metadata, street_locality: matchedCommune }
550
-
551
- for (let i = roots.length - 1; i >= 0; i--) {
552
- const n = roots[i]!
553
-
554
- if (n.tag !== "locality" || n.metadata?.["span_rescore"] !== true) continue
555
- const names = [n.value, (n.metadata?.["resolver_name"] as string | undefined) ?? ""]
556
-
557
- if (!names.some((name) => foldName(name) === foldName(matchedCommune))) {
558
- roots.splice(i, 1)
559
- }
560
- }
561
- }
562
-
563
- return
564
- }
565
- }
566
- }
567
-
568
- /** Case/diacritic-insensitive fold for commune-name comparison (#1058) — mirrors span-rescore's `norm`. */
569
- function foldName(s: string): string {
570
- return s
571
- .toLowerCase()
572
- .normalize("NFD")
573
- .replace(/[^a-z0-9 ]/g, " ")
574
- .replace(/\s+/g, " ")
575
- .trim()
576
- }
577
-
578
133
  /**
579
134
  * Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
580
135
  * brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
@@ -620,6 +175,7 @@ async function applySpanRescore(
620
175
  }
621
176
 
622
177
  if (!hit) return
178
+
623
179
  const node: AddressNode = {
624
180
  tag: "locality",
625
181
  value: hit.text,
@@ -629,6 +185,7 @@ async function applySpanRescore(
629
185
  confidence: 0.5,
630
186
  children: [],
631
187
  }
188
+
632
189
  decorateNode(node, hit.place, [])
633
190
  // `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
634
191
  // calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
@@ -675,7 +232,9 @@ async function recoverPostcodeNode(
675
232
  }
676
233
  }
677
234
 
678
- /** A resolved node carries a real coordinate (placeID set + non-zero lat/lon). */
235
+ /**
236
+ * A resolved node carries a real coordinate (placeID set + non-zero lat/lon).
237
+ */
679
238
  function isResolvedWithCoord(n: AddressNode): boolean {
680
239
  return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
681
240
  }
@@ -704,13 +263,15 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
704
263
  let anchor: { lat: number; lon: number } | null = null
705
264
  const findAnchor: AddressNode[] = [...roots]
706
265
 
707
- while (findAnchor.length > 0) {
266
+ while (findAnchor.length) {
708
267
  const n = findAnchor.pop()!
709
268
 
710
269
  if (n.tag === "postcode" && isResolvedWithCoord(n)) {
711
270
  anchor = { lat: n.lat!, lon: n.lon! }
271
+
712
272
  break
713
273
  }
274
+
714
275
  findAnchor.push(...n.children)
715
276
  }
716
277
 
@@ -718,7 +279,7 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
718
279
 
719
280
  const stack: AddressNode[] = [...roots]
720
281
 
721
- while (stack.length > 0) {
282
+ while (stack.length) {
722
283
  const node = stack.pop()!
723
284
  stack.push(...node.children)
724
285
 
@@ -730,10 +291,12 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
730
291
  // typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
731
292
  // `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
732
293
  const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
294
+
733
295
  const reconciling = alts
734
296
  .filter((a) => a.lat !== 0 || a.lon !== 0)
735
297
  .map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
736
298
  .filter((x) => x.d <= gateKm)
299
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
737
300
  .sort((x, y) => x.d - y.d)[0]
738
301
 
739
302
  if (reconciling) {
@@ -747,11 +310,14 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
747
310
  lon: node.lon!,
748
311
  score: 0,
749
312
  }
313
+
750
314
  const rest = alts.filter((a) => a !== reconciling.a)
751
315
  decorateNode(node, reconciling.a, [displaced, ...rest])
752
316
  node.metadata = { ...node.metadata, postcode_repicked: true }
317
+
753
318
  continue
754
319
  }
320
+
755
321
  // No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
756
322
  node.lat = anchor.lat
757
323
  node.lon = anchor.lon
@@ -779,7 +345,7 @@ async function applyAdminCoherence(roots: readonly AddressNode[], backend: Resol
779
345
  regionHere &&
780
346
  (node.tag === "locality" || node.tag === "dependent_locality") &&
781
347
  !isResolvedWithCoord(node) &&
782
- node.value.trim().length > 0
348
+ node.value.trim().length
783
349
  ) {
784
350
  await reconcileAdminPair(regionHere, node, backend)
785
351
  }
@@ -824,6 +390,7 @@ async function reconcileAdminPair(
824
390
  parentID: region.id,
825
391
  limit: 3,
826
392
  })
393
+
827
394
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
828
395
 
829
396
  if (lc) {
@@ -832,12 +399,15 @@ async function reconcileAdminPair(
832
399
  region,
833
400
  regionCands.filter((r) => r !== region)
834
401
  )
402
+
835
403
  regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
404
+
836
405
  decorateNode(
837
406
  localityNode,
838
407
  lc,
839
408
  scoped.filter((l) => l !== lc)
840
409
  )
410
+
841
411
  localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
842
412
 
843
413
  return
@@ -860,16 +430,19 @@ async function reconcileAdminPair(
860
430
  parentID: country.id,
861
431
  limit: 3,
862
432
  })
433
+
863
434
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
864
435
 
865
436
  if (lc) {
866
437
  decorateNode(regionNode, country, regionCands)
867
438
  regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
439
+
868
440
  decorateNode(
869
441
  localityNode,
870
442
  lc,
871
443
  scoped.filter((l) => l !== lc)
872
444
  )
445
+
873
446
  localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
874
447
 
875
448
  return
@@ -894,6 +467,7 @@ async function reconcileAdminPair(
894
467
  country: mc.iso2,
895
468
  limit: 3,
896
469
  })
470
+
897
471
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
898
472
 
899
473
  if (lc) {
@@ -902,6 +476,7 @@ async function reconcileAdminPair(
902
476
  lc,
903
477
  scoped.filter((l) => l !== lc)
904
478
  )
479
+
905
480
  localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
906
481
  // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
907
482
  // already decorated the region node with the US-state namesake. Revert that stale decoration so the
@@ -935,8 +510,10 @@ function revertResolverDecoration(node: AddressNode): void {
935
510
  "resolution_quality",
936
511
  "postcode_city_mismatch",
937
512
  ]) {
513
+ // oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record; the object is not on a hot path
938
514
  delete meta[key]
939
515
  }
516
+
940
517
  node.metadata = meta
941
518
  node.lat = undefined
942
519
  node.lon = undefined
@@ -964,7 +541,7 @@ function revertResolverDecoration(node: AddressNode): void {
964
541
  */
965
542
  async function applyExplicitCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
966
543
  const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
967
- const countryHere = node.tag === "country" && node.value.trim().length > 0 ? node : countryToken
544
+ const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken
968
545
  const regionHere = regionAbove || node.tag === "region" || node.tag === "subregion"
969
546
 
970
547
  // Fire only when the explicit country is the locality's NEAREST admin context (no region/subregion between).
@@ -1010,6 +587,7 @@ async function reconcileExplicitCountry(
1010
587
  country: mc.iso2,
1011
588
  limit: 3,
1012
589
  })
590
+
1013
591
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
1014
592
 
1015
593
  if (!lc) return
@@ -1022,6 +600,7 @@ async function reconcileExplicitCountry(
1022
600
  lc,
1023
601
  scoped.filter((l) => l !== lc)
1024
602
  )
603
+
1025
604
  localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true }
1026
605
  }
1027
606
 
@@ -1070,7 +649,7 @@ async function applyRegionCountryCoherence(
1070
649
  regionHere &&
1071
650
  !isResolvedWithCoord(regionHere) &&
1072
651
  (node.tag === "locality" || node.tag === "dependent_locality") &&
1073
- node.value.trim().length > 0
652
+ node.value.trim().length
1074
653
  ) {
1075
654
  await reconcileRegionCountry(regionHere, node, backend, defaultCountry)
1076
655
  }
@@ -1120,6 +699,7 @@ async function reconcileRegionCountry(
1120
699
  country: sub.country,
1121
700
  limit: 3,
1122
701
  })
702
+
1123
703
  const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0))
1124
704
 
1125
705
  if (!rc) return
@@ -1132,6 +712,7 @@ async function reconcileRegionCountry(
1132
712
  country: sub.country,
1133
713
  limit: 3,
1134
714
  })
715
+
1135
716
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
1136
717
 
1137
718
  if (!lc) return
@@ -1142,20 +723,29 @@ async function reconcileRegionCountry(
1142
723
  rc,
1143
724
  regionScoped.filter((r) => r !== rc)
1144
725
  )
726
+
1145
727
  regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true }
728
+
1146
729
  decorateNode(
1147
730
  localityNode,
1148
731
  lc,
1149
732
  scoped.filter((l) => l !== lc)
1150
733
  )
734
+
1151
735
  localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true }
1152
736
  }
1153
737
 
1154
738
  class WOFResolver implements Resolver {
1155
739
  readonly #backend: ResolverBackend
740
+ /**
741
+ * The gazetteer artifact's self-declared coverage facts, passed through from the backend so pipeline-level consumers
742
+ * read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
743
+ */
744
+ readonly artifactCoverage: Resolver["artifactCoverage"]
1156
745
 
1157
746
  constructor(backend: ResolverBackend) {
1158
747
  this.#backend = backend
748
+ this.artifactCoverage = backend.artifactCoverage
1159
749
  }
1160
750
 
1161
751
  async resolveTree(tree: AddressTree, opts: ResolveOpts = {}): Promise<AddressTree> {
@@ -1171,7 +761,7 @@ class WOFResolver implements Resolver {
1171
761
  postcode: firstPostcodeValue(tree.roots),
1172
762
  bias: opts.bias,
1173
763
  anchorPosterior: opts.anchorPosterior,
1174
- anchorWeight: opts.anchorWeight ?? 2.0,
764
+ anchorWeight: opts.anchorWeight ?? 2,
1175
765
  hardCountry: opts.hardCountry,
1176
766
  // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
1177
767
  // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
@@ -1271,6 +861,7 @@ class WOFResolver implements Resolver {
1271
861
  const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
1272
862
 
1273
863
  if (!loc) return
864
+
1274
865
  const interpretation: Interpretation = {
1275
866
  tag: "locality",
1276
867
  placeID: `wof:${loc.id}`,
@@ -1280,6 +871,7 @@ class WOFResolver implements Resolver {
1280
871
  confidence: 0,
1281
872
  metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
1282
873
  }
874
+
1283
875
  regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
1284
876
  }
1285
877
 
@@ -1295,9 +887,10 @@ class WOFResolver implements Resolver {
1295
887
  if (placetype === "locality") {
1296
888
  state.localityNodePresent = true
1297
889
  }
890
+
1298
891
  let resolved: ResolvedPlace | null = null
1299
892
 
1300
- if (placetype && state.lookupsRemaining > 0 && node.value.trim().length > 0) {
893
+ if (placetype && state.lookupsRemaining > 0 && node.value.trim().length) {
1301
894
  const picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
1302
895
 
1303
896
  if (picked) {
@@ -1345,7 +938,7 @@ class WOFResolver implements Resolver {
1345
938
  // Proximity bias (viewport center, user location, …) — a SOFT re-rank the backend folds into
1346
939
  // its exact-tier prominence; never a filter, so recall is untouched. This is how an ambiguous
1347
940
  // bare postcode ("48026") follows the map view instead of a global population coin-flip.
1348
- if (state.bias && state.bias.length > 0) {
941
+ if (state.bias && state.bias.length) {
1349
942
  query.bias = state.bias
1350
943
  }
1351
944
 
@@ -1357,6 +950,7 @@ class WOFResolver implements Resolver {
1357
950
  if (parentResolved && typeof parentResolved.id === "number") {
1358
951
  query.parentID = parentResolved.id
1359
952
  }
953
+
1360
954
  // #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
1361
955
  // placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is gated
1362
956
  // upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
@@ -1370,6 +964,7 @@ class WOFResolver implements Resolver {
1370
964
  // lookup, below a resolved parent's country but above the global defaults. It breaks the two-consistent-
1371
965
  // pairs tie ("Augusta, ME" → Maine, not Augusta/Messina) that pure geographic consistency cannot.
1372
966
  const countryHint = node.metadata?.["country_hint"]
967
+
1373
968
  const country =
1374
969
  parentResolved?.country ??
1375
970
  (typeof countryHint === "string" ? countryHint : undefined) ??
@@ -1398,7 +993,7 @@ class WOFResolver implements Resolver {
1398
993
  // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
1399
994
  // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
1400
995
  // this still can't wander to a foreign place. Same logical resolution → no extra budget.
1401
- if (candidates.length === 0 && state.parentFallback && query.parentID !== undefined) {
996
+ if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
1402
997
  delete query.parentID
1403
998
  candidates = await this.#backend.findPlace(query)
1404
999
  }
@@ -1408,7 +1003,7 @@ class WOFResolver implements Resolver {
1408
1003
  return null
1409
1004
  }
1410
1005
 
1411
- if (candidates.length === 0) return null
1006
+ if (!candidates.length) return null
1412
1007
  // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
1413
1008
  // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
1414
1009
  // postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
@@ -1437,6 +1032,7 @@ class WOFResolver implements Resolver {
1437
1032
  if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
1438
1033
  const post = state.anchorPosterior
1439
1034
  const w = state.anchorWeight
1035
+
1440
1036
  // #928 root cause: this sort's within-tier key was `score + w·posterior` — RAW SCORE order,
1441
1037
  // the exact metric #910 deprecated inside the exact tier as bm25-length-poisoned (a famous
1442
1038
  // place's alias-heavy doc reads ~15 pts WORSE than a tiny namesake's clean one; #905
@@ -1446,6 +1042,7 @@ class WOFResolver implements Resolver {
1446
1042
  // The within-tier key is now the backend's PROMINENCE (population + proximity, #938 units)
1447
1043
  // with the posterior as the additive country pin; score stays the final tiebreak. Backends
1448
1044
  // that don't populate `prominence` degrade to the additive score behavior.
1045
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
1449
1046
  ranked = [...candidates].sort((a, b) => {
1450
1047
  const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
1451
1048
 
@@ -1506,8 +1103,10 @@ function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives:
1506
1103
  if (node.sourceID !== undefined) {
1507
1104
  meta["classifier_source_id"] = node.sourceID
1508
1105
  }
1106
+
1509
1107
  node.metadata = meta
1510
1108
  }
1109
+
1511
1110
  node.source = "resolver"
1512
1111
  node.sourceID = `${resolved.placetype}:${resolved.id}`
1513
1112
  node.lat = resolved.lat
@@ -1540,7 +1139,7 @@ function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives:
1540
1139
  node.metadata["resolution_quality"] = resolved.resolutionQuality
1541
1140
  }
1542
1141
 
1543
- if (alternatives.length > 0) {
1142
+ if (alternatives.length) {
1544
1143
  node.alternatives = alternatives
1545
1144
  }
1546
1145
  }