@mailwoman/resolver 8.1.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.
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,480 +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 (#374): the raw half-segment heuristic underestimates the true spread
285
- // (~72% coverage on Travis); ×1.70 → a 90% bound. The ARTIFACT's own multiplier (read from the shard's
286
- // `interp_calibration` metadata table at open time — `lookup.radiusCalibration`) is the default; an
287
- // explicit caller factor is the @internal instrument override. Neither present (shards predating the
288
- // metadata table, no caller factor) keeps the raw value, byte-stable. Preserve the raw radius for
289
- // transparency.
290
- const factor = radiusCalibration ?? lookup.radiusCalibration
291
- const calibrated = factor ? Math.round(hit.uncertaintyM * factor) : hit.uncertaintyM
292
- street.metadata = {
293
- ...street.metadata,
294
- interpolated_point: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
295
- resolution_tier: "interpolated",
296
- uncertainty_m: calibrated,
297
- ...(factor ? { uncertainty_raw_m: hit.uncertaintyM, uncertainty_calibration: factor } : {}),
298
- interpolation_method: hit.method,
299
- ...(hit.parityMatched !== undefined ? { parity_matched: hit.parityMatched } : {}),
300
- ...(hit.bracket !== undefined ? { interpolation_bracket: hit.bracket } : {}),
301
- }
302
- }
303
-
304
- /**
305
- * French thoroughfare (voie) type tokens — the leading word that marks a street-only span as a THOROUGHFARE rather than
306
- * a place name ("Place Bellecour", "Cours de l'Intendance", "Quai des Bateliers"). Used by the #1042 street-centroid
307
- * tier to recognize a thoroughfare that the model mis-parsed as a `locality` (the FR no-street class, #901).
308
- * Deliberately generous — a false positive simply misses the exact street-centroid lookup and no-ops; the lookup is the
309
- * real gate.
310
- */
311
- const FR_VOIE_TYPES: ReadonlySet<string> = new Set([
312
- "rue",
313
- "ruelle",
314
- "venelle",
315
- "avenue",
316
- "av",
317
- "ave",
318
- "boulevard",
319
- "bd",
320
- "bld",
321
- "bvd",
322
- "boul",
323
- "place",
324
- "pl",
325
- "cours",
326
- "quai",
327
- "impasse",
328
- "imp",
329
- "allee",
330
- "all",
331
- "chemin",
332
- "ch",
333
- "che",
334
- "passage",
335
- "pas",
336
- "square",
337
- "sq",
338
- "faubourg",
339
- "fg",
340
- "fbg",
341
- "route",
342
- "rte",
343
- "esplanade",
344
- "promenade",
345
- "sentier",
346
- "sente",
347
- "villa",
348
- "cite",
349
- "hameau",
350
- "montee",
351
- "chaussee",
352
- "traverse",
353
- "mail",
354
- "clos",
355
- "voie",
356
- "quartier",
357
- "lotissement",
358
- "residence",
359
- "rond",
360
- ])
361
-
362
- /** Fold to lower-case, diacritic-stripped, punctuation-free tokens — mirrors `street-normalize.ts`'s `fold`. */
363
- function foldVoieTokens(s: string): string[] {
364
- return s
365
- .normalize("NFKD")
366
- .replace(/[̀-ͯ]/g, "")
367
- .toLowerCase()
368
- .replace(/[.,'’]/g, "")
369
- .replace(/-/g, " ")
370
- .split(/\s+/)
371
- .filter(Boolean)
372
- }
373
-
374
- /** Does a string START with a French thoroughfare type token ("Rue …", "Place …")? */
375
- function isVoieShaped(s: string): boolean {
376
- const first = foldVoieTokens(s)[0]
377
-
378
- return first !== undefined && FR_VOIE_TYPES.has(first)
379
- }
380
-
381
- /** Push `v` (trimmed, non-empty, deduped, capped) onto `list`. */
382
- function pushCandidate(list: string[], v: string | undefined, cap: number): void {
383
- const t = v?.trim()
384
-
385
- if (t && list.length < cap && !list.includes(t)) {
386
- list.push(t)
387
- }
388
- }
389
-
390
- /**
391
- * Street-centroid tier (#1042): the street-level rung BELOW the exact/interpolation tiers and ABOVE admin-centroid
392
- * resolution. For a STREET-ONLY query (a thoroughfare with NO house number), stamp the street's centroid onto a
393
- * `street` node so a consumer gets a street-level coordinate instead of the commune centroid (or a wrong namesake).
394
- *
395
- * The FR no-street class mis-parses the thoroughfare — "Place Bellecour, Lyon" parses `region=Lyon`, `locality="Place
396
- * Bellecour"`; "Avenue des Champs-Élysées" truncates — so this recovers the thoroughfare + commune RAW-TEXT-first (the
397
- * same substrate as span-rescore), preferring parsed nodes and falling back to the comma-split raw query. A
398
- * thoroughfare is recognized by its leading voie type ({@link isVoieShaped}); the commune is any non-voie span. Every
399
- * (thoroughfare, commune) pair is probed against the exact street-centroid lookup, first hit wins — a false candidate
400
- * simply misses. Additive only: fires ONLY when no house number is present (rooftop tiers untouched) and no
401
- * street-level coordinate already resolved, and never alters admin resolution.
402
- */
403
- function applyStreetCentroid(
404
- roots: AddressNode[],
405
- raw: string,
406
- provider: (country: string) => StreetCentroidLookup | undefined,
407
- hints: readonly string[]
408
- ): void {
409
- let streetNode: AddressNode | undefined
410
- let houseNumber = false
411
- let postcode: string | undefined
412
- const adminValues: string[] = [] // region / locality values, in tree order (thoroughfare and commune both hide here)
413
- const resolvedCountries: string[] = [] // countries the tree actually resolved to — a post-resolution country hint
414
- const stack = [...roots]
415
-
416
- while (stack.length > 0) {
417
- const n = stack.pop()!
418
-
419
- if (n.tag === "house_number") {
420
- houseNumber = true
421
- }
422
-
423
- if (n.tag === "street" && !streetNode) {
424
- streetNode = n
425
- }
426
-
427
- // Never shadow a real street-level coordinate the exact/interp tiers already stamped.
428
- if (n.metadata?.["resolution_tier"] === "address_point" || n.metadata?.["resolution_tier"] === "interpolated") {
429
- return
430
- }
431
-
432
- if (!postcode && n.tag === "postcode" && n.value.trim()) {
433
- postcode = n.value.trim()
434
- }
435
-
436
- if ((n.tag === "region" || n.tag === "locality" || n.tag === "dependent_locality") && n.value.trim()) {
437
- adminValues.push(n.value.trim())
438
- }
439
- const rc = (n.metadata?.["resolver_country"] as string | undefined)?.trim().toLowerCase()
440
-
441
- if (rc && !resolvedCountries.includes(rc)) {
442
- resolvedCountries.push(rc)
443
- }
444
- stack.push(...n.children)
445
- }
446
-
447
- if (houseNumber) return // street-only tier — a numbered address is the rooftop tiers' job
448
-
449
- // Candidate countries: pre-resolution hints (defaultCountry + ungated placer) then the resolved countries. BAN is
450
- // FR-only, so a non-FR candidate simply yields no lookup; the exact (street, base-commune) match is the real filter.
451
- const countries: string[] = []
452
-
453
- for (const c of [...hints, ...resolvedCountries]) {
454
- const cc = c?.trim().toLowerCase()
455
-
456
- if (cc && !countries.includes(cc)) {
457
- countries.push(cc)
458
- }
459
- }
460
- const lookups = countries.map((c) => provider(c)).filter((l): l is StreetCentroidLookup => l != null)
461
-
462
- if (lookups.length === 0) return
463
-
464
- const rawSegments = raw
465
- .split(",")
466
- .map((s) => s.trim())
467
- .filter(Boolean)
468
- const CAP = 5
469
-
470
- // Thoroughfare candidates (parsed-first, then raw): the assembled street node, any voie-shaped parsed value, any
471
- // voie-shaped raw comma-segment. The parse often truncates these (Champs-Élysées → "Avenue des Champs"), so the raw
472
- // segment is the recovery — a candidate that misses just advances to the next.
473
- const thoroughfares: string[] = []
474
-
475
- if (streetNode) {
476
- pushCandidate(thoroughfares, assembleStreetValue(streetNode), CAP)
477
- }
478
-
479
- for (const v of adminValues) {
480
- if (isVoieShaped(v)) {
481
- pushCandidate(thoroughfares, v, CAP)
482
- }
483
- }
484
-
485
- for (const s of rawSegments) {
486
- if (isVoieShaped(s)) {
487
- pushCandidate(thoroughfares, s, CAP)
488
- }
489
- }
490
-
491
- if (thoroughfares.length === 0) return
492
-
493
- // Commune candidates: non-voie parsed admin values, then non-voie raw segments (a truncated/garbled parse loses the
494
- // commune — "Rue de la République, Marseille" parses `locality="e"` — so the raw "Marseille" is the recovery).
495
- const communes: string[] = []
496
-
497
- for (const v of adminValues) {
498
- if (!isVoieShaped(v)) {
499
- pushCandidate(communes, v, CAP)
500
- }
501
- }
502
-
503
- for (const s of rawSegments) {
504
- if (!isVoieShaped(s) && !thoroughfares.includes(s)) {
505
- pushCandidate(communes, s, CAP)
506
- }
507
- }
508
-
509
- for (const lookup of lookups) {
510
- for (const street of thoroughfares) {
511
- let hit = postcode ? lookup.find({ street, postcode }) : null
512
- let matchedCommune: string | undefined
513
-
514
- for (let i = 0; !hit && i < communes.length; i++) {
515
- hit = lookup.find({ street, locality: communes[i]! })
516
-
517
- if (hit) {
518
- matchedCommune = communes[i]
519
- }
520
- }
521
-
522
- if (!hit) continue
523
-
524
- const target =
525
- streetNode ??
526
- (() => {
527
- const injected: AddressNode = {
528
- tag: "street",
529
- value: street,
530
- start: 0,
531
- end: 0,
532
- confidence: 0.5,
533
- children: [],
534
- }
535
- roots.push(injected)
536
-
537
- return injected
538
- })()
539
- target.metadata = {
540
- ...target.metadata,
541
- street_centroid: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
542
- resolution_tier: "street",
543
- uncertainty_m: hit.uncertaintyM,
544
- }
545
-
546
- // #1058: a commune-scoped hit is REGISTER evidence of the street's locality — record it for
547
- // the geocode layer's locality/city decoration, and drop any span-rescored locality that
548
- // contradicts it. Span-rescore injects SPECULATIVELY (a low-confidence street prefix like
549
- // "Rue" exact-matches the commune Rue in Somme); the register's exact (street, commune)
550
- // match is strictly stronger, so the injected token-of-the-street must not survive as the
551
- // result's city.
552
- if (matchedCommune) {
553
- target.metadata = { ...target.metadata, street_locality: matchedCommune }
554
-
555
- for (let i = roots.length - 1; i >= 0; i--) {
556
- const n = roots[i]!
557
-
558
- if (n.tag !== "locality" || n.metadata?.["span_rescore"] !== true) continue
559
- const names = [n.value, (n.metadata?.["resolver_name"] as string | undefined) ?? ""]
560
-
561
- if (!names.some((name) => foldName(name) === foldName(matchedCommune))) {
562
- roots.splice(i, 1)
563
- }
564
- }
565
- }
566
-
567
- return
568
- }
569
- }
570
- }
571
-
572
- /** Case/diacritic-insensitive fold for commune-name comparison (#1058) — mirrors span-rescore's `norm`. */
573
- function foldName(s: string): string {
574
- return s
575
- .toLowerCase()
576
- .normalize("NFD")
577
- .replace(/[^a-z0-9 ]/g, " ")
578
- .replace(/\s+/g, " ")
579
- .trim()
580
- }
581
-
582
133
  /**
583
134
  * Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
584
135
  * brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
@@ -624,6 +175,7 @@ async function applySpanRescore(
624
175
  }
625
176
 
626
177
  if (!hit) return
178
+
627
179
  const node: AddressNode = {
628
180
  tag: "locality",
629
181
  value: hit.text,
@@ -633,6 +185,7 @@ async function applySpanRescore(
633
185
  confidence: 0.5,
634
186
  children: [],
635
187
  }
188
+
636
189
  decorateNode(node, hit.place, [])
637
190
  // `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
638
191
  // calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
@@ -679,7 +232,9 @@ async function recoverPostcodeNode(
679
232
  }
680
233
  }
681
234
 
682
- /** 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
+ */
683
238
  function isResolvedWithCoord(n: AddressNode): boolean {
684
239
  return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
685
240
  }
@@ -708,13 +263,15 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
708
263
  let anchor: { lat: number; lon: number } | null = null
709
264
  const findAnchor: AddressNode[] = [...roots]
710
265
 
711
- while (findAnchor.length > 0) {
266
+ while (findAnchor.length) {
712
267
  const n = findAnchor.pop()!
713
268
 
714
269
  if (n.tag === "postcode" && isResolvedWithCoord(n)) {
715
270
  anchor = { lat: n.lat!, lon: n.lon! }
271
+
716
272
  break
717
273
  }
274
+
718
275
  findAnchor.push(...n.children)
719
276
  }
720
277
 
@@ -722,7 +279,7 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
722
279
 
723
280
  const stack: AddressNode[] = [...roots]
724
281
 
725
- while (stack.length > 0) {
282
+ while (stack.length) {
726
283
  const node = stack.pop()!
727
284
  stack.push(...node.children)
728
285
 
@@ -734,10 +291,12 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
734
291
  // typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
735
292
  // `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
736
293
  const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
294
+
737
295
  const reconciling = alts
738
296
  .filter((a) => a.lat !== 0 || a.lon !== 0)
739
297
  .map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
740
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
741
300
  .sort((x, y) => x.d - y.d)[0]
742
301
 
743
302
  if (reconciling) {
@@ -751,11 +310,14 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
751
310
  lon: node.lon!,
752
311
  score: 0,
753
312
  }
313
+
754
314
  const rest = alts.filter((a) => a !== reconciling.a)
755
315
  decorateNode(node, reconciling.a, [displaced, ...rest])
756
316
  node.metadata = { ...node.metadata, postcode_repicked: true }
317
+
757
318
  continue
758
319
  }
320
+
759
321
  // No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
760
322
  node.lat = anchor.lat
761
323
  node.lon = anchor.lon
@@ -783,7 +345,7 @@ async function applyAdminCoherence(roots: readonly AddressNode[], backend: Resol
783
345
  regionHere &&
784
346
  (node.tag === "locality" || node.tag === "dependent_locality") &&
785
347
  !isResolvedWithCoord(node) &&
786
- node.value.trim().length > 0
348
+ node.value.trim().length
787
349
  ) {
788
350
  await reconcileAdminPair(regionHere, node, backend)
789
351
  }
@@ -828,6 +390,7 @@ async function reconcileAdminPair(
828
390
  parentID: region.id,
829
391
  limit: 3,
830
392
  })
393
+
831
394
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
832
395
 
833
396
  if (lc) {
@@ -836,12 +399,15 @@ async function reconcileAdminPair(
836
399
  region,
837
400
  regionCands.filter((r) => r !== region)
838
401
  )
402
+
839
403
  regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
404
+
840
405
  decorateNode(
841
406
  localityNode,
842
407
  lc,
843
408
  scoped.filter((l) => l !== lc)
844
409
  )
410
+
845
411
  localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
846
412
 
847
413
  return
@@ -864,16 +430,19 @@ async function reconcileAdminPair(
864
430
  parentID: country.id,
865
431
  limit: 3,
866
432
  })
433
+
867
434
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
868
435
 
869
436
  if (lc) {
870
437
  decorateNode(regionNode, country, regionCands)
871
438
  regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
439
+
872
440
  decorateNode(
873
441
  localityNode,
874
442
  lc,
875
443
  scoped.filter((l) => l !== lc)
876
444
  )
445
+
877
446
  localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
878
447
 
879
448
  return
@@ -898,6 +467,7 @@ async function reconcileAdminPair(
898
467
  country: mc.iso2,
899
468
  limit: 3,
900
469
  })
470
+
901
471
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
902
472
 
903
473
  if (lc) {
@@ -906,6 +476,7 @@ async function reconcileAdminPair(
906
476
  lc,
907
477
  scoped.filter((l) => l !== lc)
908
478
  )
479
+
909
480
  localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
910
481
  // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
911
482
  // already decorated the region node with the US-state namesake. Revert that stale decoration so the
@@ -939,8 +510,10 @@ function revertResolverDecoration(node: AddressNode): void {
939
510
  "resolution_quality",
940
511
  "postcode_city_mismatch",
941
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
942
514
  delete meta[key]
943
515
  }
516
+
944
517
  node.metadata = meta
945
518
  node.lat = undefined
946
519
  node.lon = undefined
@@ -968,7 +541,7 @@ function revertResolverDecoration(node: AddressNode): void {
968
541
  */
969
542
  async function applyExplicitCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
970
543
  const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
971
- const countryHere = node.tag === "country" && node.value.trim().length > 0 ? node : countryToken
544
+ const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken
972
545
  const regionHere = regionAbove || node.tag === "region" || node.tag === "subregion"
973
546
 
974
547
  // Fire only when the explicit country is the locality's NEAREST admin context (no region/subregion between).
@@ -1014,6 +587,7 @@ async function reconcileExplicitCountry(
1014
587
  country: mc.iso2,
1015
588
  limit: 3,
1016
589
  })
590
+
1017
591
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
1018
592
 
1019
593
  if (!lc) return
@@ -1026,6 +600,7 @@ async function reconcileExplicitCountry(
1026
600
  lc,
1027
601
  scoped.filter((l) => l !== lc)
1028
602
  )
603
+
1029
604
  localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true }
1030
605
  }
1031
606
 
@@ -1074,7 +649,7 @@ async function applyRegionCountryCoherence(
1074
649
  regionHere &&
1075
650
  !isResolvedWithCoord(regionHere) &&
1076
651
  (node.tag === "locality" || node.tag === "dependent_locality") &&
1077
- node.value.trim().length > 0
652
+ node.value.trim().length
1078
653
  ) {
1079
654
  await reconcileRegionCountry(regionHere, node, backend, defaultCountry)
1080
655
  }
@@ -1124,6 +699,7 @@ async function reconcileRegionCountry(
1124
699
  country: sub.country,
1125
700
  limit: 3,
1126
701
  })
702
+
1127
703
  const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0))
1128
704
 
1129
705
  if (!rc) return
@@ -1136,6 +712,7 @@ async function reconcileRegionCountry(
1136
712
  country: sub.country,
1137
713
  limit: 3,
1138
714
  })
715
+
1139
716
  const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
1140
717
 
1141
718
  if (!lc) return
@@ -1146,12 +723,15 @@ async function reconcileRegionCountry(
1146
723
  rc,
1147
724
  regionScoped.filter((r) => r !== rc)
1148
725
  )
726
+
1149
727
  regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true }
728
+
1150
729
  decorateNode(
1151
730
  localityNode,
1152
731
  lc,
1153
732
  scoped.filter((l) => l !== lc)
1154
733
  )
734
+
1155
735
  localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true }
1156
736
  }
1157
737
 
@@ -1181,7 +761,7 @@ class WOFResolver implements Resolver {
1181
761
  postcode: firstPostcodeValue(tree.roots),
1182
762
  bias: opts.bias,
1183
763
  anchorPosterior: opts.anchorPosterior,
1184
- anchorWeight: opts.anchorWeight ?? 2.0,
764
+ anchorWeight: opts.anchorWeight ?? 2,
1185
765
  hardCountry: opts.hardCountry,
1186
766
  // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
1187
767
  // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
@@ -1281,6 +861,7 @@ class WOFResolver implements Resolver {
1281
861
  const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
1282
862
 
1283
863
  if (!loc) return
864
+
1284
865
  const interpretation: Interpretation = {
1285
866
  tag: "locality",
1286
867
  placeID: `wof:${loc.id}`,
@@ -1290,6 +871,7 @@ class WOFResolver implements Resolver {
1290
871
  confidence: 0,
1291
872
  metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
1292
873
  }
874
+
1293
875
  regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
1294
876
  }
1295
877
 
@@ -1305,9 +887,10 @@ class WOFResolver implements Resolver {
1305
887
  if (placetype === "locality") {
1306
888
  state.localityNodePresent = true
1307
889
  }
890
+
1308
891
  let resolved: ResolvedPlace | null = null
1309
892
 
1310
- if (placetype && state.lookupsRemaining > 0 && node.value.trim().length > 0) {
893
+ if (placetype && state.lookupsRemaining > 0 && node.value.trim().length) {
1311
894
  const picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
1312
895
 
1313
896
  if (picked) {
@@ -1355,7 +938,7 @@ class WOFResolver implements Resolver {
1355
938
  // Proximity bias (viewport center, user location, …) — a SOFT re-rank the backend folds into
1356
939
  // its exact-tier prominence; never a filter, so recall is untouched. This is how an ambiguous
1357
940
  // bare postcode ("48026") follows the map view instead of a global population coin-flip.
1358
- if (state.bias && state.bias.length > 0) {
941
+ if (state.bias && state.bias.length) {
1359
942
  query.bias = state.bias
1360
943
  }
1361
944
 
@@ -1367,6 +950,7 @@ class WOFResolver implements Resolver {
1367
950
  if (parentResolved && typeof parentResolved.id === "number") {
1368
951
  query.parentID = parentResolved.id
1369
952
  }
953
+
1370
954
  // #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
1371
955
  // placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is gated
1372
956
  // upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
@@ -1380,6 +964,7 @@ class WOFResolver implements Resolver {
1380
964
  // lookup, below a resolved parent's country but above the global defaults. It breaks the two-consistent-
1381
965
  // pairs tie ("Augusta, ME" → Maine, not Augusta/Messina) that pure geographic consistency cannot.
1382
966
  const countryHint = node.metadata?.["country_hint"]
967
+
1383
968
  const country =
1384
969
  parentResolved?.country ??
1385
970
  (typeof countryHint === "string" ? countryHint : undefined) ??
@@ -1408,7 +993,7 @@ class WOFResolver implements Resolver {
1408
993
  // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
1409
994
  // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
1410
995
  // this still can't wander to a foreign place. Same logical resolution → no extra budget.
1411
- if (candidates.length === 0 && state.parentFallback && query.parentID !== undefined) {
996
+ if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
1412
997
  delete query.parentID
1413
998
  candidates = await this.#backend.findPlace(query)
1414
999
  }
@@ -1418,7 +1003,7 @@ class WOFResolver implements Resolver {
1418
1003
  return null
1419
1004
  }
1420
1005
 
1421
- if (candidates.length === 0) return null
1006
+ if (!candidates.length) return null
1422
1007
  // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
1423
1008
  // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
1424
1009
  // postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
@@ -1447,6 +1032,7 @@ class WOFResolver implements Resolver {
1447
1032
  if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
1448
1033
  const post = state.anchorPosterior
1449
1034
  const w = state.anchorWeight
1035
+
1450
1036
  // #928 root cause: this sort's within-tier key was `score + w·posterior` — RAW SCORE order,
1451
1037
  // the exact metric #910 deprecated inside the exact tier as bm25-length-poisoned (a famous
1452
1038
  // place's alias-heavy doc reads ~15 pts WORSE than a tiny namesake's clean one; #905
@@ -1456,6 +1042,7 @@ class WOFResolver implements Resolver {
1456
1042
  // The within-tier key is now the backend's PROMINENCE (population + proximity, #938 units)
1457
1043
  // with the posterior as the additive country pin; score stays the final tiebreak. Backends
1458
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
1459
1046
  ranked = [...candidates].sort((a, b) => {
1460
1047
  const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
1461
1048
 
@@ -1516,8 +1103,10 @@ function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives:
1516
1103
  if (node.sourceID !== undefined) {
1517
1104
  meta["classifier_source_id"] = node.sourceID
1518
1105
  }
1106
+
1519
1107
  node.metadata = meta
1520
1108
  }
1109
+
1521
1110
  node.source = "resolver"
1522
1111
  node.sourceID = `${resolved.placetype}:${resolved.id}`
1523
1112
  node.lat = resolved.lat
@@ -1550,7 +1139,7 @@ function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives:
1550
1139
  node.metadata["resolution_quality"] = resolved.resolutionQuality
1551
1140
  }
1552
1141
 
1553
- if (alternatives.length > 0) {
1142
+ if (alternatives.length) {
1554
1143
  node.alternatives = alternatives
1555
1144
  }
1556
1145
  }